From 3845941b7c80198e77b309a65bed0ca788ed3370 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 00:27:23 +0000 Subject: [PATCH 01/82] Add experimental slot-owned MSHV servicing Stage complete per-slot payloads, preserve nested fallback bundles, and preflight peak ESP capacity. Integrate hypervisor failure recovery with an identity-check hook that deliberately assumes success pending follow-up. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/boot/uki.rs | 32 +- .../trident/src/engine/manual_rollback/mod.rs | 2 + .../src/engine/manual_rollback/utils.rs | 26 +- crates/trident/src/engine/mod.rs | 1 + crates/trident/src/engine/mshv.rs | 134 ++++++ crates/trident/src/engine/rollback.rs | 151 ++++++- crates/trident/src/engine/update.rs | 2 + crates/trident/src/init/offline/mod.rs | 2 + crates/trident/src/lib.rs | 29 +- .../src/server/tridentserver/datastore.rs | 7 + crates/trident/src/subsystems/esp.rs | 65 ++- crates/trident/src/subsystems/esp/mshv.rs | 2 + .../trident/src/subsystems/esp/mshv/slot.rs | 386 ++++++++++++++++++ crates/trident_api/src/constants.rs | 3 + crates/trident_api/src/error.rs | 6 + crates/trident_api/src/status.rs | 2 + docs/Explanation/Bootloader-Configuration.md | 25 ++ proto/trident/v1preview/status_service.proto | 2 + 18 files changed, 836 insertions(+), 41 deletions(-) create mode 100644 crates/trident/src/engine/mshv.rs create mode 100644 crates/trident/src/subsystems/esp/mshv/slot.rs diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index e0c1ccf965..62a1b9e74c 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -240,25 +240,33 @@ pub fn cleanup_ukis_before_staging( esp_mount_path: &Path, ) -> Result<(), Error> { let esp_uki_directory = join_relative(mount_point, esp_mount_path).join(UKI_DIRECTORY); + for path in ukis_removed_before_staging(ctx, &esp_uki_directory)? { + debug!("Pre-staging cleanup: removing old UKI '{}'", path.display()); + remove_uki_and_addons(&path)?; + } + Ok(()) +} + +pub(crate) fn ukis_removed_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); } 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). 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()); } } @@ -277,17 +285,13 @@ pub fn cleanup_ukis_before_staging( .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) diff --git a/crates/trident/src/engine/manual_rollback/mod.rs b/crates/trident/src/engine/manual_rollback/mod.rs index 0922676212..b9bb766902 100644 --- a/crates/trident/src/engine/manual_rollback/mod.rs +++ b/crates/trident/src/engine/manual_rollback/mod.rs @@ -149,6 +149,8 @@ pub fn execute_rollback( }; staged_rollback_type = Some(rollback_type); + engine::mshv::validate_transition(&datastore.host_status().spec, &requested_rollback.spec)?; + let engine_context = EngineContext::new(EngineContextParams { spec: requested_rollback.spec.clone(), spec_old: datastore.host_status().spec.clone(), diff --git a/crates/trident/src/engine/manual_rollback/utils.rs b/crates/trident/src/engine/manual_rollback/utils.rs index 04df1db6b1..1edb8c2ba5 100644 --- a/crates/trident/src/engine/manual_rollback/utils.rs +++ b/crates/trident/src/engine/manual_rollback/utils.rs @@ -350,7 +350,8 @@ impl ManualRollbackContext { current_operation.kind = OperationKind::RuntimeManualRollback; current_operation.operation_host_status = Some(current_hs.clone()); } - ServicingState::AbUpdateHealthCheckFailed => { + ServicingState::AbUpdateHealthCheckFailed + | ServicingState::AbUpdateHypervisorCheckFailed => { current_operation.kind = OperationKind::AbUpdateAutoRollback; trace!("Detected AbUpdateAutoRollback operation, ending parsing here."); break; @@ -1024,6 +1025,29 @@ mod tests { rollback_context_testing(&host_status_list, "Validate A/B update health check failed"); } + #[test] + fn test_ab_update_hypervisor_check_failed() { + let host_status_list = vec![ + inter(None, CI_FINAL, MIN), + inter(None, CI_FINAL, MIN), + prov(VOL_A, false, vec![], MIN), + inter(VOL_A, AB_STAGE, MIN), + inter(VOL_A, AB_FINAL, MIN), + inter(VOL_A, ServicingState::AbUpdateHypervisorCheckFailed, MIN), + prov_e( + VOL_A, + false, + vec![], + MIN, + Some("hypervisor failure".to_string()), + ), + ]; + rollback_context_testing( + &host_status_list, + "Validate hypervisor auto-rollback history", + ); + } + #[test] fn test_ab_update_encryption() { let host_status_list = vec![ diff --git a/crates/trident/src/engine/mod.rs b/crates/trident/src/engine/mod.rs index a1bca74146..7d035a6724 100644 --- a/crates/trident/src/engine/mod.rs +++ b/crates/trident/src/engine/mod.rs @@ -40,6 +40,7 @@ mod clean_install; mod context; mod kexec; pub mod manual_rollback; +pub(crate) mod mshv; mod newroot; pub mod provisioning_network; pub mod rollback; diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs new file mode 100644 index 0000000000..39051f6f4b --- /dev/null +++ b/crates/trident/src/engine/mshv.rs @@ -0,0 +1,134 @@ +use log::warn; + +use trident_api::{ + config::HostConfiguration, + constants::internal_params::{MSHV_SLOT_ESP_PAYLOAD, PRESERVE_MSHV_ESP_PAYLOAD}, + error::{InvalidInputError, TridentError}, + status::{AbVolumeSelection, ServicingType}, +}; + +use super::{boot, EngineContext}; + +fn unsupported(reason: &str) -> TridentError { + TridentError::new(InvalidInputError::InvalidInternalParameter { + name: MSHV_SLOT_ESP_PAYLOAD.into(), + explanation: reason.into(), + }) +} + +pub(crate) fn enabled(spec: &HostConfiguration) -> bool { + spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD) +} + +pub(crate) fn validate_transition( + previous: &HostConfiguration, + requested: &HostConfiguration, +) -> Result<(), TridentError> { + if enabled(previous) != enabled(requested) { + return Err(unsupported( + "Changing slot-owned MSHV mode on an existing installation is not supported", + )); + } + Ok(()) +} + +pub(crate) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { + if !enabled(&ctx.spec) { + return Ok(()); + } + if !cfg!(target_arch = "x86_64") || !ctx.image_distro().is_acl() || !ctx.is_uki()? { + return Err(unsupported( + "Slot-owned MSHV requires an x86-64 ACL UKI image", + )); + } + if ctx.is_stream_image { + return Err(unsupported( + "Slot-owned MSHV requires file-based ESP deployment", + )); + } + if ctx.spec.internal_params.get_flag(PRESERVE_MSHV_ESP_PAYLOAD) { + return Err(unsupported( + "Shared-path and slot-owned MSHV modes cannot be combined", + )); + } + if ctx + .spec + .storage + .encryption + .as_ref() + .is_some_and(|encryption| !encryption.pcrs.is_empty()) + { + return Err(unsupported( + "Slot-owned MSHV TPM/PCR-bound encryption is not validated", + )); + } + if ctx.servicing_type != ServicingType::CleanInstall { + validate_transition(&ctx.spec_old, &ctx.spec)?; + } + Ok(()) +} + +pub(crate) fn validate_active_hypervisor( + ctx: &EngineContext, + expected_volume: Option, +) -> Result<(), TridentError> { + if enabled(&ctx.spec) { + let expected_directory = + expected_volume.map(|volume| boot::make_esp_dir_name(ctx.install_index, volume)); + // TODO: Identify the running hypervisor and compare it with the expected OS payload. + // Deliberately assume success until the identity mechanism is implemented. + warn!( + "MSHV hypervisor identity validation is not implemented; assuming success for {:?}", + expected_directory + ); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_mode_changes_but_allows_matching_installation_modes() { + let ordinary = HostConfiguration::default(); + let mut mshv = ordinary.clone(); + mshv.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); + assert!(validate_transition(&ordinary, &mshv).is_err()); + assert!(validate_transition(&mshv, &ordinary).is_err()); + assert!(validate_transition(&ordinary, &ordinary).is_ok()); + assert!(validate_transition(&mshv, &mshv).is_ok()); + } + + #[test] + fn rejects_unsupported_mshv_images_without_affecting_other_images() { + let mut ctx = EngineContext { + is_stream_image: true, + is_uki: Some(true), + servicing_type: ServicingType::CleanInstall, + ..Default::default() + } + .with_image(crate::osimage::mock::MockOsImage { + os_release: osutils::osrelease::OsRelease { + id: Some(osutils::osrelease::AZURE_LINUX_DISTRO_ID.into()), + variant_id: Some(osutils::osrelease::AZURE_CONTAINER_LINUX_VARIANT_ID.into()), + ..Default::default() + }, + is_uki: true, + ..crate::osimage::mock::MockOsImage::new() + }); + assert!(validate_configuration(&ctx).is_ok()); + ctx.spec.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); + assert!(validate_configuration(&ctx).is_err()); + ctx.is_stream_image = false; + assert!(validate_configuration(&ctx).is_ok()); + ctx.spec.storage.encryption = Some(trident_api::config::Encryption { + pcrs: vec![sysdefs::tpm2::Pcr::Pcr4], + ..Default::default() + }); + assert!(validate_configuration(&ctx).is_err()); + ctx.spec.storage.encryption = None; + ctx.spec.internal_params.set_flag(PRESERVE_MSHV_ESP_PAYLOAD); + assert!(validate_configuration(&ctx).is_err()); + } +} diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 1d5947acda..4b8faac8d5 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -34,6 +34,8 @@ pub enum BootValidationResult { ValidBootProvisioned, /// Target OS booted successfully, and the health checks failed ValidBootHealthCheckFailed(TridentError), + /// The trial OS booted, but its hypervisor failed validation and requires rollback. + InvalidHypervisor(TridentError), } /// Validates that the firmware did not perform a rollback, i.e. correctly booted from the updated @@ -53,7 +55,8 @@ 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 - ServicingState::AbUpdateHealthCheckFailed => { + ServicingState::AbUpdateHealthCheckFailed + | ServicingState::AbUpdateHypervisorCheckFailed => { match datastore.host_status().ab_active_volume { Some(AbVolumeSelection::VolumeB) => Some(AbVolumeSelection::VolumeA), Some(AbVolumeSelection::VolumeA) => Some(AbVolumeSelection::VolumeB), @@ -69,17 +72,32 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result { - ServicingType::AbUpdate - } + ServicingState::AbUpdateFinalized + | ServicingState::AbUpdateHealthCheckFailed + | ServicingState::AbUpdateHypervisorCheckFailed => ServicingType::AbUpdate, ServicingState::CleanInstallFinalized => ServicingType::CleanInstall, ServicingState::ManualRollbackAbFinalized => ServicingType::ManualRollbackAb, _ => ServicingType::NoActiveServicing, }; // Create an EngineContext based on the Host Status + if current_servicing_state != ServicingState::CleanInstallFinalized { + super::mshv::validate_transition( + &datastore.host_status().spec_old, + &datastore.host_status().spec, + )?; + } + let recovering = matches!( + current_servicing_state, + ServicingState::AbUpdateHealthCheckFailed | ServicingState::AbUpdateHypervisorCheckFailed + ); + let expected_spec = if recovering { + datastore.host_status().spec_old.clone() + } else { + datastore.host_status().spec.clone() + }; 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 +122,31 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Result { + (false, ServicingState::AbUpdateHealthCheckFailed) + | (false, ServicingState::AbUpdateHypervisorCheckFailed) => { // 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 @@ -145,7 +189,8 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result { + (true, ServicingState::AbUpdateHealthCheckFailed) + | (true, ServicingState::AbUpdateHypervisorCheckFailed) => { // AbUpdateHealthCheckFailed, when booting from expected device (the servicing OS), mark host // status state as Provisioned info!("Rollback to servicing OS succeeded, setting host status from {current_servicing_state:?} to Provisioned"); @@ -155,6 +200,21 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Result Result { + if state == ServicingState::AbUpdateFinalized { + let serialized = serde_yaml::to_value(&error).structured(InternalError::SerializeError)?; + datastore.with_host_status(|status| { + status.servicing_state = ServicingState::AbUpdateHypervisorCheckFailed; + status.last_error = Some(serialized); + })?; + Ok(BootValidationResult::InvalidHypervisor(error)) + } else { + Err(error) + } +} + /// Completes the commit for AbUpdateFinalized and CleanInstallFinalized states when /// the host has booted from the expected boot device. This includes running health /// checks, updating boot order, updating the encryption pcrlock policy if needed, and @@ -800,6 +877,66 @@ mod tests { status::AbVolumeSelection, }; + #[test] + fn hypervisor_failure_is_persisted_before_requesting_rollback() { + let temp = tempfile::TempDir::new().unwrap(); + let path = temp.path().join("datastore.sqlite"); + let mut datastore = DataStore::open_or_create(&path).unwrap(); + let error = TridentError::new(ServicingError::ValidateAbActiveHypervisor { + expected_slot: "AZLB".into(), + observed_slot: Some("AZLA".into()), + }); + let expected_error = serde_yaml::to_value(&error).unwrap(); + let result = + record_hypervisor_failure(&mut datastore, ServicingState::AbUpdateFinalized, error) + .unwrap(); + assert!(matches!(result, BootValidationResult::InvalidHypervisor(_))); + assert_eq!( + datastore.host_status().servicing_state, + ServicingState::AbUpdateHypervisorCheckFailed + ); + assert_eq!( + datastore.host_status().last_error.as_ref(), + Some(&expected_error) + ); + drop(datastore); + let datastore = DataStore::open(&path).unwrap(); + assert_eq!( + datastore.host_status().servicing_state, + ServicingState::AbUpdateHypervisorCheckFailed + ); + assert_eq!( + datastore.host_status().last_error.as_ref(), + Some(&expected_error) + ); + } + + #[test] + fn recovery_identity_failure_does_not_request_another_rollback() { + let temp = tempfile::TempDir::new().unwrap(); + let mut datastore = + DataStore::open_or_create(&temp.path().join("datastore.sqlite")).unwrap(); + datastore + .with_host_status(|status| { + status.servicing_state = ServicingState::AbUpdateHypervisorCheckFailed; + }) + .unwrap(); + let error = TridentError::new(ServicingError::ValidateAbActiveHypervisor { + expected_slot: "AZLA".into(), + observed_slot: None, + }); + assert!(record_hypervisor_failure( + &mut datastore, + ServicingState::AbUpdateHypervisorCheckFailed, + error, + ) + .is_err()); + assert_eq!( + datastore.host_status().servicing_state, + ServicingState::AbUpdateHypervisorCheckFailed + ); + } + #[test] fn test_get_expected_device_path() { let mut ctx = EngineContext { diff --git a/crates/trident/src/engine/update.rs b/crates/trident/src/engine/update.rs index a57631cfef..e597d52bdf 100644 --- a/crates/trident/src/engine/update.rs +++ b/crates/trident/src/engine/update.rs @@ -59,6 +59,8 @@ pub(crate) fn update( image: Some(image), })?; + engine::mshv::validate_transition(&ctx.spec_old, &ctx.spec)?; + // Before starting an update servicing, need to validate that the active volume is set // correctly. if ctx.spec.storage.ab_update.is_some() { diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index 18fd905c81..fb033a4c21 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -510,6 +510,8 @@ pub fn execute( generate_host_status(&history, lsblk_output, lazy_partitions, disk)? }; + crate::engine::mshv::validate_transition(&Default::default(), &host_status.spec)?; + debug!( "host_status:\n{}", serde_yaml::to_string(&host_status).unwrap_or("Failed to serialize Host Status".into()) diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index 9cfbd301d1..2884a2f115 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -306,9 +306,11 @@ impl Trident { datastore.host_status().servicing_state, datastore.host_status().last_error ); - let last_error_to_preserve = if datastore.host_status().servicing_state - == ServicingState::AbUpdateHealthCheckFailed - { + let last_error_to_preserve = if matches!( + datastore.host_status().servicing_state, + ServicingState::AbUpdateHealthCheckFailed + | ServicingState::AbUpdateHypervisorCheckFailed + ) { datastore.host_status().last_error.clone() } else { None @@ -627,6 +629,10 @@ impl Trident { self.execute_and_record_error(datastore, |datastore| { // Ensure that the datastore exists. if !datastore.is_persistent() { + engine::mshv::validate_transition( + &Default::default(), + &host_config, + )?; if acl::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. @@ -817,6 +823,7 @@ impl Trident { ServicingState::CleanInstallFinalized | ServicingState::AbUpdateFinalized | ServicingState::AbUpdateHealthCheckFailed + | ServicingState::AbUpdateHypervisorCheckFailed | ServicingState::ManualRollbackAbFinalized ) { info!( @@ -827,9 +834,9 @@ impl Trident { } let servicing_type = match servicing_state { - ServicingState::AbUpdateFinalized | ServicingState::AbUpdateHealthCheckFailed => { - ServicingType::AbUpdate - } + ServicingState::AbUpdateFinalized + | ServicingState::AbUpdateHealthCheckFailed + | ServicingState::AbUpdateHypervisorCheckFailed => ServicingType::AbUpdate, ServicingState::CleanInstallFinalized => ServicingType::CleanInstall, ServicingState::ManualRollbackAbFinalized => ServicingType::ManualRollbackAb, _ => ServicingType::NoActiveServicing, @@ -841,7 +848,10 @@ impl Trident { ) }); - if rollback_result.is_ok() { + if matches!( + rollback_result, + Ok(rollback::BootValidationResult::ValidBootProvisioned) + ) { if let Some(ref orchestrator) = self.orchestrator { orchestrator.report_success(Some( serde_yaml::to_string(&datastore.host_status()) @@ -854,8 +864,9 @@ impl Trident { Ok(rollback::BootValidationResult::ValidBootProvisioned) => { Ok((ExitKind::Done, servicing_type)) } - Ok(rollback::BootValidationResult::ValidBootHealthCheckFailed(e)) => { - debug!("Correct boot, but health check(s) failed: {e:?}"); + Ok(rollback::BootValidationResult::InvalidHypervisor(e)) + | Ok(rollback::BootValidationResult::ValidBootHealthCheckFailed(e)) => { + debug!("Boot validation requires rollback: {e:?}"); Ok((ExitKind::NeedsReboot, servicing_type)) } Err(e) => { diff --git a/crates/trident/src/server/tridentserver/datastore.rs b/crates/trident/src/server/tridentserver/datastore.rs index defeae4770..a5a1023f89 100644 --- a/crates/trident/src/server/tridentserver/datastore.rs +++ b/crates/trident/src/server/tridentserver/datastore.rs @@ -50,6 +50,9 @@ mod preview { ServicingState::AbUpdateHealthCheckFailed => { ProtoServicingState::UpdateAbHealthCheckFailed } + ServicingState::AbUpdateHypervisorCheckFailed => { + ProtoServicingState::UpdateAbHypervisorCheckFailed + } } } @@ -112,6 +115,10 @@ mod preview { ServicingState::AbUpdateHealthCheckFailed, ProtoServicingState::UpdateAbHealthCheckFailed, ), + ( + ServicingState::AbUpdateHypervisorCheckFailed, + ProtoServicingState::UpdateAbHypervisorCheckFailed, + ), ]; // Track which ServicingState variants have been tested for coverage. diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index d35b291b4a..81d9ec160b 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -51,8 +51,13 @@ impl Subsystem for EspSubsystem { "esp" } + fn validate_host_config(&self, ctx: &EngineContext) -> Result<(), TridentError> { + crate::engine::mshv::validate_configuration(ctx) + } + #[tracing::instrument(name = "esp_provision", skip_all)] fn provision(&mut self, ctx: &EngineContext, mount_path: &Path) -> Result<(), TridentError> { + crate::engine::mshv::validate_configuration(ctx)?; // Perform file-based deployment of ESP images, if needed, after filesystems have been // mounted and initialized. @@ -81,7 +86,16 @@ pub fn set_uefi_fallback_contents( servicing_state: ServicingState, mount_point: &Path, ) -> Result<(), Error> { - let source_esp_dir_name = find_uefi_fallback_source_dir_name(ctx, servicing_state); + let source_esp_dir_name = if crate::engine::mshv::enabled(&ctx.spec) + && servicing_state == ServicingState::AbUpdateFinalized + && ctx.spec.os.uefi_fallback == UefiFallbackMode::Conservative + { + // Commit still holds the pre-update active volume until validation finishes. + ctx.get_ab_update_volume() + .map(|volume| boot::make_esp_dir_name(ctx.install_index, volume)) + } else { + find_uefi_fallback_source_dir_name(ctx, servicing_state) + }; if let Some(source_esp_dir_name) = source_esp_dir_name { debug!( "Configuring UEFI fallback for servicing state {:?} using source ESP dir '{}'", @@ -93,6 +107,7 @@ pub fn set_uefi_fallback_contents( &source_esp_dir_name, &ctx.servicing_type, ctx.install_index, + crate::engine::mshv::enabled(&ctx.spec), )?; } else { debug!( @@ -354,11 +369,29 @@ fn copy_file_artifacts( // 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")?; + let slot_mshv = crate::engine::mshv::enabled(&ctx.spec); + let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let boot_files = if slot_mshv { + mshv::slot::validate_bundle(&source_bundle)?; + mshv::slot::preflight_staging( + ctx, + temp_mount_dir, + &path::join_relative(mount_point, &ctx.esp_mount_path), + &esp_dir_path, + )?; + uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; + Vec::new() + } else { + ensure!( + !source_bundle.join("HvLoader.efi").try_exists()?, + "A slot-owned MSHV image requires internalParams.mshvSlotEspPayload" + ); + generate_boot_filepaths( + temp_mount_dir, + ctx.is_uki().unstructured("UKI setting unknown")?, + ) + .context("Failed to generate boot filepaths")? + }; // Clear esp_dir_path if it exists if esp_dir_path.exists() { @@ -377,12 +410,16 @@ fn copy_file_artifacts( } // Call helper func to copy boot files from temp_mount_dir to esp_dir_path - let grub_noprefix = + let grub_noprefix = if slot_mshv { + mshv::slot::copy_bundle(&source_bundle, &esp_dir_path)?; + false + } else { 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() - ))?; + ))? + }; if ctx.is_uki().unstructured("UKI setting unknown")? { // Prepare ESP directory structure for UKI boot @@ -394,7 +431,9 @@ fn copy_file_artifacts( // 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)?; + if !slot_mshv { + 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)?; @@ -560,6 +599,7 @@ fn copy_boot_files_for_uefi_fallback( source_esp_name: &str, servicing_type: &ServicingType, install_index: usize, + slot_mshv: bool, ) -> Result<(), Error> { let esp_dir_path = path::join_relative(mount_point, esp_mount_path).join(ESP_EFI_DIRECTORY); if skip_uefi_fallback_copy( @@ -583,7 +623,12 @@ 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 = if slot_mshv { + mshv::slot::replace_bundle(&source_esp_dir_path, &uefi_fallback_path) + } else { + replace_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() diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index c422405c2b..5378481585 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -1,5 +1,7 @@ //! ACL, efitreeloader (ETL), and MSHV-related functionality for ESP provisioning. +pub(super) mod slot; + use std::{ fs, path::{Path, PathBuf}, diff --git a/crates/trident/src/subsystems/esp/mshv/slot.rs b/crates/trident/src/subsystems/esp/mshv/slot.rs new file mode 100644 index 0000000000..b9a344bd93 --- /dev/null +++ b/crates/trident/src/subsystems/esp/mshv/slot.rs @@ -0,0 +1,386 @@ +use std::{fs, io::ErrorKind, path::Path}; + +use anyhow::{ensure, Context, Result}; +use nix::sys::statvfs::statvfs; +use osutils::uki::uki_addon_dir; +use trident_api::{config::UefiFallbackMode, constants::EFI_DEFAULT_BIN_RELATIVE_PATH}; + +use crate::engine::{boot::uki, EngineContext}; + +const FILES: &[&str] = &[ + "bootx64.efi", + "grubx64.efi", + "second.efi", + "HvLoader.efi", + "lxhvloader.dll", + "Windows/System32/hvix64.exe", + "Windows/System32/hvax64.exe", + "Windows/System32/kdstub.dll", +]; + +const SPACE_RESERVE: u64 = 1024 * 1024; + +fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { + ensure!( + fs::symlink_metadata(directory)?.is_dir(), + "Invalid payload directory" + ); + for entry in fs::read_dir(directory)? { + let entry = entry?; + let path = entry.path(); + let relative = path.strip_prefix(root)?; + let kind = entry.file_type()?; + if kind.is_dir() { + ensure!( + relative == Path::new("Windows") || relative == Path::new("Windows/System32"), + "Unexpected payload directory: {}", + relative.display() + ); + validate_tree(root, &path, temporary)?; + } else { + ensure!( + kind.is_file(), + "Payload entry is not a regular file: {}", + path.display() + ); + ensure!( + FILES.iter().any(|name| { + relative == Path::new(name) + || temporary + && (relative == Path::new(&format!("{name}.new")) + || relative == Path::new(&format!("{name}.old"))) + }), + "Unexpected payload file: {}", + relative.display() + ); + } + } + Ok(()) +} + +pub(crate) fn validate_bundle(root: &Path) -> Result<()> { + validate_tree(root, root, false)?; + for name in FILES { + ensure!( + fs::symlink_metadata(root.join(name)) + .with_context(|| format!("Missing MSHV payload file: {name}"))? + .is_file(), + "Invalid MSHV payload file: {name}" + ); + } + Ok(()) +} + +fn allocation(path: &Path, cluster: u64) -> Result { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(0), + Err(error) => return Err(error.into()), + }; + if metadata.is_file() { + return Ok(metadata.len().div_ceil(cluster) * cluster); + } + ensure!( + metadata.is_dir(), + "Not a regular file or directory: {}", + path.display() + ); + let mut total = cluster; + for entry in fs::read_dir(path)? { + total += allocation(&entry?.path(), cluster)?; + } + Ok(total) +} + +fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<()> { + ensure!( + available.saturating_add(reclaimed) >= required.saturating_add(SPACE_RESERVE), + "Insufficient ESP capacity: need {required} bytes plus {SPACE_RESERVE} bytes reserve, \ + have {available} bytes free and {reclaimed} bytes reclaimable from the inactive slot" + ); + Ok(()) +} + +pub(crate) fn preflight_staging( + ctx: &EngineContext, + source_esp: &Path, + destination_esp: &Path, + target_bundle: &Path, +) -> Result<()> { + let stats = statvfs(destination_esp)?; + let cluster = stats.fragment_size(); + ensure!(cluster > 0, "Invalid ESP allocation unit"); + let bundle = allocation(&source_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH), cluster)?; + let mut required = bundle + allocation(&source_esp.join(uki::UKI_DIRECTORY), cluster)?; + // Account for slot-addon templates whose selected file may replace a smaller live addon. + required += allocation(&source_esp.join("acl/uki-addons"), cluster)?; + if ctx.spec.os.uefi_fallback != UefiFallbackMode::Disabled { + let existing_fallback = destination_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + required += bundle.max(allocation(&existing_fallback, cluster)?); + } + let mut reclaimed = allocation(target_bundle, cluster)?; + for path in uki::ukis_removed_before_staging(ctx, &destination_esp.join(uki::UKI_DIRECTORY))? { + reclaimed += allocation(&path, cluster)? + allocation(&uki_addon_dir(&path), cluster)?; + } + check_space(stats.blocks_available() * cluster, reclaimed, required) +} + +pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { + validate_bundle(from)?; + fs::create_dir_all(to)?; + validate_tree(to, to, false)?; + for name in FILES { + let destination = to.join(name); + fs::create_dir_all(destination.parent().context("Missing payload parent")?)?; + fs::copy(from.join(name), destination)?; + } + Ok(()) +} + +pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<()> { + validate_bundle(from)?; + match fs::symlink_metadata(to) { + Ok(_) => { + validate_tree(to, to, true)?; + ensure!( + fs::canonicalize(from)? != fs::canonicalize(to)?, + "Source and fallback directories must differ" + ); + } + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + let stats = statvfs(to.parent().context("Missing fallback parent")?)?; + let cluster = stats.fragment_size(); + ensure!(cluster > 0, "Invalid ESP allocation unit"); + let required = allocation(from, cluster)?; + let mut reclaimed = 0; + for name in FILES { + reclaimed += allocation(&to.join(format!("{name}.new")), cluster)?; + } + check_space(stats.blocks_available() * cluster, reclaimed, required)?; + for name in FILES { + let destination = to.join(name); + let previous = to.join(format!("{name}.old")); + fs::create_dir_all(destination.parent().context("Missing payload parent")?)?; + if previous.exists() { + if destination.exists() { + fs::remove_file(&previous)?; + } else { + fs::rename(&previous, &destination)?; + } + } + fs::copy(from.join(name), to.join(format!("{name}.new")))?; + } + for name in FILES { + let destination = to.join(name); + if destination.exists() { + fs::rename(&destination, to.join(format!("{name}.old")))?; + } + } + for name in FILES { + fs::rename(to.join(format!("{name}.new")), to.join(name))?; + } + for name in FILES { + let previous = to.join(format!("{name}.old")); + if previous.exists() { + fs::remove_file(previous)?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::symlink; + use tempfile::TempDir; + + fn bundle(root: &Path, contents: &[u8]) { + for name in FILES { + let path = root.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); + } + } + + #[test] + fn copies_complete_bundle_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"); + bundle(&source, b"new"); + bundle(&active, b"retained"); + copy_bundle(&source, &target).unwrap(); + for name in FILES { + assert_eq!(fs::read(target.join(name)).unwrap(), b"new"); + assert_eq!(fs::read(active.join(name)).unwrap(), b"retained"); + } + } + + #[test] + fn rejects_incomplete_and_unexpected_payload_before_copy() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let target = temp.path().join("target"); + bundle(&source, b"new"); + fs::remove_file(source.join("lxhvloader.dll")).unwrap(); + assert!(copy_bundle(&source, &target).is_err()); + assert!(!target.exists()); + bundle(&source, b"new"); + fs::write(source.join("identity.json"), b"unexpected").unwrap(); + assert!(copy_bundle(&source, &target).is_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"); + bundle(&source, b"new"); + fs::create_dir(&outside).unwrap(); + symlink(&outside, &target).unwrap(); + assert!(replace_bundle(&source, &target).is_err()); + fs::remove_file(&target).unwrap(); + fs::remove_file(source.join("lxhvloader.dll")).unwrap(); + symlink(outside.join("dll"), source.join("lxhvloader.dll")).unwrap(); + assert!(copy_bundle(&source, &target).is_err()); + assert!(fs::read_dir(&outside).unwrap().next().is_none()); + } + + #[test] + fn retries_partial_publication_and_removes_only_known_temporary_files() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("AZLB"); + let fallback = temp.path().join("BOOT"); + bundle(&source, b"new"); + bundle(&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_bundle(&source, &fallback).unwrap(); + replace_bundle(&source, &fallback).unwrap(); + validate_bundle(&fallback).unwrap(); + for name in 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_bundle(&source, &source).is_err()); + } + + #[test] + fn capacity_accounts_for_clusters_and_preserves_a_reserve() { + let temp = TempDir::new().unwrap(); + fs::write(temp.path().join("file"), b"x").unwrap(); + assert_eq!(allocation(&temp.path().join("file"), 4096).unwrap(), 4096); + assert!(check_space(SPACE_RESERVE, 0, 1).is_err()); + assert!(check_space(SPACE_RESERVE, 4096, 4096).is_ok()); + } + + #[test] + fn preflight_rejects_peak_allocation_before_mutating_inactive_or_retained_files() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let destination = temp.path().join("esp"); + let target = destination.join("EFI/AZLB"); + let retained = destination.join("EFI/AZLA"); + bundle(&source.join(EFI_DEFAULT_BIN_RELATIVE_PATH), b"new"); + bundle(&target, b"inactive"); + bundle(&retained, b"committed"); + fs::create_dir_all(source.join(uki::UKI_DIRECTORY)).unwrap(); + let stats = statvfs(&destination).unwrap(); + fs::File::create(source.join(uki::UKI_DIRECTORY).join("new.efi")) + .unwrap() + .set_len(stats.blocks_available() * stats.fragment_size() + SPACE_RESERVE) + .unwrap(); + let ctx = EngineContext { + servicing_type: trident_api::status::ServicingType::AbUpdate, + ab_active_volume: Some(trident_api::status::AbVolumeSelection::VolumeA), + ..Default::default() + }; + assert!(preflight_staging(&ctx, &source, &destination, &target).is_err()); + for name in FILES { + assert_eq!(fs::read(target.join(name)).unwrap(), b"inactive"); + assert_eq!(fs::read(retained.join(name)).unwrap(), b"committed"); + } + } + + #[test] + fn fallback_modes_use_the_full_selected_bundle_during_trial_commit_and_rollback() { + use trident_api::{ + constants::internal_params::MSHV_SLOT_ESP_PAYLOAD, + status::{AbVolumeSelection, ServicingState, ServicingType}, + }; + 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"); + bundle(&active, b"retained"); + bundle(&target, b"candidate"); + bundle(&fallback, b"retained"); + 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.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); + ctx.spec.os.uefi_fallback = mode; + crate::subsystems::esp::set_uefi_fallback_contents( + &ctx, + ServicingState::AbUpdateStaged, + temp.path(), + ) + .unwrap(); + for name in FILES { + let expected = if mode == UefiFallbackMode::Optimistic { + b"candidate".as_slice() + } else { + b"retained".as_slice() + }; + assert_eq!(fs::read(fallback.join(name)).unwrap(), expected); + } + crate::subsystems::esp::set_uefi_fallback_contents( + &ctx, + ServicingState::AbUpdateFinalized, + temp.path(), + ) + .unwrap(); + for name in FILES { + 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); + crate::subsystems::esp::set_uefi_fallback_contents( + &ctx, + ServicingState::ManualRollbackAbStaged, + temp.path(), + ) + .unwrap(); + for name in FILES { + assert_eq!(fs::read(fallback.join(name)).unwrap(), b"retained"); + } + } + } +} diff --git a/crates/trident_api/src/constants.rs b/crates/trident_api/src/constants.rs index e2483e1f59..d1d726620b 100644 --- a/crates/trident_api/src/constants.rs +++ b/crates/trident_api/src/constants.rs @@ -244,6 +244,9 @@ pub mod internal_params { /// Preserve the MSHV EFI payload during clean-install file-based ESP deployment. pub const PRESERVE_MSHV_ESP_PAYLOAD: &str = "preserveMshvEspPayload"; + /// Stage an experimental slot-owned MSHV ESP bundle with its OS image. + pub const MSHV_SLOT_ESP_PAYLOAD: &str = "mshvSlotEspPayload"; + /// 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/crates/trident_api/src/error.rs b/crates/trident_api/src/error.rs index e4fda52de0..2c239aa510 100644 --- a/crates/trident_api/src/error.rs +++ b/crates/trident_api/src/error.rs @@ -712,6 +712,12 @@ pub enum ServicingError { hs_active_volume: String, }, + #[error("Running hypervisor does not match expected slot '{expected_slot}' (observed: {observed_slot:?})")] + ValidateAbActiveHypervisor { + expected_slot: String, + observed_slot: Option, + }, + #[error("Trident rebuild-raid validation failed")] ValidateRebuildRaid, diff --git a/crates/trident_api/src/status.rs b/crates/trident_api/src/status.rs index 407714de0e..638a056697 100644 --- a/crates/trident_api/src/status.rs +++ b/crates/trident_api/src/status.rs @@ -133,6 +133,8 @@ pub enum ServicingState { Provisioned, /// A/B update has been completed, the host booted into the target OS but the health checks failed. AbUpdateHealthCheckFailed, + /// The trial OS booted, but its hypervisor failed validation; recovery is pending. + AbUpdateHypervisorCheckFailed, } /// A/B volume selection. Determines which set of volumes are currently diff --git a/docs/Explanation/Bootloader-Configuration.md b/docs/Explanation/Bootloader-Configuration.md index 04838810e9..0e999ef848 100644 --- a/docs/Explanation/Bootloader-Configuration.md +++ b/docs/Explanation/Bootloader-Configuration.md @@ -48,6 +48,31 @@ The bootloader choice (and choice of UKI) has some implications on ## Bootloader Servicing +### Experimental slot-owned MSHV payloads + +For x86-64 ACL UKI COSIs built with the matching efitreeloader prefix resolver, +`internalParams.mshvSlotEspPayload: true` copies the complete `EFI/BOOT` +bundle into the target slot. The bundle contains `bootx64.efi`, `grubx64.efi`, +`second.efi`, `HvLoader.efi`, `lxhvloader.dll` and +`Windows/System32/{hvix64.exe,hvax64.exe,kdstub.dll}`. +UKIs and addons remain in `EFI/Linux`; existing firmware and UKI selectors +are unchanged. + +Use the flag for both the original install and subsequent updates. Changing +MSHV mode on an existing installation, combining it with +`preserveMshvEspPayload`, raw/disk-streaming installation, and TPM/PCR-bound +encryption are rejected. Offline-init adoption and legacy conversion are +not enabled by this feature. + +Staging validates the bundle and checks peak ESP allocation before clearing +the inactive slot. Existing fallback modes apply to the complete nested bundle. +A separate hypervisor-validation failure state supports recovery to the +retained OS without classifying the failure as a user health-check failure. + +**Hypervisor identity validation is currently a success stub.** Commit and +rollback call the hook, but cannot yet detect a mixed hypervisor/OS boot. +This experimental implementation is not production or boot-validated. + :::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/proto/trident/v1preview/status_service.proto b/proto/trident/v1preview/status_service.proto index 5cd2a97d28..5c09adf862 100644 --- a/proto/trident/v1preview/status_service.proto +++ b/proto/trident/v1preview/status_service.proto @@ -77,6 +77,8 @@ enum ServicingState { // A/B update has been completed, the host booted into the target OS but the // health checks failed. UPDATE_AB_HEALTH_CHECK_FAILED = 11; + // The trial hypervisor failed validation; recovery to the retained OS is pending. + UPDATE_AB_HYPERVISOR_CHECK_FAILED = 12; } message GetServicingStateResponse { From 531184b6d15bb018a8a4fc11dce2bbd5bd960471 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 18:56:24 +0000 Subject: [PATCH 02/82] Support slot-owned MSHV during ACL first update Follow existing AZLA bootstrap with the complete MSHV bundle and preserve established mode-transition checks. Match FAT filename casing in bundle validation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/init/offline/mod.rs | 2 +- crates/trident/src/lib.rs | 17 ++-- crates/trident/src/subsystems/esp.rs | 82 +++++++++++++++++-- .../trident/src/subsystems/esp/mshv/slot.rs | 39 ++++++++- docs/Explanation/Bootloader-Configuration.md | 9 +- 5 files changed, 126 insertions(+), 23 deletions(-) diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index fb033a4c21..2fde06715c 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -535,7 +535,7 @@ pub fn execute( "Failed to find ESP filesystem in Host Status, validation should have failed if this was the case", )))?; - esp::bootstrap_azla_from_fallback(esp_path) + esp::bootstrap_azla_from_fallback(esp_path, false) .structured(InvalidInputError::InvalidBootConfiguration) .message("Failed to bootstrap AZLA from fallback")?; diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index 2884a2f115..eafe0c8ae7 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -19,8 +19,8 @@ use trident_api::{ OsImage as ConfigOsImage, }, constants::internal_params::{ - HTTP_CONNECTION_TIMEOUT_SECONDS, ORCHESTRATOR_CONNECTION_TIMEOUT_SECONDS, - WAIT_FOR_SYSTEMD_NETWORKD, + HTTP_CONNECTION_TIMEOUT_SECONDS, MSHV_SLOT_ESP_PAYLOAD, + ORCHESTRATOR_CONNECTION_TIMEOUT_SECONDS, WAIT_FOR_SYSTEMD_NETWORKD, }, error::{ DatastoreError, ExecutionEnvironmentMisconfigurationError, InitializationError, @@ -629,14 +629,10 @@ impl Trident { self.execute_and_record_error(datastore, |datastore| { // Ensure that the datastore exists. if !datastore.is_persistent() { - engine::mshv::validate_transition( - &Default::default(), - &host_config, - )?; if acl::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() + let mut initial_host_status = acl::initial_host_status() .structured(InvalidInputError::DeriveHostConfiguration) .message("Failed to initialize host status for ACL")?; @@ -662,10 +658,15 @@ impl Trident { let esp_path = container::get_host_relative_path(esp_path.to_path_buf()) .message("Failed to resolve ESP path relative to host for ACL")?; - esp::bootstrap_azla_from_fallback(&esp_path) + let slot_mshv = engine::mshv::enabled(&host_config); + esp::bootstrap_azla_from_fallback(&esp_path, slot_mshv) .structured(InvalidInputError::InvalidBootConfiguration) .message("Failed to bootstrap AZLA ESP path for ACL")?; + if slot_mshv { + initial_host_status.spec.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); + } + datastore .with_host_status(|status| { *status = initial_host_status; diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 81d9ec160b..e00a0ffddb 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -745,16 +745,22 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { /// 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. -pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { +pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> 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); + if slot_mshv { + mshv::slot::validate_bundle(&boot_esp_path)?; + if azla_esp_path.exists() { + return mshv::slot::validate_bundle(&azla_esp_path); + } + mshv::slot::preflight_bootstrap(&boot_esp_path, esp_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) @@ -769,7 +775,12 @@ 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 = if slot_mshv { + mshv::slot::copy_bundle(&boot_esp_path, &azla_tmp_path) + } else { + replace_boot_files(&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() @@ -1531,7 +1542,7 @@ mod tests { writeln!(file, "{content}").unwrap(); } - bootstrap_azla_from_fallback(esp_dir.path()).unwrap(); + bootstrap_azla_from_fallback(esp_dir.path(), false).unwrap(); for (file_name, _content) in &file_infos { assert!( @@ -1567,7 +1578,7 @@ mod tests { let mut sentinel_file = File::create(&sentinel_path).unwrap(); writeln!(sentinel_file, "Pre-existing AZLA content").unwrap(); - bootstrap_azla_from_fallback(esp_dir.path()).unwrap(); + bootstrap_azla_from_fallback(esp_dir.path(), false).unwrap(); // AZLA must be left untouched: bootstrap only runs when AZLA is // absent, so a second call must be a no-op. @@ -1611,7 +1622,7 @@ mod tests { let mut stale_file = File::create(azla_tmp_dir.join("stale-leftover")).unwrap(); writeln!(stale_file, "Leftover from a crashed bootstrap").unwrap(); - bootstrap_azla_from_fallback(esp_dir.path()).unwrap(); + bootstrap_azla_from_fallback(esp_dir.path(), false).unwrap(); // The stale temp dir must be cleaned up, and bootstrapping must // still succeed despite it being present beforehand. @@ -1629,6 +1640,63 @@ mod tests { } } + #[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"); + let files = [ + "bootx64.efi", + "grubx64.efi", + "second.efi", + "HvLoader.efi", + "lxhvloader.dll", + "Windows/System32/hvix64.exe", + "Windows/System32/hvax64.exe", + "Windows/System32/kdstub.dll", + ]; + for name in files { + let path = boot.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, name).unwrap(); + } + fs::create_dir_all(&temporary).unwrap(); + fs::write(temporary.join("stale"), "incomplete").unwrap(); + + bootstrap_azla_from_fallback(esp.path(), true).unwrap(); + for name in files { + assert!(files_are_identical(&boot.join(name), &azla.join(name))); + } + assert!(!temporary.exists()); + + fs::write(boot.join("HvLoader.efi"), "new fallback").unwrap(); + bootstrap_azla_from_fallback(esp.path(), true).unwrap(); + assert_eq!( + fs::read_to_string(azla.join("HvLoader.efi")).unwrap(), + "HvLoader.efi" + ); + + fs::remove_file(azla.join("Windows/System32/kdstub.dll")).unwrap(); + assert!(bootstrap_azla_from_fallback(esp.path(), true).is_err()); + assert!(!azla.join("Windows/System32/kdstub.dll").exists()); + } + + #[test] + fn test_bootstrap_azla_rejects_incomplete_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"); + fs::create_dir_all(&boot).unwrap(); + fs::write(boot.join(BOOT_EFI), "shim").unwrap(); + assert!(bootstrap_azla_from_fallback(esp.path(), true).is_err()); + assert!(!azla.exists()); + assert_eq!(fs::read_to_string(boot.join(BOOT_EFI)).unwrap(), "shim"); + } + /// Validates that copy_boot_files() correctly copies boot files from temp_mount_dir to esp_dir #[test] fn test_copy_boot_files_without_noprefix() { diff --git a/crates/trident/src/subsystems/esp/mshv/slot.rs b/crates/trident/src/subsystems/esp/mshv/slot.rs index b9a344bd93..914b2d48dc 100644 --- a/crates/trident/src/subsystems/esp/mshv/slot.rs +++ b/crates/trident/src/subsystems/esp/mshv/slot.rs @@ -29,10 +29,12 @@ fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { let entry = entry?; let path = entry.path(); let relative = path.strip_prefix(root)?; + let relative_name = relative.to_str().context("Non-UTF-8 MSHV payload path")?; let kind = entry.file_type()?; if kind.is_dir() { ensure!( - relative == Path::new("Windows") || relative == Path::new("Windows/System32"), + relative_name.eq_ignore_ascii_case("Windows") + || relative_name.eq_ignore_ascii_case("Windows/System32"), "Unexpected payload directory: {}", relative.display() ); @@ -45,10 +47,10 @@ fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { ); ensure!( FILES.iter().any(|name| { - relative == Path::new(name) + relative_name.eq_ignore_ascii_case(name) || temporary - && (relative == Path::new(&format!("{name}.new")) - || relative == Path::new(&format!("{name}.old"))) + && (relative_name.eq_ignore_ascii_case(&format!("{name}.new")) + || relative_name.eq_ignore_ascii_case(&format!("{name}.old"))) }), "Unexpected payload file: {}", relative.display() @@ -125,6 +127,17 @@ pub(crate) fn preflight_staging( check_space(stats.blocks_available() * cluster, reclaimed, required) } +pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<()> { + let stats = statvfs(esp)?; + let cluster = stats.fragment_size(); + ensure!(cluster > 0, "Invalid ESP allocation unit"); + check_space( + stats.blocks_available() * cluster, + 0, + allocation(from, cluster)?, + ) +} + pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { validate_bundle(from)?; fs::create_dir_all(to)?; @@ -219,6 +232,24 @@ mod tests { } } + #[test] + fn accepts_fat_filename_casing_but_rejects_unknown_entries() { + let temp = TempDir::new().unwrap(); + for name in FILES { + let path = temp.path().join(name.to_ascii_uppercase()); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"payload").unwrap(); + } + validate_tree(temp.path(), temp.path(), false).unwrap(); + let pending = temp.path().join("SECOND.EFI.NEW"); + fs::write(&pending, b"pending").unwrap(); + assert!(validate_tree(temp.path(), temp.path(), false).is_err()); + validate_tree(temp.path(), temp.path(), true).unwrap(); + fs::remove_file(pending).unwrap(); + fs::write(temp.path().join("IDENTITY.JSON"), b"unexpected").unwrap(); + assert!(validate_tree(temp.path(), temp.path(), true).is_err()); + } + #[test] fn rejects_incomplete_and_unexpected_payload_before_copy() { let temp = TempDir::new().unwrap(); diff --git a/docs/Explanation/Bootloader-Configuration.md b/docs/Explanation/Bootloader-Configuration.md index 0e999ef848..35528a25cd 100644 --- a/docs/Explanation/Bootloader-Configuration.md +++ b/docs/Explanation/Bootloader-Configuration.md @@ -58,11 +58,14 @@ bundle into the target slot. The bundle contains `bootx64.efi`, `grubx64.efi`, UKIs and addons remain in `EFI/Linux`; existing firmware and UKI selectors are unchanged. -Use the flag for both the original install and subsequent updates. Changing +Enable the flag during installation or first-update ACL adoption, and keep it +enabled for subsequent updates. Changing MSHV mode on an existing installation, combining it with `preserveMshvEspPayload`, raw/disk-streaming installation, and TPM/PCR-bound -encryption are rejected. Offline-init adoption and legacy conversion are -not enabled by this feature. +encryption are rejected. First-update ACL adoption validates the existing +BOOT bundle and seeds the complete AZLA payload, following the normal ACL +bootstrap. Offline-init adoption and mode conversion on an already-managed +installation remain disabled. Staging validates the bundle and checks peak ESP allocation before clearing the inactive slot. Existing fallback modes apply to the complete nested bundle. From d754cfc5c1554805760fe1c14885e4f01872bfe7 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 20:04:43 +0000 Subject: [PATCH 03/82] Clean stale MSHV bootstrap files before checking capacity Preserve the existing bootstrap retry ordering and cover cleanup when capacity preflight rejects the copy. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/subsystems/esp.rs | 46 +++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index e00a0ffddb..4e5b5ab361 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -753,7 +753,6 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> Result< if azla_esp_path.exists() { return mshv::slot::validate_bundle(&azla_esp_path); } - mshv::slot::preflight_bootstrap(&boot_esp_path, esp_path)?; } trace!("Checking for AZLA volume ESP path at {:?}", &azla_esp_path); if !azla_esp_path.exists() { @@ -776,6 +775,7 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> Result< ))?; } let copy_result = if slot_mshv { + mshv::slot::preflight_bootstrap(&boot_esp_path, esp_path)?; mshv::slot::copy_bundle(&boot_esp_path, &azla_tmp_path) } else { replace_boot_files(&boot_esp_path, &azla_tmp_path) @@ -1685,6 +1685,50 @@ mod tests { assert!(!azla.join("Windows/System32/kdstub.dll").exists()); } + #[test] + fn test_bootstrap_azla_cleans_stale_mshv_copy_before_capacity_check() { + 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 [ + "bootx64.efi", + "grubx64.efi", + "second.efi", + "HvLoader.efi", + "lxhvloader.dll", + "Windows/System32/hvix64.exe", + "Windows/System32/hvax64.exe", + "Windows/System32/kdstub.dll", + ] { + 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(); + + // Force preflight failure with a sparse file, without filling the filesystem. + let stats = nix::sys::statvfs::statvfs(esp.path()).unwrap(); + let length = stats.blocks_available() * stats.fragment_size() + 1; + fs::OpenOptions::new() + .write(true) + .open(boot.join(BOOT_EFI)) + .unwrap() + .set_len(length) + .unwrap(); + + let error = bootstrap_azla_from_fallback(esp.path(), true).unwrap_err(); + assert!(error.to_string().contains("Insufficient ESP capacity")); + assert!(!temporary.exists()); + assert!(!azla.exists()); + assert_eq!(fs::metadata(boot.join(BOOT_EFI)).unwrap().len(), length); + assert_eq!(fs::read(boot.join("HvLoader.efi")).unwrap(), b"retained"); + } + #[test] fn test_bootstrap_azla_rejects_incomplete_mshv_fallback() { let esp = TempDir::new().unwrap(); From caef68e92511570d6203cbcba34958097406bd34 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 20:22:33 +0000 Subject: [PATCH 04/82] Decode hypervisor validation failures in the preview client Expose the new servicing state in trident-client and cover it in the existing preview status test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident-client/src/preview.rs | 1 + crates/trident-client/src/protocol.rs | 3 +++ crates/trident-client/src/tests.rs | 4 ++++ 3 files changed, 8 insertions(+) diff --git a/crates/trident-client/src/preview.rs b/crates/trident-client/src/preview.rs index dddb12829a..5bfd62d3e4 100644 --- a/crates/trident-client/src/preview.rs +++ b/crates/trident-client/src/preview.rs @@ -49,6 +49,7 @@ pub enum ServicingState { ManualRollbackAbFinalized, Provisioned, AbUpdateHealthCheckFailed, + AbUpdateHypervisorCheckFailed, Unknown(i32), } diff --git a/crates/trident-client/src/protocol.rs b/crates/trident-client/src/protocol.rs index 9d7654f809..4a25dfd3b4 100644 --- a/crates/trident-client/src/protocol.rs +++ b/crates/trident-client/src/protocol.rs @@ -307,6 +307,9 @@ pub(crate) fn decode_servicing_state(state: i32) -> ServicingState { Ok(ProtoServicingState::UpdateAbHealthCheckFailed) => { ServicingState::AbUpdateHealthCheckFailed } + Ok(ProtoServicingState::UpdateAbHypervisorCheckFailed) => { + ServicingState::AbUpdateHypervisorCheckFailed + } Err(_) => ServicingState::Unknown(state), } } diff --git a/crates/trident-client/src/tests.rs b/crates/trident-client/src/tests.rs index c5ae868c23..36ce17c6c2 100644 --- a/crates/trident-client/src/tests.rs +++ b/crates/trident-client/src/tests.rs @@ -1489,6 +1489,10 @@ async fn preview_status_validation_and_rollback_use_domain_types() { #[tokio::test] async fn preview_status_enums_preserve_known_unspecified_and_unknown_values() { let servicing_states = [ + ( + ProtoServicingState::UpdateAbHypervisorCheckFailed as i32, + ServicingState::AbUpdateHypervisorCheckFailed, + ), ( ProtoServicingState::Provisioned as i32, ServicingState::Provisioned, From a0c777dcabbe465248e634e40fa363f12a5cbfd7 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 21:20:54 +0000 Subject: [PATCH 05/82] Document initial MSHV architecture support choice Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/mshv.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index 39051f6f4b..d77a012d31 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -36,6 +36,8 @@ pub(crate) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE if !enabled(&ctx.spec) { return Ok(()); } + // x86-64 is an initial support choice while the MSHV payload definition is x64-only. + // Other architectures should reuse the existing architecture-aware EFI filename helpers. if !cfg!(target_arch = "x86_64") || !ctx.image_distro().is_acl() || !ctx.is_uki()? { return Err(unsupported( "Slot-owned MSHV requires an x86-64 ACL UKI image", From b3409b1711b205794f10929eac3c40adc8e4522c Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 21:40:15 +0000 Subject: [PATCH 06/82] Discover initial MSHV mode from the installed ACL payload Validate the existing BOOT bundle during HostStatus discovery, then check the requested mode before bootstrapping AZLA. Do not populate discovered state from the update request. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/init/acl/mod.rs | 173 +++++++++++++++---- crates/trident/src/lib.rs | 14 +- crates/trident/src/subsystems/esp.rs | 15 ++ docs/Explanation/Bootloader-Configuration.md | 7 +- 4 files changed, 167 insertions(+), 42 deletions(-) diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index 5eee1c0259..8f98fc6bc1 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -8,6 +8,7 @@ use log::{trace, warn}; use uuid::Uuid; use osutils::{ + container, lsblk::{self, BlockDevice}, osrelease::OsRelease, sfdisk::SfDisk, @@ -19,10 +20,16 @@ use trident_api::{ MountOptions, MountPoint, Partition, PartitionSize, PartitionTableType, PartitionType, Storage, VerityDevice, }, + constants::internal_params::MSHV_SLOT_ESP_PAYLOAD, + error::TridentResultExt, status::{AbVolumeSelection, HostStatus, ServicingState}, BlockDeviceId, }; +use crate::subsystems::esp; + +const ACL_ESP_MOUNT_POINT: &str = "/boot"; + /// 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")?; @@ -72,7 +79,9 @@ pub fn initial_host_status() -> Result { root_blk_device.device_path().display() ))?; - inner_initial_host_status(&disk_information, &root_blk_device) + let esp_path = container::get_host_relative_path(PathBuf::from(ACL_ESP_MOUNT_POINT)) + .unstructured("Failed to resolve ACL ESP path")?; + inner_initial_host_status(&disk_information, &root_blk_device, &esp_path) } /// Internal function that does much of the work of creating the @@ -82,6 +91,7 @@ pub fn initial_host_status() -> Result { fn inner_initial_host_status( disk_information: &SfDisk, root_blk_device: &BlockDevice, + esp_path: &Path, ) -> Result { let disk_name = "disk-0".to_string(); // Construct the HostStatus disk UUID struct @@ -222,7 +232,7 @@ fn inner_initial_host_status( }); } - Ok(HostStatus { + let mut host_status = HostStatus { spec: HostConfiguration { storage: Storage { disks: vec![Disk { @@ -239,7 +249,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, @@ -293,7 +303,14 @@ fn inner_initial_host_status( disk_uuids, partition_paths, ..Default::default() - }) + }; + if esp::has_slot_mshv_bundle(esp_path)? { + host_status + .spec + .internal_params + .set_flag(MSHV_SLOT_ESP_PAYLOAD); + } + Ok(host_status) } #[cfg(test)] @@ -462,6 +479,64 @@ mod tests { } } + fn create_mshv_bundle(esp_path: &Path) { + for name in [ + "bootx64.efi", + "grubx64.efi", + "second.efi", + "HvLoader.efi", + "lxhvloader.dll", + "Windows/System32/hvix64.exe", + "Windows/System32/hvax64.exe", + "Windows/System32/kdstub.dll", + ] { + let path = esp_path.join("EFI/BOOT").join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, b"payload").unwrap(); + } + } + + #[test] + fn initial_host_status_discovers_slot_mshv_from_image() { + let esp = tempfile::TempDir::new().unwrap(); + let disk = create_sfdisk("EFI-SYSTEM", TestPartitions::Correct); + let device = create_blk_device(); + let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); + assert!(!status.spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD)); + + std::fs::create_dir_all(esp.path().join("EFI/BOOT")).unwrap(); + std::fs::write(esp.path().join("EFI/BOOT/bootx64.efi"), b"shim").unwrap(); + std::fs::write( + esp.path().join("EFI/HvLoader.efi"), + b"legacy shared payload", + ) + .unwrap(); + let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); + assert!(!status.spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD)); + + create_mshv_bundle(esp.path()); + let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); + assert!(status.spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD)); + assert!(!esp.path().join("EFI/AZLA").exists()); + } + + #[test] + fn initial_host_status_rejects_incomplete_slot_mshv_payload() { + let esp = tempfile::TempDir::new().unwrap(); + create_mshv_bundle(esp.path()); + std::fs::remove_file(esp.path().join("EFI/BOOT/HvLoader.efi")).unwrap(); + let error = inner_initial_host_status( + &create_sfdisk("EFI-SYSTEM", TestPartitions::Correct), + &create_blk_device(), + esp.path(), + ) + .unwrap_err(); + assert!(error + .to_string() + .contains("Missing MSHV payload file: HvLoader.efi")); + assert!(!esp.path().join("EFI/AZLA").exists()); + } + fn create_blk_device() -> BlockDevice { BlockDevice { name: "/dev/sda".into(), @@ -478,7 +553,12 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::Correct); let blkdevice = create_blk_device(); // Run - let init_host_status = inner_initial_host_status(&sfdisk, &blkdevice).unwrap(); + let init_host_status = inner_initial_host_status( + &sfdisk, + &blkdevice, + tempfile::TempDir::new().unwrap().path(), + ) + .unwrap(); init_host_status.spec.validate().unwrap(); @@ -520,7 +600,12 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::Correct); let blkdevice = create_blk_device(); - let init_host_status = inner_initial_host_status(&sfdisk, &blkdevice).unwrap(); + let init_host_status = inner_initial_host_status( + &sfdisk, + &blkdevice, + tempfile::TempDir::new().unwrap().path(), + ) + .unwrap(); init_host_status.spec.validate().unwrap(); let volume_pairs = &init_host_status @@ -541,7 +626,12 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::WithHashSigPair); let blkdevice = create_blk_device(); - let init_host_status = inner_initial_host_status(&sfdisk, &blkdevice).unwrap(); + let init_host_status = inner_initial_host_status( + &sfdisk, + &blkdevice, + tempfile::TempDir::new().unwrap().path(), + ) + .unwrap(); init_host_status.spec.validate().unwrap(); let partitions = &init_host_status.spec.storage.disks[0].partitions; @@ -576,7 +666,12 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::WithHashSigPartial); let blkdevice = create_blk_device(); - let init_host_status = inner_initial_host_status(&sfdisk, &blkdevice).unwrap(); + let init_host_status = inner_initial_host_status( + &sfdisk, + &blkdevice, + tempfile::TempDir::new().unwrap().path(), + ) + .unwrap(); init_host_status.spec.validate().unwrap(); let volume_pairs = &init_host_status @@ -596,14 +691,18 @@ mod tests { let unexpected_label = create_sfdisk(wrong_label, TestPartitions::Correct); let blkdevice = create_blk_device(); // Run - assert!(inner_initial_host_status(&unexpected_label, &blkdevice) - .unwrap_err() - .root_cause() - .to_string() - .contains(&format!( - "Unexpected partition label '{}' found on root disk", - wrong_label - ))); + assert!(inner_initial_host_status( + &unexpected_label, + &blkdevice, + tempfile::TempDir::new().unwrap().path() + ) + .unwrap_err() + .root_cause() + .to_string() + .contains(&format!( + "Unexpected partition label '{}' found on root disk", + wrong_label + ))); } #[test] @@ -611,11 +710,15 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::MissingOne); let blkdevice = create_blk_device(); // Run - assert!(inner_initial_host_status(&sfdisk, &blkdevice) - .unwrap_err() - .root_cause() - .to_string() - .contains("Missing partition labels found on root disk")); + assert!(inner_initial_host_status( + &sfdisk, + &blkdevice, + tempfile::TempDir::new().unwrap().path() + ) + .unwrap_err() + .root_cause() + .to_string() + .contains("Missing partition labels found on root disk")); } #[test] @@ -623,11 +726,15 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::ExtraOne); let blkdevice = create_blk_device(); // Run - assert!(inner_initial_host_status(&sfdisk, &blkdevice) - .unwrap_err() - .root_cause() - .to_string() - .contains("Unexpected partition label 'extra-one' found on root disk")); + assert!(inner_initial_host_status( + &sfdisk, + &blkdevice, + tempfile::TempDir::new().unwrap().path() + ) + .unwrap_err() + .root_cause() + .to_string() + .contains("Unexpected partition label 'extra-one' found on root disk")); } #[test] @@ -635,10 +742,14 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::Duplicate); let blkdevice = create_blk_device(); // Run - assert!(inner_initial_host_status(&sfdisk, &blkdevice) - .unwrap_err() - .root_cause() - .to_string() - .contains("Multiple identical partition labels found on root disk: 'usr-a'")); + assert!(inner_initial_host_status( + &sfdisk, + &blkdevice, + tempfile::TempDir::new().unwrap().path() + ) + .unwrap_err() + .root_cause() + .to_string() + .contains("Multiple identical partition labels found on root disk: 'usr-a'")); } } diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index eafe0c8ae7..a8db449cb7 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -19,8 +19,8 @@ use trident_api::{ OsImage as ConfigOsImage, }, constants::internal_params::{ - HTTP_CONNECTION_TIMEOUT_SECONDS, MSHV_SLOT_ESP_PAYLOAD, - ORCHESTRATOR_CONNECTION_TIMEOUT_SECONDS, WAIT_FOR_SYSTEMD_NETWORKD, + HTTP_CONNECTION_TIMEOUT_SECONDS, ORCHESTRATOR_CONNECTION_TIMEOUT_SECONDS, + WAIT_FOR_SYSTEMD_NETWORKD, }, error::{ DatastoreError, ExecutionEnvironmentMisconfigurationError, InitializationError, @@ -632,10 +632,12 @@ impl Trident { if acl::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 mut initial_host_status = acl::initial_host_status() + let initial_host_status = acl::initial_host_status() .structured(InvalidInputError::DeriveHostConfiguration) .message("Failed to initialize host status for ACL")?; + engine::mshv::validate_transition(&initial_host_status.spec, &host_config)?; + // Mirror offline-initialize's bootstrap: ACL lazy adoption derives // HostStatus metadata only, it never touches the ESP. Seed EFI/AZLA from // EFI/BOOT now so manual rollback's "AZLA must already exist" invariant @@ -658,15 +660,11 @@ impl Trident { let esp_path = container::get_host_relative_path(esp_path.to_path_buf()) .message("Failed to resolve ESP path relative to host for ACL")?; - let slot_mshv = engine::mshv::enabled(&host_config); + let slot_mshv = engine::mshv::enabled(&initial_host_status.spec); esp::bootstrap_azla_from_fallback(&esp_path, slot_mshv) .structured(InvalidInputError::InvalidBootConfiguration) .message("Failed to bootstrap AZLA ESP path for ACL")?; - if slot_mshv { - initial_host_status.spec.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); - } - datastore .with_host_status(|status| { *status = initial_host_status; diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 4e5b5ab361..6ad5f3431a 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -740,6 +740,21 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { Ok(()) } +pub(crate) fn has_slot_mshv_bundle(esp_path: &Path) -> Result { + let bundle = esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + for marker in ["HvLoader.efi", "lxhvloader.dll", "Windows"] { + match fs::symlink_metadata(bundle.join(marker)) { + Ok(_) => { + mshv::slot::validate_bundle(&bundle)?; + return Ok(true); + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error).context("Failed to inspect MSHV BOOT payload"), + } + } + Ok(false) +} + /// 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 diff --git a/docs/Explanation/Bootloader-Configuration.md b/docs/Explanation/Bootloader-Configuration.md index 35528a25cd..e19ab99927 100644 --- a/docs/Explanation/Bootloader-Configuration.md +++ b/docs/Explanation/Bootloader-Configuration.md @@ -62,9 +62,10 @@ Enable the flag during installation or first-update ACL adoption, and keep it enabled for subsequent updates. Changing MSHV mode on an existing installation, combining it with `preserveMshvEspPayload`, raw/disk-streaming installation, and TPM/PCR-bound -encryption are rejected. First-update ACL adoption validates the existing -BOOT bundle and seeds the complete AZLA payload, following the normal ACL -bootstrap. Offline-init adoption and mode conversion on an already-managed +encryption are rejected. First-update ACL adoption discovers slot-owned mode +from a complete existing BOOT bundle and requires the request to match it. +It seeds the complete AZLA payload, following the normal ACL bootstrap. +Offline-init adoption and mode conversion on an already-managed installation remain disabled. Staging validates the bundle and checks peak ESP allocation before clearing From abc120779e7bcecc0ed2146b7ecb17644121641d Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 21:48:43 +0000 Subject: [PATCH 07/82] Document offline MSHV initialization support limit Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/init/offline/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index 2fde06715c..f246603638 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -510,6 +510,8 @@ pub fn execute( generate_host_status(&history, lsblk_output, lazy_partitions, disk)? }; + // MSHV-enabled ACL images are not currently supported by offline initialization. + // Reject explicit slot-owned mode; this path does not discover MSHV payloads. crate::engine::mshv::validate_transition(&Default::default(), &host_status.spec)?; debug!( From 1904245a6b5aef15e0bf5474f2af5f88e01063c2 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 21:50:20 +0000 Subject: [PATCH 08/82] Explain early MSHV mode-transition validation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/update.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/trident/src/engine/update.rs b/crates/trident/src/engine/update.rs index e597d52bdf..c929018687 100644 --- a/crates/trident/src/engine/update.rs +++ b/crates/trident/src/engine/update.rs @@ -59,6 +59,8 @@ pub(crate) fn update( image: Some(image), })?; + // Reject slot-owned MSHV mode changes before servicing selection so even + // requests classified as no-op updates cannot bypass the transition guard. engine::mshv::validate_transition(&ctx.spec_old, &ctx.spec)?; // Before starting an update servicing, need to validate that the active volume is set From ee05d864d9171c8f97c8c19da300d4ef807cd438 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 21:53:14 +0000 Subject: [PATCH 09/82] Document x64-only slot payload list Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/subsystems/esp/mshv/slot.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/trident/src/subsystems/esp/mshv/slot.rs b/crates/trident/src/subsystems/esp/mshv/slot.rs index 914b2d48dc..a91e7f5dae 100644 --- a/crates/trident/src/subsystems/esp/mshv/slot.rs +++ b/crates/trident/src/subsystems/esp/mshv/slot.rs @@ -7,6 +7,7 @@ use trident_api::{config::UefiFallbackMode, constants::EFI_DEFAULT_BIN_RELATIVE_ use crate::engine::{boot::uki, EngineContext}; +// This hardcoded x64 payload list limits the current implementation to x86-64. const FILES: &[&str] = &[ "bootx64.efi", "grubx64.efi", From 3fe19a827e4c892199fa6b37a424e1f62c793366 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 21:53:55 +0000 Subject: [PATCH 10/82] Document slot payload helper contracts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/subsystems/esp/mshv/slot.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/trident/src/subsystems/esp/mshv/slot.rs b/crates/trident/src/subsystems/esp/mshv/slot.rs index a91e7f5dae..e2774286e0 100644 --- a/crates/trident/src/subsystems/esp/mshv/slot.rs +++ b/crates/trident/src/subsystems/esp/mshv/slot.rs @@ -21,6 +21,8 @@ const FILES: &[&str] = &[ const SPACE_RESERVE: u64 = 1024 * 1024; +/// Checks allowed entries without requiring every payload file to be present. +/// Replacement destinations may also contain known `.new` and `.old` files. fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { ensure!( fs::symlink_metadata(directory)?.is_dir(), @@ -61,6 +63,8 @@ fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { Ok(()) } +/// Requires the complete supported payload and rejects unexpected entries. +/// Validates layout, not executable contents or the running hypervisor. pub(crate) fn validate_bundle(root: &Path) -> Result<()> { validate_tree(root, root, false)?; for name in FILES { @@ -74,6 +78,8 @@ pub(crate) fn validate_bundle(root: &Path) -> Result<()> { Ok(()) } +/// Estimates allocated bytes using the destination cluster size, including directories. +/// Missing paths contribute zero. fn allocation(path: &Path, cluster: u64) -> Result { let metadata = match fs::symlink_metadata(path) { Ok(metadata) => metadata, @@ -95,6 +101,7 @@ fn allocation(path: &Path, cluster: u64) -> Result { Ok(total) } +/// Requires room for the incoming allocation plus a reserve, crediting planned reclamation. fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<()> { ensure!( available.saturating_add(reclaimed) >= required.saturating_add(SPACE_RESERVE), @@ -104,6 +111,8 @@ fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<()> { Ok(()) } +/// Estimates staging space for the slot bundle, UKIs, addons, and an enabled fallback copy. +/// Credits inactive-slot contents and UKIs/addons scheduled for removal before staging. pub(crate) fn preflight_staging( ctx: &EngineContext, source_esp: &Path, @@ -128,6 +137,7 @@ pub(crate) fn preflight_staging( check_space(stats.blocks_available() * cluster, reclaimed, required) } +/// Checks room for a new bundle copy without reclaiming existing ESP contents. pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<()> { let stats = statvfs(esp)?; let cluster = stats.fragment_size(); @@ -139,6 +149,8 @@ pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<()> { ) } +/// Copies a complete validated bundle into an allowlisted destination. +/// Callers are responsible for temporary-directory staging and atomic publication. pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { validate_bundle(from)?; fs::create_dir_all(to)?; @@ -151,6 +163,8 @@ pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { Ok(()) } +/// Publishes the fallback bundle using per-file `.new` and `.old` names. +/// Reconciles leftover `.old` files, but whole-bundle replacement is not atomic. pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<()> { validate_bundle(from)?; match fs::symlink_metadata(to) { From b5a01070ccc0e8e537cb2cdee96e0fc7f739cdff Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 21:59:47 +0000 Subject: [PATCH 11/82] Clarify read-only UKI removal selection helper Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/boot/uki.rs | 4 ++-- crates/trident/src/subsystems/esp/mshv/slot.rs | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index 62a1b9e74c..5b95a41564 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -240,14 +240,14 @@ pub fn cleanup_ukis_before_staging( esp_mount_path: &Path, ) -> Result<(), Error> { let esp_uki_directory = join_relative(mount_point, esp_mount_path).join(UKI_DIRECTORY); - for path in ukis_removed_before_staging(ctx, &esp_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(()) } -pub(crate) fn ukis_removed_before_staging( +pub(crate) fn find_ukis_to_remove_before_staging( ctx: &EngineContext, esp_uki_directory: &Path, ) -> Result, Error> { diff --git a/crates/trident/src/subsystems/esp/mshv/slot.rs b/crates/trident/src/subsystems/esp/mshv/slot.rs index e2774286e0..f41d50e4e4 100644 --- a/crates/trident/src/subsystems/esp/mshv/slot.rs +++ b/crates/trident/src/subsystems/esp/mshv/slot.rs @@ -131,7 +131,9 @@ pub(crate) fn preflight_staging( required += bundle.max(allocation(&existing_fallback, cluster)?); } let mut reclaimed = allocation(target_bundle, cluster)?; - for path in uki::ukis_removed_before_staging(ctx, &destination_esp.join(uki::UKI_DIRECTORY))? { + for path in + uki::find_ukis_to_remove_before_staging(ctx, &destination_esp.join(uki::UKI_DIRECTORY))? + { reclaimed += allocation(&path, cluster)? + allocation(&uki_addon_dir(&path), cluster)?; } check_space(stats.blocks_available() * cluster, reclaimed, required) From 8527cc5342b75ff272b983a477300823a749bf94 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 22:01:25 +0000 Subject: [PATCH 12/82] Document new ESP validation and discovery functions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/subsystems/esp.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 6ad5f3431a..62f280881a 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -51,6 +51,7 @@ impl Subsystem for EspSubsystem { "esp" } + /// Applies slot-owned MSHV support restrictions before ESP servicing. fn validate_host_config(&self, ctx: &EngineContext) -> Result<(), TridentError> { crate::engine::mshv::validate_configuration(ctx) } @@ -740,6 +741,8 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { Ok(()) } +/// Detects slot-owned MSHV in BOOT, requiring the complete bundle when markers exist. +/// No markers means mode off; incomplete bundles and inspection errors fail discovery. pub(crate) fn has_slot_mshv_bundle(esp_path: &Path) -> Result { let bundle = esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH); for marker in ["HvLoader.efi", "lxhvloader.dll", "Windows"] { From 87a453e03b9b55ea8ec186b78f9ab7937e568d68 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 22:02:11 +0000 Subject: [PATCH 13/82] Explain provisioning-time MSHV validation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/subsystems/esp.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 62f280881a..6f530069ee 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -58,6 +58,7 @@ impl Subsystem for EspSubsystem { #[tracing::instrument(name = "esp_provision", skip_all)] fn provision(&mut self, ctx: &EngineContext, mount_path: &Path) -> Result<(), TridentError> { + // Recheck MSHV constraints here rather than relying solely on prior validation. crate::engine::mshv::validate_configuration(ctx)?; // Perform file-based deployment of ESP images, if needed, after filesystems have been // mounted and initialized. From 38b83e17a51a71a9c50e68db0903098fffa6fb1f Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 22:23:02 +0000 Subject: [PATCH 14/82] Select validated update slot for conservative fallback commit Use the shared selector for both ordinary and MSHV payloads. Cover both update directions with distinct slot contents. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/subsystems/esp.rs | 80 +++++++++++++++++++++------- 1 file changed, 61 insertions(+), 19 deletions(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 6f530069ee..d41a08533f 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -88,16 +88,7 @@ pub fn set_uefi_fallback_contents( servicing_state: ServicingState, mount_point: &Path, ) -> Result<(), Error> { - let source_esp_dir_name = if crate::engine::mshv::enabled(&ctx.spec) - && servicing_state == ServicingState::AbUpdateFinalized - && ctx.spec.os.uefi_fallback == UefiFallbackMode::Conservative - { - // Commit still holds the pre-update active volume until validation finishes. - ctx.get_ab_update_volume() - .map(|volume| boot::make_esp_dir_name(ctx.install_index, volume)) - } else { - find_uefi_fallback_source_dir_name(ctx, servicing_state) - }; + let source_esp_dir_name = find_uefi_fallback_source_dir_name(ctx, servicing_state); if let Some(source_esp_dir_name) = source_esp_dir_name { debug!( "Configuring UEFI fallback for servicing state {:?} using source ESP dir '{}'", @@ -542,13 +533,12 @@ 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 => { + // Commit still records the pre-update active slot. Refresh fallback + // from the newly validated update target, after health checks pass. + 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 { @@ -1306,8 +1296,16 @@ 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", + Some("AZLB".to_string()), // in commit, copy from the validated update target + "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, @@ -1409,6 +1407,50 @@ mod tests { ); } + #[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 From 5ca0440f86a4f25fb29506e7c1f2b89d9a39b062 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 22:26:06 +0000 Subject: [PATCH 15/82] Keep boot-validation context comment with its construction Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/rollback.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 4b8faac8d5..e706ce3e93 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -80,7 +80,6 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result ServicingType::NoActiveServicing, }; - // Create an EngineContext based on the Host Status if current_servicing_state != ServicingState::CleanInstallFinalized { super::mshv::validate_transition( &datastore.host_status().spec_old, @@ -96,6 +95,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Date: Wed, 11 Nov 2026 22:26:49 +0000 Subject: [PATCH 16/82] Explain commit mode validation and clean-install exemption Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/rollback.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index e706ce3e93..46dab02cea 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -80,6 +80,8 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result ServicingType::NoActiveServicing, }; + // Commit and recovery must preserve the installation's slot-owned MSHV mode. + // CleanInstallFinalized has no previous installed mode, so there is no transition to validate. if current_servicing_state != ServicingState::CleanInstallFinalized { super::mshv::validate_transition( &datastore.host_status().spec_old, From 1a7414ad8809fe8cdd91375949cadde61a50d451 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 22:27:31 +0000 Subject: [PATCH 17/82] Explain retained configuration during recovery validation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/rollback.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 46dab02cea..ebfa4a1c1f 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -88,6 +88,8 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Date: Wed, 11 Nov 2026 22:31:02 +0000 Subject: [PATCH 18/82] Simplify and explain hypervisor validation inputs Pass configuration and slot identity directly instead of constructing a retained-only engine context. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/mshv.rs | 9 +++++--- crates/trident/src/engine/rollback.rs | 31 +++++++++++++-------------- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index d77a012d31..2acef8d1a8 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -70,13 +70,16 @@ pub(crate) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE Ok(()) } +/// Hypervisor identity-validation hook for the expected installation and slot. +/// Currently assumes success until runtime identity detection is implemented. pub(crate) fn validate_active_hypervisor( - ctx: &EngineContext, + spec: &HostConfiguration, + install_index: usize, expected_volume: Option, ) -> Result<(), TridentError> { - if enabled(&ctx.spec) { + if enabled(spec) { let expected_directory = - expected_volume.map(|volume| boot::make_esp_dir_name(ctx.install_index, volume)); + expected_volume.map(|volume| boot::make_esp_dir_name(install_index, volume)); // TODO: Identify the running hypervisor and compare it with the expected OS payload. // Deliberately assume success until the identity mechanism is implemented. warn!( diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index ebfa4a1c1f..2711892f37 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -126,29 +126,28 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Date: Wed, 11 Nov 2026 22:35:45 +0000 Subject: [PATCH 19/82] Separate health and hypervisor recovery match arms Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/rollback.rs | 38 +++++++++++++++------------ 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 2711892f37..f6f1852c95 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -192,8 +192,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result { + (true, ServicingState::AbUpdateHealthCheckFailed) => { // AbUpdateHealthCheckFailed, when booting from expected device (the servicing OS), mark host // status state as Provisioned info!("Rollback to servicing OS succeeded, setting host status from {current_servicing_state:?} to Provisioned"); @@ -203,27 +202,32 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result { + // Restore the retained OS's status, but still report the rejected update's failure. + info!("Rollback to servicing OS succeeded, setting host status from {current_servicing_state:?} to Provisioned"); + datastore.with_host_status(|host_status| { + host_status.spec = host_status.spec_old.clone(); + host_status.spec_old = Default::default(); + host_status.servicing_state = ServicingState::Provisioned; + })?; + + return Err(TridentError::new( + ServicingError::ValidateAbActiveHypervisor { + expected_slot: ctx + .get_ab_update_volume() + .map(|volume| super::boot::make_esp_dir_name(ctx.install_index, volume)) + .unwrap_or_default(), + observed_slot: None, + }, + )) + .message("Rollback to the retained OS succeeded after hypervisor validation failed"); + } (false, ServicingState::AbUpdateFinalized) => { // AbUpdateFinalize, when booting from incorrect device (the servicing OS), mark host status // state as Provisioned From c2c6a482aa9640e8dbba0ae6003b4b8572dce43f Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 22:39:05 +0000 Subject: [PATCH 20/82] Explain manual rollback mode-transition validation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/manual_rollback/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/trident/src/engine/manual_rollback/mod.rs b/crates/trident/src/engine/manual_rollback/mod.rs index b9bb766902..83952fcadd 100644 --- a/crates/trident/src/engine/manual_rollback/mod.rs +++ b/crates/trident/src/engine/manual_rollback/mod.rs @@ -149,6 +149,8 @@ pub fn execute_rollback( }; staged_rollback_type = Some(rollback_type); + // Historical rollback targets must preserve the installation's slot-owned + // MSHV mode, just like update requests; reject mode changes before staging. engine::mshv::validate_transition(&datastore.host_status().spec, &requested_rollback.spec)?; let engine_context = EngineContext::new(EngineContextParams { From 88e7b8b1f97011cb14a36f2c194b9607a93ce710 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 22:58:57 +0000 Subject: [PATCH 21/82] Document MSHV boot and slot-owned servicing separately Explain the boot scenario, complete payload hierarchy, configuration and fallback behavior. Link the standalone page from bootloader configuration. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- docs/Explanation/Bootloader-Configuration.md | 30 +---- docs/Explanation/MSHV.md | 130 +++++++++++++++++++ 2 files changed, 132 insertions(+), 28 deletions(-) create mode 100644 docs/Explanation/MSHV.md diff --git a/docs/Explanation/Bootloader-Configuration.md b/docs/Explanation/Bootloader-Configuration.md index e19ab99927..2c77c56d9e 100644 --- a/docs/Explanation/Bootloader-Configuration.md +++ b/docs/Explanation/Bootloader-Configuration.md @@ -48,34 +48,8 @@ The bootloader choice (and choice of UKI) has some implications on ## Bootloader Servicing -### Experimental slot-owned MSHV payloads - -For x86-64 ACL UKI COSIs built with the matching efitreeloader prefix resolver, -`internalParams.mshvSlotEspPayload: true` copies the complete `EFI/BOOT` -bundle into the target slot. The bundle contains `bootx64.efi`, `grubx64.efi`, -`second.efi`, `HvLoader.efi`, `lxhvloader.dll` and -`Windows/System32/{hvix64.exe,hvax64.exe,kdstub.dll}`. -UKIs and addons remain in `EFI/Linux`; existing firmware and UKI selectors -are unchanged. - -Enable the flag during installation or first-update ACL adoption, and keep it -enabled for subsequent updates. Changing -MSHV mode on an existing installation, combining it with -`preserveMshvEspPayload`, raw/disk-streaming installation, and TPM/PCR-bound -encryption are rejected. First-update ACL adoption discovers slot-owned mode -from a complete existing BOOT bundle and requires the request to match it. -It seeds the complete AZLA payload, following the normal ACL bootstrap. -Offline-init adoption and mode conversion on an already-managed -installation remain disabled. - -Staging validates the bundle and checks peak ESP allocation before clearing -the inactive slot. Existing fallback modes apply to the complete nested bundle. -A separate hypervisor-validation failure state supports recovery to the -retained OS without classifying the failure as a user health-check failure. - -**Hypervisor identity validation is currently a success stub.** Commit and -rollback call the hook, but cannot yet detect a mixed hypervisor/OS boot. -This experimental implementation is not production or boot-validated. +For ACL images with MSHV, see [MSHV](./MSHV.md) for the boot chain, +slot-owned payload layout, and servicing requirements. :::note Trident handles bootloader servicing for A/B updates without any required user diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md new file mode 100644 index 0000000000..8e785546c3 --- /dev/null +++ b/docs/Explanation/MSHV.md @@ -0,0 +1,130 @@ +# MSHV + +Azure Container Linux (ACL) images with MSHV support boot Linux as the root +partition of the Microsoft hypervisor. Servicing these images requires keeping +the hypervisor's boot payload together with the OS version that uses it. +Trident's slot-owned MSHV mode extends [A/B updates](./AB-Update.md) to manage +that payload alongside each OS slot. + +## How MSHV Boot Differs + +In an ordinary UKI-based image, shim starts systemd-boot, which loads the +selected Unified Kernel Image (UKI). An MSHV image adds efitreeloader and +hypervisor-loading components before systemd-boot: + +```text +UEFI + -> shim (bootx64.efi) + -> efitreeloader (grubx64.efi) + -> HvLoader.efi -> lxhvloader.dll -> hypervisor payload preparation + -> systemd-boot (second.efi) -> selected UKI -> Linux with MSHV support +``` + +Despite its filename, `grubx64.efi` in this bundle is efitreeloader, not GRUB. +HvLoader prepares the hypervisor-loading interface before systemd-boot loads +the Linux UKI. + +A shared-path MSHV layout keeps hypervisor 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 payload used by the retained OS. + +Slot-owned servicing instead keeps the complete boot payload in each slot +directory. The matching efitreeloader prefix resolver locates its dependencies +relative to the directory from which it runs. The same bundle can consequently +run from a managed slot or from the UEFI fallback directory without referring +to another slot's hypervisor files. + +Firmware boot-entry and UKI selection mechanisms remain unchanged; the +difference is which additional files belong to each slot. + +## Payload Layout + +The source COSI must contain this complete bundle. Paths below 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 +``` + +Trident copies all eight files, preserving the nested directories. For the +first OS installation, the managed layout is: + +```text +EFI/ ++-- BOOT/ (fallback copy of a selected slot's complete bundle) ++-- AZLA/ (complete slot A bundle) ++-- AZLB/ (complete slot B bundle, 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 bundles. 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 complete BOOT bundle and built with +the matching efitreeloader prefix resolver. Include this flag in the +[Host Configuration](../Reference/Host-Configuration/API-Reference/HostConfiguration.md): + +```yaml +internalParams: + mshvSlotEspPayload: true +``` + +Enable the flag during clean installation or first-update ACL adoption, and +keep it enabled for subsequent updates. + +For first-update adoption, Trident discovers the mode from the installed +image's BOOT bundle and requires the request to match. It seeds the complete +AZLA bundle before persisting the discovered HostStatus. Incomplete MSHV +bundles fail discovery; legacy shared files outside BOOT do not establish +slot-owned mode. + +## Updates, Fallback, and Rollback + +Staging validates the source bundle and estimates the ESP space required +before clearing the target slot directory. It then copies the complete +bundle into the inactive slot and stages the OS's UKI and addons using the +normal UKI servicing flow. The retained slot's bundle is not replaced. + +[UEFI fallback modes](./UEFI-Fallback.md) apply to the complete BOOT bundle: + +| Mode | Before the update reboot | After successful boot validation and health checks | +| --- | --- | --- | +| `conservative` | BOOT contains the retained slot's bundle. | Commit refreshes BOOT from the validated update target. | +| `optimistic` | BOOT already contains the update target's bundle. | No further fallback copy is needed. | +| `disabled` | Trident does not populate BOOT. | No fallback copy is performed. | + +Rollback selects the retained OS slot and its corresponding payload. +A separate hypervisor-validation failure state supports automatic recovery +without classifying an identity failure as a user health-check failure. + +## Current Limitations + +The current implementation is limited to x86-64 ACL UKI images because the +payload definition hardcodes x64 filenames. It requires file-based ESP +deployment. Raw/disk-streaming installation, TPM/PCR-bound encryption, and +combining this mode with `preserveMshvEspPayload` are rejected. + +Offline initialization of MSHV-enabled ACL images is not currently supported. +Changing slot-owned mode on an already-managed installation is also rejected. + +**Hypervisor identity validation currently assumes success.** Commit and +rollback invoke the hook, but it does 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. From b5aa942cad4584ba1668e35a421a5140b94a2d43 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 23:02:50 +0000 Subject: [PATCH 22/82] Link efitreeloader repository from MSHV documentation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- docs/Explanation/MSHV.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index 8e785546c3..500b7635cc 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -9,8 +9,9 @@ that payload alongside each OS slot. ## How MSHV Boot Differs In an ordinary UKI-based image, shim starts systemd-boot, which loads the -selected Unified Kernel Image (UKI). An MSHV image adds efitreeloader and -hypervisor-loading components before systemd-boot: +selected Unified Kernel Image (UKI). An MSHV image adds +[efitreeloader](https://github.com/microsoft/efitreeloader) and hypervisor-loading +components before systemd-boot: ```text UEFI From da5d234c6e6142829c45d45ad9266fd30a023c2c Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 23:07:27 +0000 Subject: [PATCH 23/82] Clarify MSHV disk streaming and recorded-mode restrictions Distinguish prepared-image boot from slot-owned initialization and describe rejected flag changes explicitly. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- docs/Explanation/MSHV.md | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index 500b7635cc..673f7ba108 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -117,12 +117,45 @@ without classifying an identity failure as a user health-check failure. ## Current Limitations The current implementation is limited to x86-64 ACL UKI images because the -payload definition hardcodes x64 filenames. It requires file-based ESP -deployment. Raw/disk-streaming installation, TPM/PCR-bound encryption, and +payload definition hardcodes x64 filenames. TPM/PCR-bound encryption and combining this mode with `preserveMshvEspPayload` are rejected. Offline initialization of MSHV-enabled ACL images is not currently supported. -Changing slot-owned mode on an already-managed installation is also rejected. + +### Disk Streaming + +[Disk streaming](./Disk-Streaming.md) preserves the image's partition contents +rather than preparing slot-owned ESP bundles. A correctly prepared MSHV image +may already contain the required boot layout; streaming itself does not +inherently prevent that image from booting. + +The current configuration validator rejects `mshvSlotEspPayload: true` during +disk-streaming execution. This is a restriction on initializing slot-owned +management through that path, not a blanket prohibition on streaming an +MSHV-capable image. Later slot-owned updates require either valid persisted +HostStatus with the matching mode or first-update ACL adoption as described +above. Booting a prepared image through disk streaming has not been validated +as part of this implementation. + +### Changing the Recorded Mode + +Here, "mode" means the `internalParams.mshvSlotEspPayload` flag, not whether +the kernel supports MSHV. An installation is already managed once Trident has +persisted its HostStatus. Subsequent update requests and historical +configurations selected for manual rollback must retain the recorded flag: + +* If recorded as enabled, keep `mshvSlotEspPayload: true`. Setting it to false + or omitting it from an update request is rejected. +* If recorded as disabled, setting `mshvSlotEspPayload: true` is rejected, + even if the new COSI contains an MSHV bundle. + +Trident does not convert an existing shared/non-MSHV payload layout into +slot-owned management, or convert a slot-owned installation back out of it. +Normal A/B updates and rollbacks that retain the same flag remain supported. +The initial mode is established during clean installation or discovered +during first-update ACL adoption, before an installation is already managed. + +### Hypervisor Identity **Hypervisor identity validation currently assumes success.** Commit and rollback invoke the hook, but it does not yet identify the running hypervisor From fbc81f07637c5760ddec69b9d8920aa4fe812b2a Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 23:10:33 +0000 Subject: [PATCH 24/82] Remove disk streaming from MSHV limitations Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- docs/Explanation/MSHV.md | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index 673f7ba108..b13b73c795 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -122,21 +122,6 @@ combining this mode with `preserveMshvEspPayload` are rejected. Offline initialization of MSHV-enabled ACL images is not currently supported. -### Disk Streaming - -[Disk streaming](./Disk-Streaming.md) preserves the image's partition contents -rather than preparing slot-owned ESP bundles. A correctly prepared MSHV image -may already contain the required boot layout; streaming itself does not -inherently prevent that image from booting. - -The current configuration validator rejects `mshvSlotEspPayload: true` during -disk-streaming execution. This is a restriction on initializing slot-owned -management through that path, not a blanket prohibition on streaming an -MSHV-capable image. Later slot-owned updates require either valid persisted -HostStatus with the matching mode or first-update ACL adoption as described -above. Booting a prepared image through disk streaming has not been validated -as part of this implementation. - ### Changing the Recorded Mode Here, "mode" means the `internalParams.mshvSlotEspPayload` flag, not whether From d0df6229745bf541973d8f7571fb1f53c446d4d4 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 23:11:39 +0000 Subject: [PATCH 25/82] Simplify MSHV identity-validation limitation wording Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- docs/Explanation/MSHV.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index b13b73c795..7d8228959b 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -143,7 +143,7 @@ during first-update ACL adoption, before an installation is already managed. ### Hypervisor Identity **Hypervisor identity validation currently assumes success.** Commit and -rollback invoke the hook, but it does not yet identify the running hypervisor +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. From 452cf2fe42bf4b6fbe42af83f5ce8b415a723615 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 23:13:37 +0000 Subject: [PATCH 26/82] Define successful MSHV identity validation against active slot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- docs/Explanation/MSHV.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index 7d8228959b..858aa7ff37 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -142,8 +142,9 @@ during first-update ACL adoption, before an installation is already managed. ### Hypervisor Identity -**Hypervisor identity validation currently assumes success.** 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. +**Hypervisor identity validation currently assumes success**, meaning that the +running hypervisor matches the hypervisor payload in the active OS slot's +`EFI/AZLA` or `EFI/AZLB` directory. 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. From fe304605e6bb6716792b33d030f9bf30fe004402 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 11 Nov 2026 23:50:22 +0000 Subject: [PATCH 27/82] Make MSHV configuration test architecture-aware Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3fe6d65-a531-4d83-a1bd-4c2c38a03fee --- crates/trident/src/engine/mshv.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index 2acef8d1a8..c93bd76e5d 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -126,7 +126,10 @@ mod tests { ctx.spec.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); assert!(validate_configuration(&ctx).is_err()); ctx.is_stream_image = false; - assert!(validate_configuration(&ctx).is_ok()); + assert_eq!( + validate_configuration(&ctx).is_ok(), + cfg!(target_arch = "x86_64"), + ); ctx.spec.storage.encryption = Some(trident_api::config::Encryption { pcrs: vec![sysdefs::tpm2::Pcr::Pcr4], ..Default::default() From dd280ab9e7ca8c606f1628033b1af46ee3edbdd8 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Thu, 12 Nov 2026 16:53:41 +0000 Subject: [PATCH 28/82] Move shared MSHV bundle helpers into boot module Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 80a35139-3390-48e7-be09-b448aa8769c8 --- crates/trident/src/engine/boot/mod.rs | 1 + .../esp/mshv/slot.rs => engine/boot/mshv.rs} | 17 ++++++++++ crates/trident/src/init/acl/mod.rs | 4 +-- crates/trident/src/subsystems/esp.rs | 33 +++++-------------- crates/trident/src/subsystems/esp/mshv.rs | 2 -- 5 files changed, 28 insertions(+), 29 deletions(-) rename crates/trident/src/{subsystems/esp/mshv/slot.rs => engine/boot/mshv.rs} (95%) 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/subsystems/esp/mshv/slot.rs b/crates/trident/src/engine/boot/mshv.rs similarity index 95% rename from crates/trident/src/subsystems/esp/mshv/slot.rs rename to crates/trident/src/engine/boot/mshv.rs index f41d50e4e4..d7422eb2e1 100644 --- a/crates/trident/src/subsystems/esp/mshv/slot.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -21,6 +21,23 @@ const FILES: &[&str] = &[ const SPACE_RESERVE: u64 = 1024 * 1024; +/// Detects slot-owned MSHV in BOOT, requiring the complete bundle when markers exist. +/// No markers means mode off; incomplete bundles and inspection errors fail discovery. +pub(crate) fn has_slot_mshv_bundle(esp_path: &Path) -> Result { + let bundle = esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + for marker in ["HvLoader.efi", "lxhvloader.dll", "Windows"] { + match fs::symlink_metadata(bundle.join(marker)) { + Ok(_) => { + validate_bundle(&bundle)?; + return Ok(true); + } + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error).context("Failed to inspect MSHV BOOT payload"), + } + } + Ok(false) +} + /// Checks allowed entries without requiring every payload file to be present. /// Replacement destinations may also contain known `.new` and `.old` files. fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index 8f98fc6bc1..5a1fcc27dc 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -26,7 +26,7 @@ use trident_api::{ BlockDeviceId, }; -use crate::subsystems::esp; +use crate::engine::boot::mshv; const ACL_ESP_MOUNT_POINT: &str = "/boot"; @@ -304,7 +304,7 @@ fn inner_initial_host_status( partition_paths, ..Default::default() }; - if esp::has_slot_mshv_bundle(esp_path)? { + if mshv::has_slot_mshv_bundle(esp_path)? { host_status .spec .internal_params diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index d41a08533f..b719822d7c 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -365,8 +365,8 @@ fn copy_file_artifacts( let slot_mshv = crate::engine::mshv::enabled(&ctx.spec); let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); let boot_files = if slot_mshv { - mshv::slot::validate_bundle(&source_bundle)?; - mshv::slot::preflight_staging( + boot::mshv::validate_bundle(&source_bundle)?; + boot::mshv::preflight_staging( ctx, temp_mount_dir, &path::join_relative(mount_point, &ctx.esp_mount_path), @@ -404,7 +404,7 @@ fn copy_file_artifacts( // Call helper func to copy boot files from temp_mount_dir to esp_dir_path let grub_noprefix = if slot_mshv { - mshv::slot::copy_bundle(&source_bundle, &esp_dir_path)?; + boot::mshv::copy_bundle(&source_bundle, &esp_dir_path)?; false } else { copy_boot_files(temp_mount_dir, &esp_dir_path, boot_files).context(format!( @@ -616,7 +616,7 @@ fn copy_boot_files_for_uefi_fallback( uefi_fallback_path.display() ); let result = if slot_mshv { - mshv::slot::replace_bundle(&source_esp_dir_path, &uefi_fallback_path) + boot::mshv::replace_bundle(&source_esp_dir_path, &uefi_fallback_path) } else { replace_boot_files(&source_esp_dir_path, &uefi_fallback_path) }; @@ -732,23 +732,6 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { Ok(()) } -/// Detects slot-owned MSHV in BOOT, requiring the complete bundle when markers exist. -/// No markers means mode off; incomplete bundles and inspection errors fail discovery. -pub(crate) fn has_slot_mshv_bundle(esp_path: &Path) -> Result { - let bundle = esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH); - for marker in ["HvLoader.efi", "lxhvloader.dll", "Windows"] { - match fs::symlink_metadata(bundle.join(marker)) { - Ok(_) => { - mshv::slot::validate_bundle(&bundle)?; - return Ok(true); - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(error).context("Failed to inspect MSHV BOOT payload"), - } - } - Ok(false) -} - /// 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 @@ -758,9 +741,9 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> Result< let azla_esp_path = esp_path.join(ESP_EFI_DIRECTORY).join("AZLA"); let boot_esp_path = esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH); if slot_mshv { - mshv::slot::validate_bundle(&boot_esp_path)?; + boot::mshv::validate_bundle(&boot_esp_path)?; if azla_esp_path.exists() { - return mshv::slot::validate_bundle(&azla_esp_path); + return boot::mshv::validate_bundle(&azla_esp_path); } } trace!("Checking for AZLA volume ESP path at {:?}", &azla_esp_path); @@ -784,8 +767,8 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> Result< ))?; } let copy_result = if slot_mshv { - mshv::slot::preflight_bootstrap(&boot_esp_path, esp_path)?; - mshv::slot::copy_bundle(&boot_esp_path, &azla_tmp_path) + boot::mshv::preflight_bootstrap(&boot_esp_path, esp_path)?; + boot::mshv::copy_bundle(&boot_esp_path, &azla_tmp_path) } else { replace_boot_files(&boot_esp_path, &azla_tmp_path) }; diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 5378481585..c422405c2b 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -1,7 +1,5 @@ //! ACL, efitreeloader (ETL), and MSHV-related functionality for ESP provisioning. -pub(super) mod slot; - use std::{ fs, path::{Path, PathBuf}, From 7026c0b5947c63b813662f4bfcc18531e7aeb433 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Thu, 12 Nov 2026 22:11:47 +0000 Subject: [PATCH 29/82] Clarify MSHV servicing function and block comments Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3776b97-18ef-40d5-821f-dac82f77e3de --- crates/trident-client/src/preview.rs | 1 + crates/trident-client/src/protocol.rs | 1 + crates/trident-client/src/tests.rs | 1 + crates/trident/src/engine/boot/mshv.rs | 24 +++++-- crates/trident/src/engine/boot/uki.rs | 9 ++- .../trident/src/engine/manual_rollback/mod.rs | 2 + .../src/engine/manual_rollback/utils.rs | 5 ++ crates/trident/src/engine/mshv.rs | 10 ++- crates/trident/src/engine/rollback.rs | 30 ++++---- crates/trident/src/engine/update.rs | 1 + crates/trident/src/init/acl/mod.rs | 11 +++ crates/trident/src/init/offline/mod.rs | 5 +- crates/trident/src/lib.rs | 18 +++-- crates/trident/src/subsystems/esp.rs | 72 ++++++++++--------- 14 files changed, 127 insertions(+), 63 deletions(-) diff --git a/crates/trident-client/src/preview.rs b/crates/trident-client/src/preview.rs index 5bfd62d3e4..668c3882f5 100644 --- a/crates/trident-client/src/preview.rs +++ b/crates/trident-client/src/preview.rs @@ -49,6 +49,7 @@ pub enum ServicingState { ManualRollbackAbFinalized, Provisioned, AbUpdateHealthCheckFailed, + /// The trial OS booted, but hypervisor validation failed and automatic recovery is pending. AbUpdateHypervisorCheckFailed, Unknown(i32), } diff --git a/crates/trident-client/src/protocol.rs b/crates/trident-client/src/protocol.rs index 4a25dfd3b4..14d825a58b 100644 --- a/crates/trident-client/src/protocol.rs +++ b/crates/trident-client/src/protocol.rs @@ -286,6 +286,7 @@ fn decode_location(location: ProtoFileLocation) -> SourceLocation { } } +/// Decodes preview servicing states, including hypervisor recovery, preserving unknown wire values. #[cfg(feature = "preview")] pub(crate) fn decode_servicing_state(state: i32) -> ServicingState { match ProtoServicingState::try_from(state) { diff --git a/crates/trident-client/src/tests.rs b/crates/trident-client/src/tests.rs index 36ce17c6c2..89027543e6 100644 --- a/crates/trident-client/src/tests.rs +++ b/crates/trident-client/src/tests.rs @@ -1485,6 +1485,7 @@ async fn preview_status_validation_and_rollback_use_domain_types() { assert_eq!(captured.validation_yaml.len(), 2); } +/// Preview decoding retains known recovery states and preserves unknown wire values. #[cfg(feature = "preview")] #[tokio::test] async fn preview_status_enums_preserve_known_unspecified_and_unknown_values() { diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index d7422eb2e1..47b4a7bd2e 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -38,8 +38,8 @@ pub(crate) fn has_slot_mshv_bundle(esp_path: &Path) -> Result { Ok(false) } -/// Checks allowed entries without requiring every payload file to be present. -/// Replacement destinations may also contain known `.new` and `.old` files. +/// Checks the case-insensitive allowlist, rejecting symlinks and special files. +/// Does not require completeness; `temporary` also permits known `.new` and `.old` files. fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { ensure!( fs::symlink_metadata(directory)?.is_dir(), @@ -82,6 +82,7 @@ fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { /// Requires the complete supported payload and rejects unexpected entries. /// Validates layout, not executable contents or the running hypervisor. +/// Required-path lookups rely on FAT's case-insensitive filename resolution. pub(crate) fn validate_bundle(root: &Path) -> Result<()> { validate_tree(root, root, false)?; for name in FILES { @@ -95,8 +96,8 @@ pub(crate) fn validate_bundle(root: &Path) -> Result<()> { Ok(()) } -/// Estimates allocated bytes using the destination cluster size, including directories. -/// Missing paths contribute zero. +/// Estimates cluster-rounded file bytes plus one cluster per directory. +/// Missing paths contribute zero; symlinks and special files are rejected. fn allocation(path: &Path, cluster: u64) -> Result { let metadata = match fs::symlink_metadata(path) { Ok(metadata) => metadata, @@ -169,7 +170,8 @@ pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<()> { } /// Copies a complete validated bundle into an allowlisted destination. -/// Callers are responsible for temporary-directory staging and atomic publication. +/// Overwrites matching files non-atomically; callers needing atomic publication +/// must stage in a temporary directory and rename it into place. pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { validate_bundle(from)?; fs::create_dir_all(to)?; @@ -183,7 +185,8 @@ pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { } /// Publishes the fallback bundle using per-file `.new` and `.old` names. -/// Reconciles leftover `.old` files, but whole-bundle replacement is not atomic. +/// Restores missing live files from `.old`, discards stale backups, and stages +/// every `.new` file before renaming live files. Whole-bundle replacement is not atomic. pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<()> { validate_bundle(from)?; match fs::symlink_metadata(to) { @@ -243,6 +246,7 @@ mod tests { use std::os::unix::fs::symlink; use tempfile::TempDir; + /// Creates all allowlisted payload files with deterministic test contents. fn bundle(root: &Path, contents: &[u8]) { for name in FILES { let path = root.join(name); @@ -251,6 +255,7 @@ mod tests { } } + /// Copying the candidate bundle must not modify the retained slot. #[test] fn copies_complete_bundle_without_touching_other_slots() { let temp = TempDir::new().unwrap(); @@ -266,6 +271,7 @@ mod tests { } } + /// Allowlist matching ignores case, but temporary names require explicit permission. #[test] fn accepts_fat_filename_casing_but_rejects_unknown_entries() { let temp = TempDir::new().unwrap(); @@ -284,6 +290,7 @@ mod tests { assert!(validate_tree(temp.path(), temp.path(), true).is_err()); } + /// Invalid sources must fail before creating the destination. #[test] fn rejects_incomplete_and_unexpected_payload_before_copy() { let temp = TempDir::new().unwrap(); @@ -299,6 +306,7 @@ mod tests { assert!(!target.exists()); } + /// Payload validation must not follow symlinks into an unrelated directory. #[test] fn rejects_source_and_destination_symlinks() { let temp = TempDir::new().unwrap(); @@ -316,6 +324,7 @@ mod tests { assert!(fs::read_dir(&outside).unwrap().next().is_none()); } + /// Retrying interrupted fallback publication replaces stale files and removes backups. #[test] fn retries_partial_publication_and_removes_only_known_temporary_files() { let temp = TempDir::new().unwrap(); @@ -341,6 +350,7 @@ mod tests { assert!(replace_bundle(&source, &source).is_err()); } + /// Capacity checks include cluster rounding, reclaimable space, and the reserve. #[test] fn capacity_accounts_for_clusters_and_preserves_a_reserve() { let temp = TempDir::new().unwrap(); @@ -350,6 +360,7 @@ mod tests { assert!(check_space(SPACE_RESERVE, 4096, 4096).is_ok()); } + /// An oversized staged UKI must fail preflight without changing either slot's payload. #[test] fn preflight_rejects_peak_allocation_before_mutating_inactive_or_retained_files() { let temp = TempDir::new().unwrap(); @@ -378,6 +389,7 @@ mod tests { } } + /// Fallback policy selects a complete bundle without overwriting the retained slot. #[test] fn fallback_modes_use_the_full_selected_bundle_during_trial_commit_and_rollback() { use trident_api::{ diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index 5b95a41564..a755622a66 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -233,7 +233,8 @@ fn remove_uki_and_addons(path: &Path) -> Result<(), Error> { /// 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. +/// UKI is no longer the sole rollback, and only for OS index 0, which owns it. +/// Associated addon directories are removed with each selected UKI. pub fn cleanup_ukis_before_staging( ctx: &EngineContext, mount_point: &Path, @@ -247,6 +248,8 @@ pub fn cleanup_ukis_before_staging( Ok(()) } +/// Lists the UKIs selected by pre-staging cleanup without modifying the ESP. +/// Capacity preflight uses the same selection to credit UKIs and their addon directories. pub(crate) fn find_ukis_to_remove_before_staging( ctx: &EngineContext, esp_uki_directory: &Path, @@ -262,7 +265,7 @@ pub(crate) fn find_ukis_to_remove_before_staging( let active_suffix = format!("{active_slot}.efi"); let trident_ukis = enumerate_trident_managed_ukis(esp_uki_directory)?; - // 1. Remove trident-managed UKIs for the target slot+os-index + // 1. Select trident-managed UKIs for the target slot+os-index // (all update indices, e.g. vmlinuz-100-azla0.efi, vmlinuz-102-azla0.efi). for (_index, suffix, path) in &trident_ukis { if *suffix == target_suffix { @@ -270,7 +273,7 @@ pub(crate) fn find_ukis_to_remove_before_staging( } } - // 2. Remove non-trident-managed UKIs only if: + // 2. 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 (proving the original is // superseded as rollback). diff --git a/crates/trident/src/engine/manual_rollback/mod.rs b/crates/trident/src/engine/manual_rollback/mod.rs index 83952fcadd..1755e0199d 100644 --- a/crates/trident/src/engine/manual_rollback/mod.rs +++ b/crates/trident/src/engine/manual_rollback/mod.rs @@ -91,6 +91,8 @@ pub fn check_rollback( /// `(ExitKind::Done, ServicingType::NoActiveServicing)` rather than a bare /// `ExitKind::Done` that's indistinguishable from a real rollback at the /// gRPC layer (see `ServicingResponse.servicing_kind` in servicing.proto). +/// +/// Rejects rollback targets that change the installation's slot-owned MSHV mode before staging. pub fn execute_rollback( datastore: &mut DataStore, requested_rollback_kind: ManualRollbackRequestKind, diff --git a/crates/trident/src/engine/manual_rollback/utils.rs b/crates/trident/src/engine/manual_rollback/utils.rs index 1edb8c2ba5..99e6ed8474 100644 --- a/crates/trident/src/engine/manual_rollback/utils.rs +++ b/crates/trident/src/engine/manual_rollback/utils.rs @@ -247,6 +247,9 @@ impl ManualRollbackContext { /// * an operation that cannot be rolled back is found /// * a HostStatus entry is None /// + /// Automatic rollback after health or hypervisor validation failure ends parsing, + /// so the rejected candidate is not offered as a manual rollback target. + /// /// Once the Operations have been parsed, the ManualRollback operations (both /// A/B and runtime) and the operations that they undo (both A/B and runtime /// updates) are pruned from the list of Operations. @@ -352,6 +355,7 @@ impl ManualRollbackContext { } ServicingState::AbUpdateHealthCheckFailed | ServicingState::AbUpdateHypervisorCheckFailed => { + // Automatic recovery ends rollback history at the failed candidate. current_operation.kind = OperationKind::AbUpdateAutoRollback; trace!("Detected AbUpdateAutoRollback operation, ending parsing here."); break; @@ -1025,6 +1029,7 @@ mod tests { rollback_context_testing(&host_status_list, "Validate A/B update health check failed"); } + /// Hypervisor-triggered recovery must bound manual rollback history like health failure. #[test] fn test_ab_update_hypervisor_check_failed() { let host_status_list = vec![ diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index c93bd76e5d..6f102a4ebb 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -9,6 +9,7 @@ use trident_api::{ use super::{boot, EngineContext}; +/// Builds an input error attributed to the slot-owned MSHV mode parameter. fn unsupported(reason: &str) -> TridentError { TridentError::new(InvalidInputError::InvalidInternalParameter { name: MSHV_SLOT_ESP_PAYLOAD.into(), @@ -16,10 +17,12 @@ fn unsupported(reason: &str) -> TridentError { }) } +/// Returns whether the configuration opts into slot-owned MSHV payloads. pub(crate) fn enabled(spec: &HostConfiguration) -> bool { spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD) } +/// Rejects enabling or disabling slot-owned MSHV on an established installation. pub(crate) fn validate_transition( previous: &HostConfiguration, requested: &HostConfiguration, @@ -32,6 +35,8 @@ pub(crate) fn validate_transition( Ok(()) } +/// Checks image, deployment, encryption, and mode-transition restrictions when MSHV is enabled. +/// Configurations without slot-owned MSHV are left to ordinary validation. pub(crate) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { if !enabled(&ctx.spec) { return Ok(()); @@ -71,7 +76,8 @@ pub(crate) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE } /// Hypervisor identity-validation hook for the expected installation and slot. -/// Currently assumes success until runtime identity detection is implemented. +/// Currently always succeeds; enabled configurations only log the expected slot. +/// It does not inspect the running hypervisor or validate payload contents. pub(crate) fn validate_active_hypervisor( spec: &HostConfiguration, install_index: usize, @@ -94,6 +100,7 @@ pub(crate) fn validate_active_hypervisor( mod tests { use super::*; + /// Established installations may retain their mode, but may not switch modes. #[test] fn rejects_mode_changes_but_allows_matching_installation_modes() { let ordinary = HostConfiguration::default(); @@ -105,6 +112,7 @@ mod tests { assert!(validate_transition(&mshv, &mshv).is_ok()); } + /// MSHV restrictions apply only after opt-in and reject unsupported deployment combinations. #[test] fn rejects_unsupported_mshv_images_without_affecting_other_images() { let mut ctx = EngineContext { diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index f6f1852c95..fde2d182c9 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -38,11 +38,10 @@ pub enum BootValidationResult { InvalidHypervisor(TridentError), } -/// Validates that the firmware did not perform a rollback, i.e. correctly booted from the updated -/// target OS image. -/// -/// 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. +/// Validates the expected boot device and invokes the MSHV identity hook (currently a success stub). +/// Commits finalized servicing on success, or reconciles status after firmware/automatic rollback. +/// Trial A/B validation failures can request recovery; recovery failures return an error +/// without requesting another rollback. Errors may leave Host Status unchanged. #[tracing::instrument(skip_all)] pub fn validate_boot(datastore: &mut DataStore) -> Result { info!("Validating whether host correctly booted from target OS image"); @@ -53,8 +52,8 @@ 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 + // After health or hypervisor validation fails, invert the recorded volume + // so the context's update target resolves to the retained servicing OS. ServicingState::AbUpdateHealthCheckFailed | ServicingState::AbUpdateHypervisorCheckFailed => { match datastore.host_status().ab_active_volume { @@ -126,8 +125,8 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result 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 + // Recovery after health or hypervisor validation failed to boot the + // servicing OS. Report the failure without changing Host Status. 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(), @@ -270,6 +268,8 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result ExpectedPartition<'a> { /// the expectations of the ACL image layout, and returns a HostStatus /// representing the current state of the host. This will be used to /// initialize the Trident datastore if it has not been created yet. +/// Discovers slot-owned MSHV from the host ESP without modifying its contents. pub fn initial_host_status() -> Result { let blk_devices = lsblk::list().context("Failed to run lsblk")?; let root_blk_device = blk_devices @@ -88,6 +89,7 @@ pub fn initial_host_status() -> Result { /// initial ACL HostStatus, separated from the code that gets the /// Host's current disk information. This allows for easier testing /// of the HostStatus creation logic. +/// A complete MSHV BOOT bundle enables slot-owned mode; incomplete marked bundles fail. fn inner_initial_host_status( disk_information: &SfDisk, root_blk_device: &BlockDevice, @@ -304,6 +306,7 @@ fn inner_initial_host_status( partition_paths, ..Default::default() }; + // Record the discovered mode only; the update path bootstraps AZLA before persisting it. if mshv::has_slot_mshv_bundle(esp_path)? { host_status .spec @@ -479,6 +482,7 @@ mod tests { } } + /// Creates a complete BOOT bundle for read-only ACL discovery tests. fn create_mshv_bundle(esp_path: &Path) { for name in [ "bootx64.efi", @@ -496,6 +500,7 @@ mod tests { } } + /// Only a complete BOOT bundle enables MSHV; discovery must not create AZLA. #[test] fn initial_host_status_discovers_slot_mshv_from_image() { let esp = tempfile::TempDir::new().unwrap(); @@ -520,6 +525,7 @@ mod tests { assert!(!esp.path().join("EFI/AZLA").exists()); } + /// A marked but incomplete BOOT bundle must fail adoption without creating AZLA. #[test] fn initial_host_status_rejects_incomplete_slot_mshv_payload() { let esp = tempfile::TempDir::new().unwrap(); @@ -548,6 +554,7 @@ mod tests { } } + /// Ordinary ACL partition discovery remains valid without MSHV ESP contents. #[test] fn test_inner_initial_host_status_success() { let sfdisk = create_sfdisk("efi-system", TestPartitions::Correct); @@ -685,6 +692,7 @@ mod tests { assert!(volume_pairs.iter().all(|p| p.id != "usr-hash-sig")); } + /// An unexpected ESP partition label must still fail with an empty test ESP. #[test] fn test_inner_initial_host_status_unexpected_part_name() { let wrong_label = "wrong-label"; @@ -705,6 +713,7 @@ mod tests { ))); } + /// Missing required partitions must be rejected before ESP discovery. #[test] fn test_inner_initial_host_status_missing_part() { let sfdisk = create_sfdisk("efi-system", TestPartitions::MissingOne); @@ -721,6 +730,7 @@ mod tests { .contains("Missing partition labels found on root disk")); } + /// Unrecognized partitions must not be silently adopted. #[test] fn test_inner_initial_host_status_extra_part() { let sfdisk = create_sfdisk("efi-system", TestPartitions::ExtraOne); @@ -737,6 +747,7 @@ mod tests { .contains("Unexpected partition label 'extra-one' found on root disk")); } + /// Duplicate partition labels must not produce an ambiguous HostStatus. #[test] fn test_inner_initial_host_status_duplicate_part() { let sfdisk = create_sfdisk("efi-system", TestPartitions::Duplicate); diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index f246603638..548dd83951 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. +/// Explicit slot-owned MSHV mode is rejected; this path does not discover MSHV bundles. pub fn execute( hs_path: Option<&Path>, lazy_partitions: &[String], @@ -510,8 +511,8 @@ pub fn execute( generate_host_status(&history, lsblk_output, lazy_partitions, disk)? }; - // MSHV-enabled ACL images are not currently supported by offline initialization. - // Reject explicit slot-owned mode; this path does not discover MSHV payloads. + // Reject explicit slot-owned mode before writing the datastore or bootstrapping AZLA. + // Unflagged MSHV payloads are not detected by this path. crate::engine::mshv::validate_transition(&Default::default(), &host_status.spec)?; debug!( diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index a8db449cb7..483c91670b 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -290,6 +290,8 @@ impl Trident { Ok(()) } + /// Runs an operation and records errors, preserving the original validation + /// failure if recovery after an A/B health or hypervisor failure returns an error. fn execute_and_record_error( &mut self, datastore: &mut DataStore, @@ -298,9 +300,8 @@ impl Trident { where F: FnOnce(&mut DataStore) -> Result, { - // AbUpdateHealthCheckFailed is a special case where we would like - // to preserve the last error across any recovery. This aids in - // surfacing the original error. + // Preserve the original health/hypervisor failure if recovery returns an error, + // rather than replacing it with a secondary recovery error. debug!( "Execute and record error with servicing state: {:?} and last error: {:?}", datastore.host_status().servicing_state, @@ -607,6 +608,8 @@ impl Trident { }) } + /// Adopts an untracked ACL host when needed, then stages/finalizes the requested update. + /// Adoption requires matching MSHV modes and a bootstrapped AZLA before persisting status. pub fn update( &mut self, datastore: &mut DataStore, @@ -636,6 +639,7 @@ impl Trident { .structured(InvalidInputError::DeriveHostConfiguration) .message("Failed to initialize host status for ACL")?; + // The requested mode must match the discovered BOOT payload before adoption. engine::mshv::validate_transition(&initial_host_status.spec, &host_config)?; // Mirror offline-initialize's bootstrap: ACL lazy adoption derives @@ -660,6 +664,7 @@ impl Trident { let esp_path = container::get_host_relative_path(esp_path.to_path_buf()) .message("Failed to resolve ESP path relative to host for ACL")?; + // Copy the complete nested bundle for MSHV, not just ordinary boot files. let slot_mshv = engine::mshv::enabled(&initial_host_status.spec); esp::bootstrap_azla_from_fallback(&esp_path, slot_mshv) .structured(InvalidInputError::InvalidBootConfiguration) @@ -810,12 +815,13 @@ impl Trident { self.install(datastore, Operations::all(), false, Some(image)) } + /// Validates finalized servicing or automatic recovery and reports its reboot disposition. + /// Only a fully provisioned result is reported to the orchestrator as success. 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 boots and recovery after health or hypervisor validation failure. let servicing_state = datastore.host_status().servicing_state; if !matches!( servicing_state, @@ -847,6 +853,7 @@ impl Trident { ) }); + // A validation result requesting rollback is not an orchestrator success. if matches!( rollback_result, Ok(rollback::BootValidationResult::ValidBootProvisioned) @@ -865,6 +872,7 @@ impl Trident { } Ok(rollback::BootValidationResult::InvalidHypervisor(e)) | Ok(rollback::BootValidationResult::ValidBootHealthCheckFailed(e)) => { + // The caller must reboot to complete automatic recovery. debug!("Boot validation requires rollback: {e:?}"); Ok((ExitKind::NeedsReboot, servicing_type)) } diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index b719822d7c..09edb46c2d 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -56,6 +56,7 @@ impl Subsystem for EspSubsystem { crate::engine::mshv::validate_configuration(ctx) } + /// Revalidates MSHV restrictions and deploys boot artifacts for file-based servicing. #[tracing::instrument(name = "esp_provision", skip_all)] fn provision(&mut self, ctx: &EngineContext, mount_path: &Path) -> Result<(), TridentError> { // Recheck MSHV constraints here rather than relying solely on prior validation. @@ -74,15 +75,11 @@ 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. /// -/// 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. +/// Before reboot, staged-state handling copies volume A for clean install, the candidate +/// for optimistic A/B update, or the retained slot for conservative A/B update. +/// Manual A/B rollback copies its target for either enabled fallback mode. +/// At A/B commit, conservative mode copies the validated update target; optimistic mode +/// needs no further copy. Disabled mode does not copy. Slot-owned MSHV copies the full bundle. pub fn set_uefi_fallback_contents( ctx: &EngineContext, servicing_state: ServicingState, @@ -327,6 +324,8 @@ where } /// Performs file-based update of stand-alone ESP volume by copying boot files. +/// Slot-owned MSHV validates the bundle and preflights capacity before reclaiming the +/// target slot's payload/UKIs; the retained slot's payload is left untouched. fn copy_file_artifacts( temp_image_path: &Path, ctx: &EngineContext, @@ -360,11 +359,11 @@ 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 + // MSHV uses a complete allowlisted bundle rather than the ordinary boot-file list. let slot_mshv = crate::engine::mshv::enabled(&ctx.spec); let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); let boot_files = if slot_mshv { + // Validate and budget peak allocation before deleting target-slot files or UKIs. boot::mshv::validate_bundle(&source_bundle)?; boot::mshv::preflight_staging( ctx, @@ -375,6 +374,7 @@ fn copy_file_artifacts( uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; Vec::new() } else { + // Refuse to deploy an MSHV bundle through the ordinary, partial boot-file path. ensure!( !source_bundle.join("HvLoader.efi").try_exists()?, "A slot-owned MSHV image requires internalParams.mshvSlotEspPayload" @@ -418,7 +418,7 @@ fn copy_file_artifacts( // 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. + // MSHV already reclaimed old UKIs after preflight; other UKI images clean up here. // 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 @@ -486,19 +486,20 @@ fn copy_file_artifacts( /// Determines the source dir name to copy the UEFI fallback boot files from. This varies /// based on the servicing state and UEFI fallback mode. /// -/// 1. During finalize +/// 1. Before reboot, when handling a staged servicing state: /// * 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) +/// - 'conservative': use the retained 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. +/// 2. During commit, after the target OS boot has been verified: /// * 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 +/// - 'conservative': use the validated update target, opposite the still-recorded active volume +/// +/// Disabled fallback and states not listed above select no source. fn find_uefi_fallback_source_dir_name( ctx: &EngineContext, servicing_state: ServicingState, @@ -584,7 +585,8 @@ fn skip_uefi_fallback_copy( false } -/// Copies all files from 'source_esp_name' folder to the UEFI fallback folder. +/// Replaces fallback from the selected slot, unless the unseeded-AZLA update case is skipped. +/// Slot-owned MSHV copies the complete nested bundle; ordinary mode copies top-level files. fn copy_boot_files_for_uefi_fallback( mount_point: &Path, esp_mount_path: &Path, @@ -737,6 +739,10 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { /// 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. +/// +/// Slot-owned MSHV requires complete BOOT and existing AZLA bundles. A missing AZLA +/// is copied after capacity preflight and published by directory rename; an existing +/// AZLA is validated but never refreshed from BOOT. pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> 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); @@ -752,13 +758,8 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> Result< "AZLA volume ESP path {:?} does not exist, attempting to copy from fallback location", azla_esp_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. + // Publish only a complete staged copy. An incomplete AZLA would be skipped + // in ordinary mode or rejected, rather than repaired, in slot-owned MSHV mode. 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!( @@ -767,6 +768,7 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> Result< ))?; } let copy_result = if slot_mshv { + // Reclaim stale staging contents above before checking space for a fresh copy. boot::mshv::preflight_bootstrap(&boot_esp_path, esp_path)?; boot::mshv::copy_bundle(&boot_esp_path, &azla_tmp_path) } else { @@ -1239,7 +1241,7 @@ mod tests { UefiFallbackMode::Conservative, Some(AbVolumeSelection::VolumeA), ServicingType::CleanInstall, - Some("AZLA".to_string()), // in finalize, with 'conservative', copy from volume A (volume we just put COSI files on) + Some("AZLA".to_string()), // before reboot, copy the clean-install target "Validate CleanInstallStaged + Conservative + active volume A ==> AZLA", ), ( @@ -1247,7 +1249,7 @@ mod tests { UefiFallbackMode::Optimistic, Some(AbVolumeSelection::VolumeA), ServicingType::CleanInstall, - Some("AZLA".to_string()), // in finalize, with 'optimistic', copy from volume A (volume we just put COSI files on) + Some("AZLA".to_string()), // before reboot, copy the clean-install target "Validate CleanInstallStaged + Optimistic + active volume A ==> AZLA", ), ( @@ -1255,7 +1257,7 @@ mod tests { UefiFallbackMode::Conservative, Some(AbVolumeSelection::VolumeA), ServicingType::AbUpdate, - Some("AZLA".to_string()), // in finalize, with 'conservative', copy from active volume (the COSI bits have not been validated yet) + Some("AZLA".to_string()), // before reboot, preserve the retained slot as fallback "Validate AbUpdateStaged + Conservative + active volume A ==> AZLA", ), ( @@ -1263,7 +1265,7 @@ mod tests { UefiFallbackMode::Optimistic, Some(AbVolumeSelection::VolumeA), ServicingType::AbUpdate, - Some("AZLB".to_string()), // in finalize, with 'optimistic', copy from inactive volume (that we just put COSI files on) + Some("AZLB".to_string()), // before reboot, copy the staged candidate "Validate AbUpdateStaged + Optimistic + active volume A ==> AZLB", ), ( @@ -1295,7 +1297,7 @@ mod tests { UefiFallbackMode::Optimistic, Some(AbVolumeSelection::VolumeA), ServicingType::AbUpdate, - None, // in commit, with 'optimistic', no copy is needed because it was done in finalize + None, // optimistic fallback already contains the candidate "Validate AbUpdateFinalized + Optimistic + active volume A ==> None", ), ( @@ -1390,6 +1392,7 @@ mod tests { ); } + /// Conservative commit copies the opposite, validated slot rather than the recorded active one. #[test] fn test_conservative_commit_copies_validated_slot() { let file_names = vec![PathBuf::from(BOOT_EFI), PathBuf::from(GRUB_EFI)]; @@ -1568,6 +1571,7 @@ mod tests { } } + /// Ordinary bootstrap seeds AZLA from the fallback's top-level boot files. #[test] fn test_bootstrap_azla_from_fallback() { let esp_dir = TempDir::new().unwrap(); @@ -1598,6 +1602,7 @@ mod tests { } } + /// Ordinary bootstrap leaves an existing AZLA untouched, even if it is incomplete. #[test] fn test_bootstrap_azla_from_fallback_is_idempotent_when_azla_already_exists() { let esp_dir = TempDir::new().unwrap(); @@ -1624,8 +1629,7 @@ mod tests { bootstrap_azla_from_fallback(esp_dir.path(), false).unwrap(); - // AZLA must be left untouched: bootstrap only runs when AZLA is - // absent, so a second call must be a no-op. + // With slot_mshv disabled, existing AZLA needs no completeness check or copy. let contents = fs::read_to_string(&sentinel_path).unwrap(); assert_eq!( contents.trim(), @@ -1638,6 +1642,7 @@ mod tests { ); } + /// An abandoned ordinary bootstrap must not contaminate the next staged copy. #[test] fn test_bootstrap_azla_from_fallback_cleans_up_stale_tmp_dir() { let esp_dir = TempDir::new().unwrap(); @@ -1684,6 +1689,7 @@ mod tests { } } + /// MSHV bootstrap copies nested files, preserves a complete AZLA, and rejects an incomplete one. #[test] fn test_bootstrap_azla_from_mshv_fallback() { let esp = TempDir::new().unwrap(); @@ -1729,6 +1735,7 @@ mod tests { assert!(!azla.join("Windows/System32/kdstub.dll").exists()); } + /// Stale staging is removed before preflight, while capacity failure leaves BOOT untouched. #[test] fn test_bootstrap_azla_cleans_stale_mshv_copy_before_capacity_check() { let esp = TempDir::new().unwrap(); @@ -1773,6 +1780,7 @@ mod tests { assert_eq!(fs::read(boot.join("HvLoader.efi")).unwrap(), b"retained"); } + /// Incomplete MSHV fallback must fail before publishing AZLA. #[test] fn test_bootstrap_azla_rejects_incomplete_mshv_fallback() { let esp = TempDir::new().unwrap(); From 7acc0edbda8550c73ad0541c84702bd33f7ce00b Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Thu, 12 Nov 2026 22:16:32 +0000 Subject: [PATCH 30/82] Tighten MSHV comments and match enum style Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3776b97-18ef-40d5-821f-dac82f77e3de --- crates/trident-client/src/preview.rs | 1 - crates/trident-client/src/protocol.rs | 2 +- crates/trident-client/src/tests.rs | 2 +- crates/trident/src/engine/boot/mshv.rs | 40 ++++---- crates/trident/src/engine/boot/uki.rs | 36 ++----- .../trident/src/engine/manual_rollback/mod.rs | 5 +- .../src/engine/manual_rollback/utils.rs | 7 +- crates/trident/src/engine/mshv.rs | 22 ++--- crates/trident/src/engine/rollback.rs | 32 +++---- crates/trident/src/engine/update.rs | 5 +- crates/trident/src/init/acl/mod.rs | 18 ++-- crates/trident/src/init/offline/mod.rs | 5 +- crates/trident/src/lib.rs | 20 ++-- crates/trident/src/subsystems/esp.rs | 94 ++++++------------- 14 files changed, 105 insertions(+), 184 deletions(-) diff --git a/crates/trident-client/src/preview.rs b/crates/trident-client/src/preview.rs index 668c3882f5..5bfd62d3e4 100644 --- a/crates/trident-client/src/preview.rs +++ b/crates/trident-client/src/preview.rs @@ -49,7 +49,6 @@ pub enum ServicingState { ManualRollbackAbFinalized, Provisioned, AbUpdateHealthCheckFailed, - /// The trial OS booted, but hypervisor validation failed and automatic recovery is pending. AbUpdateHypervisorCheckFailed, Unknown(i32), } diff --git a/crates/trident-client/src/protocol.rs b/crates/trident-client/src/protocol.rs index 14d825a58b..9c072f4cb0 100644 --- a/crates/trident-client/src/protocol.rs +++ b/crates/trident-client/src/protocol.rs @@ -286,7 +286,7 @@ fn decode_location(location: ProtoFileLocation) -> SourceLocation { } } -/// Decodes preview servicing states, including hypervisor recovery, preserving unknown wire values. +/// Decodes preview states, preserving unknown wire values. #[cfg(feature = "preview")] pub(crate) fn decode_servicing_state(state: i32) -> ServicingState { match ProtoServicingState::try_from(state) { diff --git a/crates/trident-client/src/tests.rs b/crates/trident-client/src/tests.rs index 89027543e6..b71cfda596 100644 --- a/crates/trident-client/src/tests.rs +++ b/crates/trident-client/src/tests.rs @@ -1485,7 +1485,7 @@ async fn preview_status_validation_and_rollback_use_domain_types() { assert_eq!(captured.validation_yaml.len(), 2); } -/// Preview decoding retains known recovery states and preserves unknown wire values. +/// Preview decoding preserves known, unspecified, and unknown states. #[cfg(feature = "preview")] #[tokio::test] async fn preview_status_enums_preserve_known_unspecified_and_unknown_values() { diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 47b4a7bd2e..8ae7a07017 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -38,8 +38,8 @@ pub(crate) fn has_slot_mshv_bundle(esp_path: &Path) -> Result { Ok(false) } -/// Checks the case-insensitive allowlist, rejecting symlinks and special files. -/// Does not require completeness; `temporary` also permits known `.new` and `.old` files. +/// Checks allowed entries without requiring completeness or following symlinks. +/// Matching ignores case; `temporary` also permits known `.new` and `.old` files. fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { ensure!( fs::symlink_metadata(directory)?.is_dir(), @@ -80,9 +80,8 @@ fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { Ok(()) } -/// Requires the complete supported payload and rejects unexpected entries. -/// Validates layout, not executable contents or the running hypervisor. -/// Required-path lookups rely on FAT's case-insensitive filename resolution. +/// Requires the complete allowlisted layout, relying on FAT's case-insensitive lookups. +/// Does not validate executable contents or hypervisor identity. pub(crate) fn validate_bundle(root: &Path) -> Result<()> { validate_tree(root, root, false)?; for name in FILES { @@ -129,8 +128,7 @@ fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<()> { Ok(()) } -/// Estimates staging space for the slot bundle, UKIs, addons, and an enabled fallback copy. -/// Credits inactive-slot contents and UKIs/addons scheduled for removal before staging. +/// Budgets bundles, UKIs, addons, and fallback, crediting planned pre-staging cleanup. pub(crate) fn preflight_staging( ctx: &EngineContext, source_esp: &Path, @@ -169,9 +167,8 @@ pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<()> { ) } -/// Copies a complete validated bundle into an allowlisted destination. -/// Overwrites matching files non-atomically; callers needing atomic publication -/// must stage in a temporary directory and rename it into place. +/// Copies a validated bundle non-atomically into an allowlisted destination. +/// For atomic publication, copy to a temporary directory and rename it. pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { validate_bundle(from)?; fs::create_dir_all(to)?; @@ -184,9 +181,8 @@ pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { Ok(()) } -/// Publishes the fallback bundle using per-file `.new` and `.old` names. -/// Restores missing live files from `.old`, discards stale backups, and stages -/// every `.new` file before renaming live files. Whole-bundle replacement is not atomic. +/// Reconciles `.old` backups and stages all `.new` files before replacing fallback. +/// Whole-bundle replacement is not atomic. pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<()> { validate_bundle(from)?; match fs::symlink_metadata(to) { @@ -246,7 +242,7 @@ mod tests { use std::os::unix::fs::symlink; use tempfile::TempDir; - /// Creates all allowlisted payload files with deterministic test contents. + /// Creates a complete test bundle. fn bundle(root: &Path, contents: &[u8]) { for name in FILES { let path = root.join(name); @@ -255,7 +251,7 @@ mod tests { } } - /// Copying the candidate bundle must not modify the retained slot. + /// Candidate copying preserves the retained slot. #[test] fn copies_complete_bundle_without_touching_other_slots() { let temp = TempDir::new().unwrap(); @@ -271,7 +267,7 @@ mod tests { } } - /// Allowlist matching ignores case, but temporary names require explicit permission. + /// Allowlist matching ignores case; temporary names require opt-in. #[test] fn accepts_fat_filename_casing_but_rejects_unknown_entries() { let temp = TempDir::new().unwrap(); @@ -290,7 +286,7 @@ mod tests { assert!(validate_tree(temp.path(), temp.path(), true).is_err()); } - /// Invalid sources must fail before creating the destination. + /// Invalid sources fail before destination creation. #[test] fn rejects_incomplete_and_unexpected_payload_before_copy() { let temp = TempDir::new().unwrap(); @@ -306,7 +302,7 @@ mod tests { assert!(!target.exists()); } - /// Payload validation must not follow symlinks into an unrelated directory. + /// Validation rejects source and destination symlinks. #[test] fn rejects_source_and_destination_symlinks() { let temp = TempDir::new().unwrap(); @@ -324,7 +320,7 @@ mod tests { assert!(fs::read_dir(&outside).unwrap().next().is_none()); } - /// Retrying interrupted fallback publication replaces stale files and removes backups. + /// Retrying publication replaces stale files and removes backups. #[test] fn retries_partial_publication_and_removes_only_known_temporary_files() { let temp = TempDir::new().unwrap(); @@ -350,7 +346,7 @@ mod tests { assert!(replace_bundle(&source, &source).is_err()); } - /// Capacity checks include cluster rounding, reclaimable space, and the reserve. + /// Capacity includes cluster rounding, reclamation, and a reserve. #[test] fn capacity_accounts_for_clusters_and_preserves_a_reserve() { let temp = TempDir::new().unwrap(); @@ -360,7 +356,7 @@ mod tests { assert!(check_space(SPACE_RESERVE, 4096, 4096).is_ok()); } - /// An oversized staged UKI must fail preflight without changing either slot's payload. + /// Failed preflight leaves both slots untouched. #[test] fn preflight_rejects_peak_allocation_before_mutating_inactive_or_retained_files() { let temp = TempDir::new().unwrap(); @@ -389,7 +385,7 @@ mod tests { } } - /// Fallback policy selects a complete bundle without overwriting the retained slot. + /// Each fallback policy copies whole bundles and preserves the retained slot. #[test] fn fallback_modes_use_the_full_selected_bundle_during_trial_commit_and_rollback() { use trident_api::{ diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index a755622a66..4663c8b7dd 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -220,21 +220,9 @@ fn remove_uki_and_addons(path: &Path) -> Result<(), Error> { Ok(()) } -/// 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 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. -/// -/// Removes: -/// 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, and only for OS index 0, which owns it. -/// Associated addon directories are removed with each selected UKI. +/// Frees ESP space by removing target-slot/OS-index UKIs and their addon directories. +/// Also removes original UKIs for OS index 0 once Trident manages its active slot. +/// Other slots and OS indices are preserved. pub fn cleanup_ukis_before_staging( ctx: &EngineContext, mount_point: &Path, @@ -248,8 +236,7 @@ pub fn cleanup_ukis_before_staging( Ok(()) } -/// Lists the UKIs selected by pre-staging cleanup without modifying the ESP. -/// Capacity preflight uses the same selection to credit UKIs and their addon directories. +/// Lists cleanup candidates without mutation, also used to budget reclaimable space. pub(crate) fn find_ukis_to_remove_before_staging( ctx: &EngineContext, esp_uki_directory: &Path, @@ -265,24 +252,15 @@ pub(crate) fn find_ukis_to_remove_before_staging( let active_suffix = format!("{active_slot}.efi"); let trident_ukis = enumerate_trident_managed_ukis(esp_uki_directory)?; - // 1. Select trident-managed UKIs for the target slot+os-index - // (all update indices, e.g. vmlinuz-100-azla0.efi, vmlinuz-102-azla0.efi). + // Select all update indices for the target slot and OS index. for (_index, suffix, path) in &trident_ukis { if *suffix == target_suffix { removals.push(path.clone()); } } - // 2. 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 (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. + // Only OS 0 owns the original UKI. Its managed active slot is sufficient + // rollback; requiring both slots would leave too little ESP space to stage. let has_active_slot_uki = trident_ukis .iter() .any(|(_index, suffix, _)| *suffix == active_suffix); diff --git a/crates/trident/src/engine/manual_rollback/mod.rs b/crates/trident/src/engine/manual_rollback/mod.rs index 1755e0199d..da45775577 100644 --- a/crates/trident/src/engine/manual_rollback/mod.rs +++ b/crates/trident/src/engine/manual_rollback/mod.rs @@ -92,7 +92,7 @@ pub fn check_rollback( /// `ExitKind::Done` that's indistinguishable from a real rollback at the /// gRPC layer (see `ServicingResponse.servicing_kind` in servicing.proto). /// -/// Rejects rollback targets that change the installation's slot-owned MSHV mode before staging. +/// Rejects MSHV mode changes before staging a rollback target. pub fn execute_rollback( datastore: &mut DataStore, requested_rollback_kind: ManualRollbackRequestKind, @@ -151,8 +151,7 @@ pub fn execute_rollback( }; staged_rollback_type = Some(rollback_type); - // Historical rollback targets must preserve the installation's slot-owned - // MSHV mode, just like update requests; reject mode changes before staging. + // Historical targets must preserve the installation's MSHV mode. engine::mshv::validate_transition(&datastore.host_status().spec, &requested_rollback.spec)?; let engine_context = EngineContext::new(EngineContextParams { diff --git a/crates/trident/src/engine/manual_rollback/utils.rs b/crates/trident/src/engine/manual_rollback/utils.rs index 99e6ed8474..a08e8e3492 100644 --- a/crates/trident/src/engine/manual_rollback/utils.rs +++ b/crates/trident/src/engine/manual_rollback/utils.rs @@ -247,8 +247,7 @@ impl ManualRollbackContext { /// * an operation that cannot be rolled back is found /// * a HostStatus entry is None /// - /// Automatic rollback after health or hypervisor validation failure ends parsing, - /// so the rejected candidate is not offered as a manual rollback target. + /// Health/hypervisor automatic rollback ends parsing, excluding the rejected candidate. /// /// Once the Operations have been parsed, the ManualRollback operations (both /// A/B and runtime) and the operations that they undo (both A/B and runtime @@ -355,7 +354,7 @@ impl ManualRollbackContext { } ServicingState::AbUpdateHealthCheckFailed | ServicingState::AbUpdateHypervisorCheckFailed => { - // Automatic recovery ends rollback history at the failed candidate. + // Do not offer the rejected candidate as a rollback target. current_operation.kind = OperationKind::AbUpdateAutoRollback; trace!("Detected AbUpdateAutoRollback operation, ending parsing here."); break; @@ -1029,7 +1028,7 @@ mod tests { rollback_context_testing(&host_status_list, "Validate A/B update health check failed"); } - /// Hypervisor-triggered recovery must bound manual rollback history like health failure. + /// Hypervisor recovery bounds history like health-check recovery. #[test] fn test_ab_update_hypervisor_check_failed() { let host_status_list = vec![ diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index 6f102a4ebb..535533bf0d 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -9,7 +9,7 @@ use trident_api::{ use super::{boot, EngineContext}; -/// Builds an input error attributed to the slot-owned MSHV mode parameter. +/// Attributes unsupported configurations to the MSHV mode parameter. fn unsupported(reason: &str) -> TridentError { TridentError::new(InvalidInputError::InvalidInternalParameter { name: MSHV_SLOT_ESP_PAYLOAD.into(), @@ -17,12 +17,12 @@ fn unsupported(reason: &str) -> TridentError { }) } -/// Returns whether the configuration opts into slot-owned MSHV payloads. +/// Checks the slot-owned MSHV opt-in. pub(crate) fn enabled(spec: &HostConfiguration) -> bool { spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD) } -/// Rejects enabling or disabling slot-owned MSHV on an established installation. +/// Rejects MSHV mode changes on an existing installation. pub(crate) fn validate_transition( previous: &HostConfiguration, requested: &HostConfiguration, @@ -35,14 +35,12 @@ pub(crate) fn validate_transition( Ok(()) } -/// Checks image, deployment, encryption, and mode-transition restrictions when MSHV is enabled. -/// Configurations without slot-owned MSHV are left to ordinary validation. +/// Enforces support and mode-transition restrictions when slot-owned MSHV is enabled. pub(crate) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { if !enabled(&ctx.spec) { return Ok(()); } - // x86-64 is an initial support choice while the MSHV payload definition is x64-only. - // Other architectures should reuse the existing architecture-aware EFI filename helpers. + // The current payload allowlist supports only x86-64. if !cfg!(target_arch = "x86_64") || !ctx.image_distro().is_acl() || !ctx.is_uki()? { return Err(unsupported( "Slot-owned MSHV requires an x86-64 ACL UKI image", @@ -75,9 +73,8 @@ pub(crate) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE Ok(()) } -/// Hypervisor identity-validation hook for the expected installation and slot. -/// Currently always succeeds; enabled configurations only log the expected slot. -/// It does not inspect the running hypervisor or validate payload contents. +/// Success stub: logs the expected slot only when MSHV is enabled. +/// Does not inspect hypervisor identity. pub(crate) fn validate_active_hypervisor( spec: &HostConfiguration, install_index: usize, @@ -87,7 +84,6 @@ pub(crate) fn validate_active_hypervisor( let expected_directory = expected_volume.map(|volume| boot::make_esp_dir_name(install_index, volume)); // TODO: Identify the running hypervisor and compare it with the expected OS payload. - // Deliberately assume success until the identity mechanism is implemented. warn!( "MSHV hypervisor identity validation is not implemented; assuming success for {:?}", expected_directory @@ -100,7 +96,7 @@ pub(crate) fn validate_active_hypervisor( mod tests { use super::*; - /// Established installations may retain their mode, but may not switch modes. + /// Matching modes pass; transitions fail in either direction. #[test] fn rejects_mode_changes_but_allows_matching_installation_modes() { let ordinary = HostConfiguration::default(); @@ -112,7 +108,7 @@ mod tests { assert!(validate_transition(&mshv, &mshv).is_ok()); } - /// MSHV restrictions apply only after opt-in and reject unsupported deployment combinations. + /// Unsupported MSHV combinations fail only after opt-in. #[test] fn rejects_unsupported_mshv_images_without_affecting_other_images() { let mut ctx = EngineContext { diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index fde2d182c9..c8ffb2a6e6 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -38,10 +38,9 @@ pub enum BootValidationResult { InvalidHypervisor(TridentError), } -/// Validates the expected boot device and invokes the MSHV identity hook (currently a success stub). -/// Commits finalized servicing on success, or reconciles status after firmware/automatic rollback. -/// Trial A/B validation failures can request recovery; recovery failures return an error -/// without requesting another rollback. Errors may leave Host Status unchanged. +/// Validates the boot device and calls the MSHV identity hook (currently a success stub). +/// Commits a valid target or reconciles rollback status. Trial A/B validation failures +/// can request recovery; recovery failures return errors without another rollback. #[tracing::instrument(skip_all)] pub fn validate_boot(datastore: &mut DataStore) -> Result { info!("Validating whether host correctly booted from target OS image"); @@ -52,8 +51,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result datastore.host_status().ab_active_volume, - // After health or hypervisor validation fails, invert the recorded volume - // so the context's update target resolves to the retained servicing OS. + // Invert the context volume so recovery targets the retained servicing OS. ServicingState::AbUpdateHealthCheckFailed | ServicingState::AbUpdateHypervisorCheckFailed => { match datastore.host_status().ab_active_volume { @@ -79,16 +77,14 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result ServicingType::NoActiveServicing, }; - // Commit and recovery must preserve the installation's slot-owned MSHV mode. - // CleanInstallFinalized has no previous installed mode, so there is no transition to validate. + // Preserve MSHV mode except on clean install, which has no previous mode. if current_servicing_state != ServicingState::CleanInstallFinalized { super::mshv::validate_transition( &datastore.host_status().spec_old, &datastore.host_status().spec, )?; } - // After candidate validation fails, recovery must validate the retained OS - // using spec_old rather than the failed candidate's configuration. + // Recovery validates the retained OS, not the failed candidate. let recovering = matches!( current_servicing_state, ServicingState::AbUpdateHealthCheckFailed | ServicingState::AbUpdateHypervisorCheckFailed @@ -125,8 +121,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Result Result { - // Recovery after health or hypervisor validation failed to boot the - // servicing OS. Report the failure without changing Host Status. + // Failed recovery leaves 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(), @@ -268,8 +261,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result ExpectedPartition<'a> { /// the expectations of the ACL image layout, and returns a HostStatus /// representing the current state of the host. This will be used to /// initialize the Trident datastore if it has not been created yet. -/// Discovers slot-owned MSHV from the host ESP without modifying its contents. +/// Also discovers MSHV mode without modifying the ESP. pub fn initial_host_status() -> Result { let blk_devices = lsblk::list().context("Failed to run lsblk")?; let root_blk_device = blk_devices @@ -89,7 +89,7 @@ pub fn initial_host_status() -> Result { /// initial ACL HostStatus, separated from the code that gets the /// Host's current disk information. This allows for easier testing /// of the HostStatus creation logic. -/// A complete MSHV BOOT bundle enables slot-owned mode; incomplete marked bundles fail. +/// Complete MSHV bundles enable slot-owned mode; incomplete marked bundles fail. fn inner_initial_host_status( disk_information: &SfDisk, root_blk_device: &BlockDevice, @@ -306,7 +306,7 @@ fn inner_initial_host_status( partition_paths, ..Default::default() }; - // Record the discovered mode only; the update path bootstraps AZLA before persisting it. + // Adoption bootstraps AZLA before persisting this discovered mode. if mshv::has_slot_mshv_bundle(esp_path)? { host_status .spec @@ -482,7 +482,7 @@ mod tests { } } - /// Creates a complete BOOT bundle for read-only ACL discovery tests. + /// Creates a complete BOOT bundle for discovery tests. fn create_mshv_bundle(esp_path: &Path) { for name in [ "bootx64.efi", @@ -500,7 +500,7 @@ mod tests { } } - /// Only a complete BOOT bundle enables MSHV; discovery must not create AZLA. + /// Only complete BOOT bundles enable MSHV; discovery leaves AZLA untouched. #[test] fn initial_host_status_discovers_slot_mshv_from_image() { let esp = tempfile::TempDir::new().unwrap(); @@ -525,7 +525,7 @@ mod tests { assert!(!esp.path().join("EFI/AZLA").exists()); } - /// A marked but incomplete BOOT bundle must fail adoption without creating AZLA. + /// Incomplete marked bundles fail discovery without creating AZLA. #[test] fn initial_host_status_rejects_incomplete_slot_mshv_payload() { let esp = tempfile::TempDir::new().unwrap(); @@ -554,7 +554,7 @@ mod tests { } } - /// Ordinary ACL partition discovery remains valid without MSHV ESP contents. + /// Ordinary ACL discovery needs no MSHV payload. #[test] fn test_inner_initial_host_status_success() { let sfdisk = create_sfdisk("efi-system", TestPartitions::Correct); @@ -692,7 +692,7 @@ mod tests { assert!(volume_pairs.iter().all(|p| p.id != "usr-hash-sig")); } - /// An unexpected ESP partition label must still fail with an empty test ESP. + /// Unexpected ESP labels fail before payload discovery. #[test] fn test_inner_initial_host_status_unexpected_part_name() { let wrong_label = "wrong-label"; @@ -747,7 +747,7 @@ mod tests { .contains("Unexpected partition label 'extra-one' found on root disk")); } - /// Duplicate partition labels must not produce an ambiguous HostStatus. + /// Duplicate labels cannot produce an ambiguous HostStatus. #[test] fn test_inner_initial_host_status_duplicate_part() { let sfdisk = create_sfdisk("efi-system", TestPartitions::Duplicate); diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index 548dd83951..7863eb5fc5 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -457,7 +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. -/// Explicit slot-owned MSHV mode is rejected; this path does not discover MSHV bundles. +/// Rejects explicit MSHV mode; does not discover MSHV payloads. pub fn execute( hs_path: Option<&Path>, lazy_partitions: &[String], @@ -511,8 +511,7 @@ pub fn execute( generate_host_status(&history, lsblk_output, lazy_partitions, disk)? }; - // Reject explicit slot-owned mode before writing the datastore or bootstrapping AZLA. - // Unflagged MSHV payloads are not detected by this path. + // Reject explicit MSHV mode before persistence/bootstrap; unflagged payloads go undetected. crate::engine::mshv::validate_transition(&Default::default(), &host_status.spec)?; debug!( diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index 483c91670b..e3f8ddcbc6 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -290,8 +290,7 @@ impl Trident { Ok(()) } - /// Runs an operation and records errors, preserving the original validation - /// failure if recovery after an A/B health or hypervisor failure returns an error. + /// Records operation errors, preserving the original A/B validation error if recovery fails. fn execute_and_record_error( &mut self, datastore: &mut DataStore, @@ -300,8 +299,7 @@ impl Trident { where F: FnOnce(&mut DataStore) -> Result, { - // Preserve the original health/hypervisor failure if recovery returns an error, - // rather than replacing it with a secondary recovery error. + // A recovery error must not replace the original health/hypervisor failure. debug!( "Execute and record error with servicing state: {:?} and last error: {:?}", datastore.host_status().servicing_state, @@ -608,8 +606,7 @@ impl Trident { }) } - /// Adopts an untracked ACL host when needed, then stages/finalizes the requested update. - /// Adoption requires matching MSHV modes and a bootstrapped AZLA before persisting status. + /// Adopts untracked ACL hosts as needed, then stages/finalizes the update. pub fn update( &mut self, datastore: &mut DataStore, @@ -639,7 +636,7 @@ impl Trident { .structured(InvalidInputError::DeriveHostConfiguration) .message("Failed to initialize host status for ACL")?; - // The requested mode must match the discovered BOOT payload before adoption. + // Adoption requires matching requested and discovered MSHV modes. engine::mshv::validate_transition(&initial_host_status.spec, &host_config)?; // Mirror offline-initialize's bootstrap: ACL lazy adoption derives @@ -664,7 +661,7 @@ impl Trident { let esp_path = container::get_host_relative_path(esp_path.to_path_buf()) .message("Failed to resolve ESP path relative to host for ACL")?; - // Copy the complete nested bundle for MSHV, not just ordinary boot files. + // MSHV adoption copies the full nested bundle. let slot_mshv = engine::mshv::enabled(&initial_host_status.spec); esp::bootstrap_azla_from_fallback(&esp_path, slot_mshv) .structured(InvalidInputError::InvalidBootConfiguration) @@ -815,13 +812,12 @@ impl Trident { self.install(datastore, Operations::all(), false, Some(image)) } - /// Validates finalized servicing or automatic recovery and reports its reboot disposition. - /// Only a fully provisioned result is reported to the orchestrator as success. + /// Validates finalized servicing/recovery and returns whether a reboot is needed. pub fn commit( &mut self, datastore: &mut DataStore, ) -> Result<(ExitKind, ServicingType), TridentError> { - // Re-evaluate finalized boots and recovery after health or hypervisor validation failure. + // Validate finalized boots and health/hypervisor recovery. let servicing_state = datastore.host_status().servicing_state; if !matches!( servicing_state, @@ -853,7 +849,7 @@ impl Trident { ) }); - // A validation result requesting rollback is not an orchestrator success. + // Report success only after provisioning, not when rollback is required. if matches!( rollback_result, Ok(rollback::BootValidationResult::ValidBootProvisioned) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 09edb46c2d..3b32618d7c 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -56,10 +56,10 @@ impl Subsystem for EspSubsystem { crate::engine::mshv::validate_configuration(ctx) } - /// Revalidates MSHV restrictions and deploys boot artifacts for file-based servicing. + /// Revalidates MSHV restrictions before file-based ESP deployment. #[tracing::instrument(name = "esp_provision", skip_all)] fn provision(&mut self, ctx: &EngineContext, mount_path: &Path) -> Result<(), TridentError> { - // Recheck MSHV constraints here rather than relying solely on prior validation. + // Recheck constraints even if prior validation was skipped. crate::engine::mshv::validate_configuration(ctx)?; // Perform file-based deployment of ESP images, if needed, after filesystems have been // mounted and initialized. @@ -72,14 +72,9 @@ 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. -/// -/// Before reboot, staged-state handling copies volume A for clean install, the candidate -/// for optimistic A/B update, or the retained slot for conservative A/B update. -/// Manual A/B rollback copies its target for either enabled fallback mode. -/// At A/B commit, conservative mode copies the validated update target; optimistic mode -/// needs no further copy. Disabled mode does not copy. Slot-owned MSHV copies the full bundle. +/// Copies the selected slot to fallback; MSHV copies its complete nested bundle. +/// Conservative A/B fallback follows the retained slot until commit; optimistic +/// fallback follows the candidate before reboot. Disabled fallback is unchanged. pub fn set_uefi_fallback_contents( ctx: &EngineContext, servicing_state: ServicingState, @@ -323,9 +318,8 @@ where Ok((temp_image, computed_hash)) } -/// Performs file-based update of stand-alone ESP volume by copying boot files. -/// Slot-owned MSHV validates the bundle and preflights capacity before reclaiming the -/// target slot's payload/UKIs; the retained slot's payload is left untouched. +/// Deploys boot files, preflighting MSHV capacity before reclaiming target-slot files. +/// Retained-slot payloads are preserved. fn copy_file_artifacts( temp_image_path: &Path, ctx: &EngineContext, @@ -359,11 +353,11 @@ 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()); - // MSHV uses a complete allowlisted bundle rather than the ordinary boot-file list. + // MSHV uses a complete bundle, not the ordinary boot-file list. let slot_mshv = crate::engine::mshv::enabled(&ctx.spec); let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); let boot_files = if slot_mshv { - // Validate and budget peak allocation before deleting target-slot files or UKIs. + // Validate and budget space before deleting target-slot files. boot::mshv::validate_bundle(&source_bundle)?; boot::mshv::preflight_staging( ctx, @@ -374,7 +368,7 @@ fn copy_file_artifacts( uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; Vec::new() } else { - // Refuse to deploy an MSHV bundle through the ordinary, partial boot-file path. + // Ordinary copying would omit required MSHV payload files. ensure!( !source_bundle.join("HvLoader.efi").try_exists()?, "A slot-owned MSHV image requires internalParams.mshvSlotEspPayload" @@ -418,12 +412,8 @@ fn copy_file_artifacts( // Prepare ESP directory structure for UKI boot uki::prepare_esp_for_uki(mount_point, &ctx.esp_mount_path)?; - // MSHV already reclaimed old UKIs after preflight; other UKI images clean up here. - // 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. + // MSHV cleaned up after preflight; other UKI images reclaim space here. + // A crash before staging may lose the target UKI, but preserves the active slot. if !slot_mshv { uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; } @@ -483,23 +473,9 @@ fn copy_file_artifacts( 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. -/// -/// 1. Before reboot, when handling a staged servicing state: -/// * 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 retained 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: -/// * 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 validated update target, opposite the still-recorded active volume -/// -/// Disabled fallback and states not listed above select no source. +/// Before reboot, selects A for clean install or the manual A/B rollback target. +/// Optimistic A/B updates select the candidate before reboot; conservative mode selects +/// the retained slot before reboot and the validated target at commit. Other cases return None. fn find_uefi_fallback_source_dir_name( ctx: &EngineContext, servicing_state: ServicingState, @@ -535,8 +511,7 @@ fn find_uefi_fallback_source_dir_name( }, ServicingState::AbUpdateFinalized => match ctx.spec.os.uefi_fallback { UefiFallbackMode::Conservative => { - // Commit still records the pre-update active slot. Refresh fallback - // from the newly validated update target, after health checks pass. + // 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)) } @@ -585,8 +560,8 @@ fn skip_uefi_fallback_copy( false } -/// Replaces fallback from the selected slot, unless the unseeded-AZLA update case is skipped. -/// Slot-owned MSHV copies the complete nested bundle; ordinary mode copies top-level files. +/// Replaces fallback with nested MSHV or top-level ordinary 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, @@ -734,15 +709,9 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { 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. -/// -/// Slot-owned MSHV requires complete BOOT and existing AZLA bundles. A missing AZLA -/// is copied after capacity preflight and published by directory rename; an existing -/// AZLA is validated but never refreshed from BOOT. +/// Seeds missing `EFI/AZLA` from `EFI/BOOT` via a staged directory rename. +/// MSHV validates both bundles when present and preflights space before copying. +/// Existing AZLA contents are never refreshed. pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> 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); @@ -758,8 +727,7 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> Result< "AZLA volume ESP path {:?} does not exist, attempting to copy from fallback location", azla_esp_path ); - // Publish only a complete staged copy. An incomplete AZLA would be skipped - // in ordinary mode or rejected, rather than repaired, in slot-owned MSHV mode. + // An incomplete published AZLA would be skipped or rejected on retry. 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!( @@ -768,7 +736,7 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> Result< ))?; } let copy_result = if slot_mshv { - // Reclaim stale staging contents above before checking space for a fresh copy. + // Check capacity after reclaiming stale staging contents. boot::mshv::preflight_bootstrap(&boot_esp_path, esp_path)?; boot::mshv::copy_bundle(&boot_esp_path, &azla_tmp_path) } else { @@ -1392,7 +1360,7 @@ mod tests { ); } - /// Conservative commit copies the opposite, validated slot rather than the recorded active one. + /// 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)]; @@ -1571,7 +1539,7 @@ mod tests { } } - /// Ordinary bootstrap seeds AZLA from the fallback's top-level boot files. + /// Ordinary bootstrap copies top-level boot files. #[test] fn test_bootstrap_azla_from_fallback() { let esp_dir = TempDir::new().unwrap(); @@ -1602,7 +1570,7 @@ mod tests { } } - /// Ordinary bootstrap leaves an existing AZLA untouched, even if it is incomplete. + /// 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(); @@ -1629,7 +1597,7 @@ mod tests { bootstrap_azla_from_fallback(esp_dir.path(), false).unwrap(); - // With slot_mshv disabled, existing AZLA needs no completeness check or copy. + // Ordinary mode neither validates nor refreshes existing AZLA. let contents = fs::read_to_string(&sentinel_path).unwrap(); assert_eq!( contents.trim(), @@ -1642,7 +1610,7 @@ mod tests { ); } - /// An abandoned ordinary bootstrap must not contaminate the next staged copy. + /// 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(); @@ -1689,7 +1657,7 @@ mod tests { } } - /// MSHV bootstrap copies nested files, preserves a complete AZLA, and rejects an incomplete one. + /// MSHV copies nested files and validates, but never refreshes, existing AZLA. #[test] fn test_bootstrap_azla_from_mshv_fallback() { let esp = TempDir::new().unwrap(); @@ -1735,7 +1703,7 @@ mod tests { assert!(!azla.join("Windows/System32/kdstub.dll").exists()); } - /// Stale staging is removed before preflight, while capacity failure leaves BOOT untouched. + /// Failed preflight follows stale-copy cleanup and leaves BOOT untouched. #[test] fn test_bootstrap_azla_cleans_stale_mshv_copy_before_capacity_check() { let esp = TempDir::new().unwrap(); @@ -1780,7 +1748,7 @@ mod tests { assert_eq!(fs::read(boot.join("HvLoader.efi")).unwrap(), b"retained"); } - /// Incomplete MSHV fallback must fail before publishing AZLA. + /// Incomplete MSHV fallback cannot publish AZLA. #[test] fn test_bootstrap_azla_rejects_incomplete_mshv_fallback() { let esp = TempDir::new().unwrap(); From 53e47d23d40fcf026c2e50ebd3f23336736d7053 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Thu, 12 Nov 2026 23:03:18 +0000 Subject: [PATCH 31/82] docs: clarify UEFI fallback selection matrix Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3776b97-18ef-40d5-821f-dac82f77e3de --- crates/trident/src/subsystems/esp.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 3b32618d7c..be7138a5ed 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -473,9 +473,17 @@ fn copy_file_artifacts( Ok(()) } -/// Before reboot, selects A for clean install or the manual A/B rollback target. -/// Optimistic A/B updates select the candidate before reboot; conservative mode selects -/// the retained slot before reboot and the validated target at commit. Other cases return None. +/// Selects the slot to copy into `EFI/BOOT`; `None` leaves fallback unchanged. +/// +/// | Servicing state | Optimistic | Conservative | +/// | --- | --- | --- | +/// | CleanInstallStaged | A | A | +/// | AbUpdateStaged | Candidate | Retained | +/// | AbUpdateFinalized | None | Validated target | +/// | ManualRollbackAbStaged | Rollback target | Rollback target | +/// +/// Disabled fallback and unlisted states return `None`. +/// A missing active slot defaults to A in the two A/B staging cases. fn find_uefi_fallback_source_dir_name( ctx: &EngineContext, servicing_state: ServicingState, From aa8a51d4a5df343b1e7390c304a99dbd24eb0a2d Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Thu, 12 Nov 2026 23:08:19 +0000 Subject: [PATCH 32/82] docs: restore UEFI fallback lifecycle explanation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3776b97-18ef-40d5-821f-dac82f77e3de --- crates/trident/src/subsystems/esp.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index be7138a5ed..856d703be5 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -72,9 +72,19 @@ impl Subsystem for EspSubsystem { } } -/// Copies the selected slot to fallback; MSHV copies its complete nested bundle. -/// Conservative A/B fallback follows the retained slot until commit; optimistic -/// fallback follows the candidate before reboot. Disabled fallback is unchanged. +/// Configures UEFI fallback by copying boot files to the UEFI fallback folder +/// based on the UEFI fallback mode and servicing state. +/// +/// UEFI fallback is handled in two stages: +/// 1. During finalize: +/// * Clean install copies the target OS boot files (always volume A). +/// * A/B update copies the candidate in optimistic mode or the retained slot +/// in conservative mode. +/// * 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 the complete nested bundle. pub fn set_uefi_fallback_contents( ctx: &EngineContext, servicing_state: ServicingState, From e43d4327e3d18d45e7def6bfdc49187e29d41cfb Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Thu, 12 Nov 2026 23:42:51 +0000 Subject: [PATCH 33/82] Move MSHV validation into ESP and use architecture helper Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3776b97-18ef-40d5-821f-dac82f77e3de --- crates/sysdefs/src/arch.rs | 5 ++ crates/trident/src/engine/mshv.rs | 82 ++------------------- crates/trident/src/subsystems/esp.rs | 4 +- crates/trident/src/subsystems/esp/mshv.rs | 88 ++++++++++++++++++++++- 4 files changed, 98 insertions(+), 81 deletions(-) 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/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index 535533bf0d..8cdd78a0a4 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -2,15 +2,15 @@ use log::warn; use trident_api::{ config::HostConfiguration, - constants::internal_params::{MSHV_SLOT_ESP_PAYLOAD, PRESERVE_MSHV_ESP_PAYLOAD}, + constants::internal_params::MSHV_SLOT_ESP_PAYLOAD, error::{InvalidInputError, TridentError}, - status::{AbVolumeSelection, ServicingType}, + status::AbVolumeSelection, }; -use super::{boot, EngineContext}; +use super::boot; /// Attributes unsupported configurations to the MSHV mode parameter. -fn unsupported(reason: &str) -> TridentError { +pub(crate) fn unsupported(reason: &str) -> TridentError { TridentError::new(InvalidInputError::InvalidInternalParameter { name: MSHV_SLOT_ESP_PAYLOAD.into(), explanation: reason.into(), @@ -35,44 +35,6 @@ pub(crate) fn validate_transition( Ok(()) } -/// Enforces support and mode-transition restrictions when slot-owned MSHV is enabled. -pub(crate) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { - if !enabled(&ctx.spec) { - return Ok(()); - } - // The current payload allowlist supports only x86-64. - if !cfg!(target_arch = "x86_64") || !ctx.image_distro().is_acl() || !ctx.is_uki()? { - return Err(unsupported( - "Slot-owned MSHV requires an x86-64 ACL UKI image", - )); - } - if ctx.is_stream_image { - return Err(unsupported( - "Slot-owned MSHV requires file-based ESP deployment", - )); - } - if ctx.spec.internal_params.get_flag(PRESERVE_MSHV_ESP_PAYLOAD) { - return Err(unsupported( - "Shared-path and slot-owned MSHV modes cannot be combined", - )); - } - if ctx - .spec - .storage - .encryption - .as_ref() - .is_some_and(|encryption| !encryption.pcrs.is_empty()) - { - return Err(unsupported( - "Slot-owned MSHV TPM/PCR-bound encryption is not validated", - )); - } - if ctx.servicing_type != ServicingType::CleanInstall { - validate_transition(&ctx.spec_old, &ctx.spec)?; - } - Ok(()) -} - /// Success stub: logs the expected slot only when MSHV is enabled. /// Does not inspect hypervisor identity. pub(crate) fn validate_active_hypervisor( @@ -107,40 +69,4 @@ mod tests { assert!(validate_transition(&ordinary, &ordinary).is_ok()); assert!(validate_transition(&mshv, &mshv).is_ok()); } - - /// Unsupported MSHV combinations fail only after opt-in. - #[test] - fn rejects_unsupported_mshv_images_without_affecting_other_images() { - let mut ctx = EngineContext { - is_stream_image: true, - is_uki: Some(true), - servicing_type: ServicingType::CleanInstall, - ..Default::default() - } - .with_image(crate::osimage::mock::MockOsImage { - os_release: osutils::osrelease::OsRelease { - id: Some(osutils::osrelease::AZURE_LINUX_DISTRO_ID.into()), - variant_id: Some(osutils::osrelease::AZURE_CONTAINER_LINUX_VARIANT_ID.into()), - ..Default::default() - }, - is_uki: true, - ..crate::osimage::mock::MockOsImage::new() - }); - assert!(validate_configuration(&ctx).is_ok()); - ctx.spec.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); - assert!(validate_configuration(&ctx).is_err()); - ctx.is_stream_image = false; - assert_eq!( - validate_configuration(&ctx).is_ok(), - cfg!(target_arch = "x86_64"), - ); - ctx.spec.storage.encryption = Some(trident_api::config::Encryption { - pcrs: vec![sysdefs::tpm2::Pcr::Pcr4], - ..Default::default() - }); - assert!(validate_configuration(&ctx).is_err()); - ctx.spec.storage.encryption = None; - ctx.spec.internal_params.set_flag(PRESERVE_MSHV_ESP_PAYLOAD); - assert!(validate_configuration(&ctx).is_err()); - } } diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 856d703be5..75a2268d1b 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -53,14 +53,14 @@ impl Subsystem for EspSubsystem { /// Applies slot-owned MSHV support restrictions before ESP servicing. fn validate_host_config(&self, ctx: &EngineContext) -> Result<(), TridentError> { - crate::engine::mshv::validate_configuration(ctx) + mshv::validate_configuration(ctx) } /// Revalidates MSHV restrictions before file-based ESP deployment. #[tracing::instrument(name = "esp_provision", skip_all)] fn provision(&mut self, ctx: &EngineContext, mount_path: &Path) -> Result<(), TridentError> { // Recheck constraints even if prior validation was skipped. - crate::engine::mshv::validate_configuration(ctx)?; + mshv::validate_configuration(ctx)?; // Perform file-based deployment of ESP images, if needed, after filesystems have been // mounted and initialized. diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index c422405c2b..768cf4cb69 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -1,4 +1,4 @@ -//! ACL, efitreeloader (ETL), and MSHV-related functionality for ESP provisioning. +//! ACL, efitreeloader (ETL), and MSHV support for ESP validation and provisioning. use std::{ fs, @@ -8,6 +8,17 @@ use std::{ use anyhow::{ensure, Context, Error}; use log::{debug, warn}; +use sysdefs::arch::SystemArchitecture; +use trident_api::{ + constants::internal_params::PRESERVE_MSHV_ESP_PAYLOAD, error::TridentError, + status::ServicingType, +}; + +use crate::engine::{ + mshv::{enabled, unsupported, validate_transition}, + EngineContext, +}; + /// Filename of the second-stage EFI executable for efitreeloader (ETL). pub(super) const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; @@ -19,6 +30,44 @@ const MSHV_ESP_PAYLOAD_BINARIES: [&str; 2] = ["efi/HvLoader.efi", "efi/lxhvloade /// maintaining a fixed binary list. Subdirectories are ignored. const MSHV_ESP_PAYLOAD_DIR: &str = "efi/Windows/System32"; +/// Enforces support and mode-transition restrictions when slot-owned MSHV is enabled. +pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { + if !enabled(&ctx.spec) { + return Ok(()); + } + // The current payload allowlist supports only x86-64. + if !SystemArchitecture::current().is_x64() || !ctx.image_distro().is_acl() || !ctx.is_uki()? { + return Err(unsupported( + "Slot-owned MSHV requires an x86-64 ACL UKI image", + )); + } + if ctx.is_stream_image { + return Err(unsupported( + "Slot-owned MSHV requires file-based ESP deployment", + )); + } + if ctx.spec.internal_params.get_flag(PRESERVE_MSHV_ESP_PAYLOAD) { + return Err(unsupported( + "Shared-path and slot-owned MSHV modes cannot be combined", + )); + } + if ctx + .spec + .storage + .encryption + .as_ref() + .is_some_and(|encryption| !encryption.pcrs.is_empty()) + { + return Err(unsupported( + "Slot-owned MSHV TPM/PCR-bound encryption is not validated", + )); + } + if ctx.servicing_type != ServicingType::CleanInstall { + validate_transition(&ctx.spec_old, &ctx.spec)?; + } + Ok(()) +} + /// Copies the MSHV ESP payload files from the source ESP to the destination ESP /// for a clean install. /// @@ -128,6 +177,43 @@ mod tests { use nix::{sys::stat::Mode, unistd}; use tempfile::TempDir; + use trident_api::constants::internal_params::MSHV_SLOT_ESP_PAYLOAD; + + /// Unsupported MSHV combinations fail only after opt-in. + #[test] + fn rejects_unsupported_mshv_images_without_affecting_other_images() { + let mut ctx = EngineContext { + is_stream_image: true, + is_uki: Some(true), + servicing_type: ServicingType::CleanInstall, + ..Default::default() + } + .with_image(crate::osimage::mock::MockOsImage { + os_release: osutils::osrelease::OsRelease { + id: Some(osutils::osrelease::AZURE_LINUX_DISTRO_ID.into()), + variant_id: Some(osutils::osrelease::AZURE_CONTAINER_LINUX_VARIANT_ID.into()), + ..Default::default() + }, + is_uki: true, + ..crate::osimage::mock::MockOsImage::new() + }); + assert!(validate_configuration(&ctx).is_ok()); + ctx.spec.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); + assert!(validate_configuration(&ctx).is_err()); + ctx.is_stream_image = false; + assert_eq!( + validate_configuration(&ctx).is_ok(), + SystemArchitecture::current().is_x64(), + ); + ctx.spec.storage.encryption = Some(trident_api::config::Encryption { + pcrs: vec![sysdefs::tpm2::Pcr::Pcr4], + ..Default::default() + }); + assert!(validate_configuration(&ctx).is_err()); + ctx.spec.storage.encryption = None; + ctx.spec.internal_params.set_flag(PRESERVE_MSHV_ESP_PAYLOAD); + assert!(validate_configuration(&ctx).is_err()); + } struct EspFixture { source: TempDir, From 3d0376ded06fa548b58d9db05f33937e0d1a7c0e Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Fri, 13 Nov 2026 01:07:23 +0000 Subject: [PATCH 34/82] Remove legacy MSHV payload preservation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3776b97-18ef-40d5-821f-dac82f77e3de --- crates/trident/src/subsystems/esp.rs | 13 +- crates/trident/src/subsystems/esp/mshv.rs | 549 +--------------------- crates/trident_api/src/constants.rs | 3 - docs/Explanation/MSHV.md | 4 +- 4 files changed, 7 insertions(+), 562 deletions(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 75a2268d1b..04ce1fb326 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}, @@ -473,13 +473,6 @@ 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(()) } diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 768cf4cb69..21534be0a1 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -1,18 +1,7 @@ -//! ACL, efitreeloader (ETL), and MSHV support for ESP validation and provisioning. - -use std::{ - fs, - path::{Path, PathBuf}, -}; - -use anyhow::{ensure, Context, Error}; -use log::{debug, warn}; +//! Slot-owned MSHV validation and efitreeloader (ETL) ESP definitions. use sysdefs::arch::SystemArchitecture; -use trident_api::{ - constants::internal_params::PRESERVE_MSHV_ESP_PAYLOAD, error::TridentError, - status::ServicingType, -}; +use trident_api::{error::TridentError, status::ServicingType}; use crate::engine::{ mshv::{enabled, unsupported, validate_transition}, @@ -22,14 +11,6 @@ use crate::engine::{ /// Filename of the second-stage EFI executable for efitreeloader (ETL). pub(super) const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; -/// 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"]; - -/// 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"; - /// Enforces support and mode-transition restrictions when slot-owned MSHV is enabled. pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { if !enabled(&ctx.spec) { @@ -46,11 +27,6 @@ pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE "Slot-owned MSHV requires file-based ESP deployment", )); } - if ctx.spec.internal_params.get_flag(PRESERVE_MSHV_ESP_PAYLOAD) { - return Err(unsupported( - "Shared-path and slot-owned MSHV modes cannot be combined", - )); - } if ctx .spec .storage @@ -68,115 +44,10 @@ pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE Ok(()) } -/// Copies the MSHV ESP payload files from the source ESP to the destination ESP -/// for a clean install. -/// -/// 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())); - } - } - - 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() - ) - })?; - } - - Ok(()) -} - #[cfg(test)] mod tests { use super::*; - use std::{ - ffi::OsString, - os::unix::{ffi::OsStringExt, fs as unix_fs}, - }; - - use nix::{sys::stat::Mode, unistd}; - use tempfile::TempDir; use trident_api::constants::internal_params::MSHV_SLOT_ESP_PAYLOAD; /// Unsupported MSHV combinations fail only after opt-in. @@ -210,421 +81,5 @@ mod tests { ..Default::default() }); assert!(validate_configuration(&ctx).is_err()); - ctx.spec.storage.encryption = None; - ctx.spec.internal_params.set_flag(PRESERVE_MSHV_ESP_PAYLOAD); - assert!(validate_configuration(&ctx).is_err()); - } - - struct EspFixture { - source: TempDir, - destination: TempDir, - } - - 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()) - } - - 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() - ); - assert_eq!( - fs::read(self.source.path().join(relative_path)).unwrap(), - relative_path.as_bytes() - ); - } - } - - 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 d1d726620b..92be6f3a75 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"; - /// Stage an experimental slot-owned MSHV ESP bundle with its OS image. pub const MSHV_SLOT_ESP_PAYLOAD: &str = "mshvSlotEspPayload"; diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index 858aa7ff37..719797fe2d 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -117,8 +117,8 @@ without classifying an identity failure as a user health-check failure. ## Current Limitations The current implementation is limited to x86-64 ACL UKI images because the -payload definition hardcodes x64 filenames. TPM/PCR-bound encryption and -combining this mode with `preserveMshvEspPayload` are rejected. +payload definition hardcodes x64 filenames. TPM/PCR-bound encryption is +rejected. Offline initialization of MSHV-enabled ACL images is not currently supported. From e82ca71b0b7be54d72325dbd7cc9577c61cf8235 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Fri, 13 Nov 2026 01:13:47 +0000 Subject: [PATCH 35/82] docs: remove experimental label from MSHV parameter Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3776b97-18ef-40d5-821f-dac82f77e3de --- crates/trident_api/src/constants.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/trident_api/src/constants.rs b/crates/trident_api/src/constants.rs index 92be6f3a75..e28f4c4633 100644 --- a/crates/trident_api/src/constants.rs +++ b/crates/trident_api/src/constants.rs @@ -241,7 +241,7 @@ pub mod internal_params { /// Run extra partition and filesystem checks before reboot. pub const PRE_REBOOT_CHECKS: &str = "preRebootChecks"; - /// Stage an experimental slot-owned MSHV ESP bundle with its OS image. + /// Stage a slot-owned MSHV ESP bundle with its OS image. pub const MSHV_SLOT_ESP_PAYLOAD: &str = "mshvSlotEspPayload"; /// Re-encrypt the encrypted LUKS2 volumes in-place on clean install, instead of initializing From f4d698e5ef0fe46ca0a74377ca6c7ba4d4c3fbba Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Fri, 13 Nov 2026 17:49:32 +0000 Subject: [PATCH 36/82] Reclaim interrupted UKI staging before ESP deployment Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: aee297a0-5d1d-4c96-a32b-4fc509e108e0 --- crates/trident/src/engine/boot/uki.rs | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index 4663c8b7dd..f002c39702 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -246,6 +246,9 @@ pub(crate) fn find_ukis_to_remove_before_staging( 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); @@ -1584,6 +1587,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] From 327f8e13a67ca2cf19528bd5ef2529ea20ee2e9f Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Fri, 13 Nov 2026 01:33:50 +0000 Subject: [PATCH 37/82] Detect MSHV images from COSI bootloader metadata Remove mshvSlotEspPayload. Inspect installed bundles when no COSI is loaded. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f3776b97-18ef-40d5-821f-dac82f77e3de --- crates/trident/src/engine/boot/mshv.rs | 16 +-- crates/trident/src/engine/context/image.rs | 1 + crates/trident/src/engine/context/mod.rs | 5 + .../trident/src/engine/manual_rollback/mod.rs | 3 - crates/trident/src/engine/mshv.rs | 72 ++++------- crates/trident/src/engine/rollback.rs | 7 -- crates/trident/src/engine/update.rs | 3 - crates/trident/src/init/acl/mod.rs | 25 ++-- crates/trident/src/init/offline/mod.rs | 20 +++- crates/trident/src/lib.rs | 7 +- crates/trident/src/osimage/cosi/metadata.rs | 29 ++++- crates/trident/src/osimage/cosi/validation.rs | 55 +++++---- crates/trident/src/osimage/mock.rs | 4 + crates/trident/src/osimage/mod.rs | 10 ++ crates/trident/src/subsystems/esp.rs | 44 +++---- crates/trident/src/subsystems/esp/mshv.rs | 113 ++++++++++++++---- .../trident/src/subsystems/storage/osimage.rs | 7 ++ crates/trident_api/src/constants.rs | 3 - docs/Explanation/MSHV.md | 42 +++---- .../cosi-metadata-v1.2.schema.json | 6 +- 20 files changed, 264 insertions(+), 208 deletions(-) diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 8ae7a07017..80037e1745 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -21,18 +21,16 @@ const FILES: &[&str] = &[ const SPACE_RESERVE: u64 = 1024 * 1024; -/// Detects slot-owned MSHV in BOOT, requiring the complete bundle when markers exist. -/// No markers means mode off; incomplete bundles and inspection errors fail discovery. -pub(crate) fn has_slot_mshv_bundle(esp_path: &Path) -> Result { - let bundle = esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH); +/// Detects MSHV in an installed bootloader directory; marked bundles must be complete. +pub(crate) fn has_slot_mshv_bundle(bundle: &Path) -> Result { for marker in ["HvLoader.efi", "lxhvloader.dll", "Windows"] { match fs::symlink_metadata(bundle.join(marker)) { Ok(_) => { - validate_bundle(&bundle)?; + validate_bundle(bundle)?; return Ok(true); } Err(error) if error.kind() == ErrorKind::NotFound => {} - Err(error) => return Err(error).context("Failed to inspect MSHV BOOT payload"), + Err(error) => return Err(error).context("Failed to inspect MSHV boot payload"), } } Ok(false) @@ -388,10 +386,7 @@ mod tests { /// Each fallback policy copies whole bundles and preserves the retained slot. #[test] fn fallback_modes_use_the_full_selected_bundle_during_trial_commit_and_rollback() { - use trident_api::{ - constants::internal_params::MSHV_SLOT_ESP_PAYLOAD, - status::{AbVolumeSelection, ServicingState, ServicingType}, - }; + use trident_api::status::{AbVolumeSelection, ServicingState, ServicingType}; for mode in [ UefiFallbackMode::Conservative, UefiFallbackMode::Optimistic, @@ -412,7 +407,6 @@ mod tests { esp_mount_path: ".".into(), ..Default::default() }; - ctx.spec.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); ctx.spec.os.uefi_fallback = mode; crate::subsystems::esp::set_uefi_fallback_contents( &ctx, diff --git a/crates/trident/src/engine/context/image.rs b/crates/trident/src/engine/context/image.rs index 3788c65738..760f2213f4 100644 --- a/crates/trident/src/engine/context/image.rs +++ b/crates/trident/src/engine/context/image.rs @@ -173,6 +173,7 @@ mod tests { os_arch: SystemArchitecture::Amd64, os_release: OsRelease::default(), is_uki: false, + is_mshv: false, partitioning_info: None, images: mock_entries .clone() diff --git a/crates/trident/src/engine/context/mod.rs b/crates/trident/src/engine/context/mod.rs index f0ed166334..37e72e1408 100644 --- a/crates/trident/src/engine/context/mod.rs +++ b/crates/trident/src/engine/context/mod.rs @@ -432,6 +432,11 @@ impl EngineContext { )) } + /// Returns whether the source image declares an MSHV boot chain. + pub(crate) fn is_mshv(&self) -> bool { + self.image.as_ref().is_some_and(OsImage::is_mshv) + } + /// Returns the zstd max window log required for decompression of files /// coming from the OS image, if available. pub(crate) fn image_zstd_max_window_log(&self) -> Option { diff --git a/crates/trident/src/engine/manual_rollback/mod.rs b/crates/trident/src/engine/manual_rollback/mod.rs index da45775577..e95e92cadb 100644 --- a/crates/trident/src/engine/manual_rollback/mod.rs +++ b/crates/trident/src/engine/manual_rollback/mod.rs @@ -151,9 +151,6 @@ pub fn execute_rollback( }; staged_rollback_type = Some(rollback_type); - // Historical targets must preserve the installation's MSHV mode. - engine::mshv::validate_transition(&datastore.host_status().spec, &requested_rollback.spec)?; - let engine_context = EngineContext::new(EngineContextParams { spec: requested_rollback.spec.clone(), spec_old: datastore.host_status().spec.clone(), diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index 8cdd78a0a4..c5dbd5127d 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -1,50 +1,39 @@ use log::warn; +use osutils::container; use trident_api::{ config::HostConfiguration, - constants::internal_params::MSHV_SLOT_ESP_PAYLOAD, - error::{InvalidInputError, TridentError}, + constants::{EFI_DEFAULT_BIN_DIRECTORY, ESP_EFI_DIRECTORY}, + error::{InvalidInputError, ReportError, TridentError, TridentResultExt}, status::AbVolumeSelection, }; use super::boot; -/// Attributes unsupported configurations to the MSHV mode parameter. -pub(crate) fn unsupported(reason: &str) -> TridentError { - TridentError::new(InvalidInputError::InvalidInternalParameter { - name: MSHV_SLOT_ESP_PAYLOAD.into(), - explanation: reason.into(), - }) -} - -/// Checks the slot-owned MSHV opt-in. -pub(crate) fn enabled(spec: &HostConfiguration) -> bool { - spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD) -} - -/// Rejects MSHV mode changes on an existing installation. -pub(crate) fn validate_transition( - previous: &HostConfiguration, - requested: &HostConfiguration, -) -> Result<(), TridentError> { - if enabled(previous) != enabled(requested) { - return Err(unsupported( - "Changing slot-owned MSHV mode on an existing installation is not supported", - )); - } - Ok(()) -} - -/// Success stub: logs the expected slot only when MSHV is enabled. -/// Does not inspect hypervisor identity. +/// Checks the expected slot's bundle, but assumes its hypervisor identity matches. pub(crate) fn validate_active_hypervisor( spec: &HostConfiguration, install_index: usize, expected_volume: Option, ) -> Result<(), TridentError> { - if enabled(spec) { - let expected_directory = - expected_volume.map(|volume| boot::make_esp_dir_name(install_index, volume)); + let Some(esp_path) = spec + .storage + .filesystems + .iter() + .find(|filesystem| filesystem.is_esp) + .and_then(|filesystem| filesystem.mount_point_path()) + else { + return Ok(()); + }; + let esp_path = container::get_host_relative_path(esp_path.to_path_buf()) + .message("Failed to resolve ESP path for MSHV validation")?; + let expected_directory = expected_volume + .map(|volume| boot::make_esp_dir_name(install_index, volume)) + .unwrap_or_else(|| EFI_DEFAULT_BIN_DIRECTORY.into()); + // Boot validation has no COSI loaded; inspect the expected slot, not fallback. + if boot::mshv::has_slot_mshv_bundle(&esp_path.join(ESP_EFI_DIRECTORY).join(&expected_directory)) + .structured(InvalidInputError::InvalidBootConfiguration)? + { // TODO: Identify the running hypervisor and compare it with the expected OS payload. warn!( "MSHV hypervisor identity validation is not implemented; assuming success for {:?}", @@ -53,20 +42,3 @@ pub(crate) fn validate_active_hypervisor( } Ok(()) } - -#[cfg(test)] -mod tests { - use super::*; - - /// Matching modes pass; transitions fail in either direction. - #[test] - fn rejects_mode_changes_but_allows_matching_installation_modes() { - let ordinary = HostConfiguration::default(); - let mut mshv = ordinary.clone(); - mshv.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); - assert!(validate_transition(&ordinary, &mshv).is_err()); - assert!(validate_transition(&mshv, &ordinary).is_err()); - assert!(validate_transition(&ordinary, &ordinary).is_ok()); - assert!(validate_transition(&mshv, &mshv).is_ok()); - } -} diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index c8ffb2a6e6..49b6fb6f35 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -77,13 +77,6 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result ServicingType::NoActiveServicing, }; - // Preserve MSHV mode except on clean install, which has no previous mode. - if current_servicing_state != ServicingState::CleanInstallFinalized { - super::mshv::validate_transition( - &datastore.host_status().spec_old, - &datastore.host_status().spec, - )?; - } // Recovery validates the retained OS, not the failed candidate. let recovering = matches!( current_servicing_state, diff --git a/crates/trident/src/engine/update.rs b/crates/trident/src/engine/update.rs index a73e6ce53c..ff39e390c4 100644 --- a/crates/trident/src/engine/update.rs +++ b/crates/trident/src/engine/update.rs @@ -60,9 +60,6 @@ pub(crate) fn update( image: Some(image), })?; - // Reject MSHV mode changes before selection, including for no-op updates. - engine::mshv::validate_transition(&ctx.spec_old, &ctx.spec)?; - // Before starting an update servicing, need to validate that the active volume is set // correctly. if ctx.spec.storage.ab_update.is_some() { diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index f8c6906314..9ba51dc1d0 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -20,7 +20,7 @@ use trident_api::{ MountOptions, MountPoint, Partition, PartitionSize, PartitionTableType, PartitionType, Storage, VerityDevice, }, - constants::internal_params::MSHV_SLOT_ESP_PAYLOAD, + constants::EFI_DEFAULT_BIN_RELATIVE_PATH, error::TridentResultExt, status::{AbVolumeSelection, HostStatus, ServicingState}, BlockDeviceId, @@ -89,7 +89,7 @@ pub fn initial_host_status() -> Result { /// initial ACL HostStatus, separated from the code that gets the /// Host's current disk information. This allows for easier testing /// of the HostStatus creation logic. -/// Complete MSHV bundles enable slot-owned mode; incomplete marked bundles fail. +/// Rejects incomplete MSHV bundles without modifying the ESP. fn inner_initial_host_status( disk_information: &SfDisk, root_blk_device: &BlockDevice, @@ -234,7 +234,7 @@ fn inner_initial_host_status( }); } - let mut host_status = HostStatus { + let host_status = HostStatus { spec: HostConfiguration { storage: Storage { disks: vec![Disk { @@ -306,13 +306,7 @@ fn inner_initial_host_status( partition_paths, ..Default::default() }; - // Adoption bootstraps AZLA before persisting this discovered mode. - if mshv::has_slot_mshv_bundle(esp_path)? { - host_status - .spec - .internal_params - .set_flag(MSHV_SLOT_ESP_PAYLOAD); - } + mshv::has_slot_mshv_bundle(&esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH))?; Ok(host_status) } @@ -500,14 +494,13 @@ mod tests { } } - /// Only complete BOOT bundles enable MSHV; discovery leaves AZLA untouched. + /// MSHV discovery needs no configuration flag and leaves AZLA untouched. #[test] - fn initial_host_status_discovers_slot_mshv_from_image() { + fn initial_host_status_accepts_slot_mshv_without_opt_in() { let esp = tempfile::TempDir::new().unwrap(); let disk = create_sfdisk("EFI-SYSTEM", TestPartitions::Correct); let device = create_blk_device(); - let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); - assert!(!status.spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD)); + let ordinary = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); std::fs::create_dir_all(esp.path().join("EFI/BOOT")).unwrap(); std::fs::write(esp.path().join("EFI/BOOT/bootx64.efi"), b"shim").unwrap(); @@ -517,11 +510,11 @@ mod tests { ) .unwrap(); let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); - assert!(!status.spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD)); + assert_eq!(status.spec, ordinary.spec); create_mshv_bundle(esp.path()); let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); - assert!(status.spec.internal_params.get_flag(MSHV_SLOT_ESP_PAYLOAD)); + assert_eq!(status.spec, ordinary.spec); assert!(!esp.path().join("EFI/AZLA").exists()); } diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index 7863eb5fc5..7707c25964 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -19,7 +19,9 @@ use trident_api::{ MountOptions, MountPoint, Partition, PartitionSize, PartitionTableType, PartitionType, VerityCorruptionOption, VerityDevice, }, - constants::{internal_params::ENABLE_UKI_SUPPORT, ROOT_MOUNT_POINT_PATH}, + constants::{ + internal_params::ENABLE_UKI_SUPPORT, EFI_DEFAULT_BIN_RELATIVE_PATH, ROOT_MOUNT_POINT_PATH, + }, error::{ ExecutionEnvironmentMisconfigurationError, InitializationError, InternalError, InvalidInputError, ReportError, TridentError, TridentResultExt, @@ -511,9 +513,6 @@ pub fn execute( generate_host_status(&history, lsblk_output, lazy_partitions, disk)? }; - // Reject explicit MSHV mode before persistence/bootstrap; unflagged payloads go undetected. - crate::engine::mshv::validate_transition(&Default::default(), &host_status.spec)?; - debug!( "host_status:\n{}", serde_yaml::to_string(&host_status).unwrap_or("Failed to serialize Host Status".into()) @@ -537,7 +536,18 @@ pub fn execute( "Failed to find ESP filesystem in Host Status, validation should have failed if this was the case", )))?; - esp::bootstrap_azla_from_fallback(esp_path, false) + // Offline initialization has no source COSI; inspect the installed BOOT bundle. + if crate::engine::boot::mshv::has_slot_mshv_bundle( + &esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH), + ) + .structured(InvalidInputError::InvalidBootConfiguration)? + { + return Err(TridentError::new( + InvalidInputError::InvalidBootConfiguration, + )) + .message("Offline initialization of slot-owned MSHV images is not supported"); + } + esp::bootstrap_azla_from_fallback(esp_path) .structured(InvalidInputError::InvalidBootConfiguration) .message("Failed to bootstrap AZLA from fallback")?; diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index e3f8ddcbc6..b2e2075ad3 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -636,9 +636,6 @@ impl Trident { .structured(InvalidInputError::DeriveHostConfiguration) .message("Failed to initialize host status for ACL")?; - // Adoption requires matching requested and discovered MSHV modes. - engine::mshv::validate_transition(&initial_host_status.spec, &host_config)?; - // Mirror offline-initialize's bootstrap: ACL lazy adoption derives // HostStatus metadata only, it never touches the ESP. Seed EFI/AZLA from // EFI/BOOT now so manual rollback's "AZLA must already exist" invariant @@ -661,9 +658,7 @@ impl Trident { let esp_path = container::get_host_relative_path(esp_path.to_path_buf()) .message("Failed to resolve ESP path relative to host for ACL")?; - // MSHV adoption copies the full nested bundle. - let slot_mshv = engine::mshv::enabled(&initial_host_status.spec); - esp::bootstrap_azla_from_fallback(&esp_path, slot_mshv) + esp::bootstrap_azla_from_fallback(&esp_path) .structured(InvalidInputError::InvalidBootConfiguration) .message("Failed to bootstrap AZLA ESP path for ACL")?; diff --git a/crates/trident/src/osimage/cosi/metadata.rs b/crates/trident/src/osimage/cosi/metadata.rs index 8061aa7166..2377c842e9 100644 --- a/crates/trident/src/osimage/cosi/metadata.rs +++ b/crates/trident/src/osimage/cosi/metadata.rs @@ -148,6 +148,13 @@ impl CosiMetadata { self.bootloader.as_ref().map(OsImageBootloader::from) } + /// Returns whether the image declares an efitreeloader/MSHV/systemd-boot chain. + pub(crate) fn is_mshv(&self) -> bool { + self.bootloader.as_ref().is_some_and(|bootloader| { + bootloader.bootloader_type == BootloaderType::EfitreeloaderMshvSystemdBoot + }) + } + /// Returns the ESP filesystem image. pub(super) fn get_esp_filesystem(&self) -> Result<&Image, Error> { let matches = self @@ -351,6 +358,9 @@ pub(crate) enum BootloaderType { #[serde(rename = "systemd-boot")] SystemdBoot, + #[serde(rename = "efitreeloader-mshv-systemd-boot")] + EfitreeloaderMshvSystemdBoot, + #[serde(rename = "grub")] Grub, @@ -895,7 +905,7 @@ mod tests { } #[test] - fn test_is_uki() { + fn test_bootloader_detection() { fn parse(value: Value) -> CosiMetadata { serde_json::from_value(value).unwrap() } @@ -930,11 +940,26 @@ mod tests { }); assert!(parse(base.clone()).is_uki()); + assert!(!parse(base.clone()).is_mshv()); + + let mut mshv = base.clone(); + mshv["bootloader"]["type"] = json!("efitreeloader-mshv-systemd-boot"); + let metadata = parse(mshv); + assert!(metadata.is_mshv()); + assert!(metadata.is_uki()); + + for bootloader_type in ["grub", "unknown"] { + let mut other = base.clone(); + other["bootloader"]["type"] = json!(bootloader_type); + assert!(!parse(other).is_mshv()); + } // No bootloader => false. let mut no_bootloader = base.clone(); no_bootloader.as_object_mut().unwrap().remove("bootloader"); - assert!(!parse(no_bootloader).is_uki()); + let metadata = parse(no_bootloader); + assert!(!metadata.is_uki()); + assert!(!metadata.is_mshv()); // No systemdBoot section => false. let mut no_systemd_boot = base.clone(); diff --git a/crates/trident/src/osimage/cosi/validation.rs b/crates/trident/src/osimage/cosi/validation.rs index 4fcc38f8f6..2e22417953 100644 --- a/crates/trident/src/osimage/cosi/validation.rs +++ b/crates/trident/src/osimage/cosi/validation.rs @@ -58,24 +58,22 @@ impl CosiMetadata { Some(systemd_boot), ) => { match systemd_boot.entries.as_slice() { - // No entries is invalid [] => { - return mk_err( - CosiMetadataErrorKind::V1_1SystemdBootEmptyEntries, - ); + return mk_err(CosiMetadataErrorKind::V1_1SystemdBootEmptyEntries); } - // First entry MUST be of type 'uki-standalone' - [entry, ..] if !entry.boot_type.eq(&SystemdBootloaderType::UkiStandalone) => warn!( - "First entry of bootloader type 'systemd-boot' is not of type 'uki-standalone'" - ), + // Non-UKI entries only warn here. + [entry, ..] + if !entry.boot_type.eq(&SystemdBootloaderType::UkiStandalone) => + { + warn!("First systemd-boot entry is not of type 'uki-standalone'") + } - // Having more than one entry is warned about, only the first is used in this version of Trident. - [_, rest @..] if !rest.is_empty() => warn!( - "Bootloader type 'systemd-boot' has more than one entry, only the first entry will be used" + // Additional entries are ignored. + [_, rest @ ..] if !rest.is_empty() => warn!( + "Multiple systemd-boot entries found; only the first entry will be used" ), - // Everything else is OK _ => {} } } @@ -386,23 +384,24 @@ mod tests { CosiMetadataErrorKind::V1_1GrubWithSystemdBootEntries, ); - // systemd-boot without systemd-boot entries is invalid. - let mut sdb_missing_entries = base.clone(); - if let Some(obj) = sdb_missing_entries["bootloader"].as_object_mut() { - obj.remove("systemdBoot"); + for bootloader_type in ["systemd-boot", "efitreeloader-mshv-systemd-boot"] { + let mut metadata = base.clone(); + metadata["bootloader"]["type"] = json!(bootloader_type); + parse_and_validate(metadata.clone()).unwrap(); + + let mut missing_entries = metadata.clone(); + missing_entries["bootloader"] + .as_object_mut() + .unwrap() + .remove("systemdBoot"); + assert_validate_err_kind( + missing_entries, + CosiMetadataErrorKind::V1_1SystemdBootMissingEntries, + ); + + metadata["bootloader"]["systemdBoot"]["entries"] = json!([]); + assert_validate_err_kind(metadata, CosiMetadataErrorKind::V1_1SystemdBootEmptyEntries); } - assert_validate_err_kind( - sdb_missing_entries, - CosiMetadataErrorKind::V1_1SystemdBootMissingEntries, - ); - - // systemd-boot with empty entries is invalid. - let mut sdb_empty_entries = base.clone(); - sdb_empty_entries["bootloader"]["systemdBoot"]["entries"] = json!([]); - assert_validate_err_kind( - sdb_empty_entries, - CosiMetadataErrorKind::V1_1SystemdBootEmptyEntries, - ); // efitreeloader/MSHV uses the same systemd-boot configuration. let mut mshv_sdb = base.clone(); diff --git a/crates/trident/src/osimage/mock.rs b/crates/trident/src/osimage/mock.rs index 5c9714cb6f..4da99479ab 100644 --- a/crates/trident/src/osimage/mock.rs +++ b/crates/trident/src/osimage/mock.rs @@ -42,6 +42,9 @@ pub struct MockOsImage { pub is_uki: bool, + #[serde(default)] + pub is_mshv: bool, + #[serde(skip)] pub partitioning_info: Option, } @@ -126,6 +129,7 @@ impl MockOsImage { os_arch: SystemArchitecture::Amd64, os_release: OsRelease::default(), is_uki: false, + is_mshv: false, images: vec![], partitioning_info: None, } diff --git a/crates/trident/src/osimage/mod.rs b/crates/trident/src/osimage/mod.rs index 5b0e55cb03..aa71f59b3d 100644 --- a/crates/trident/src/osimage/mod.rs +++ b/crates/trident/src/osimage/mod.rs @@ -111,6 +111,15 @@ impl OsImage { Ok(os_image) } + /// Returns whether COSI metadata declares an MSHV boot chain. + pub(crate) fn is_mshv(&self) -> bool { + match &self.0 { + OsImageInner::Cosi(cosi) => cosi.metadata.is_mshv(), + #[cfg(test)] + OsImageInner::Mock(mock) => mock.is_mshv, + } + } + pub(crate) fn is_uki(&self) -> bool { match &self.0 { OsImageInner::Cosi(cosi) => cosi.metadata.is_uki(), @@ -506,6 +515,7 @@ mod tests { os_arch: arch, os_release: os_release.clone(), is_uki: false, + is_mshv: false, partitioning_info: None, images: vec![ MockImage::new( diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 04ce1fb326..805bf9ea11 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -102,7 +102,6 @@ pub fn set_uefi_fallback_contents( &source_esp_dir_name, &ctx.servicing_type, ctx.install_index, - crate::engine::mshv::enabled(&ctx.spec), )?; } else { debug!( @@ -364,8 +363,10 @@ fn copy_file_artifacts( debug!("Writing boot files to directory {}", esp_dir_path.display()); // MSHV uses a complete bundle, not the ordinary boot-file list. - let slot_mshv = crate::engine::mshv::enabled(&ctx.spec); + let slot_mshv = ctx.is_mshv(); let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + // Compare source metadata with the retained slot before any ESP writes. + mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; let boot_files = if slot_mshv { // Validate and budget space before deleting target-slot files. boot::mshv::validate_bundle(&source_bundle)?; @@ -381,7 +382,7 @@ fn copy_file_artifacts( // Ordinary copying would omit required MSHV payload files. ensure!( !source_bundle.join("HvLoader.efi").try_exists()?, - "A slot-owned MSHV image requires internalParams.mshvSlotEspPayload" + "An MSHV image must declare COSI bootloader type 'efitreeloader-mshv-systemd-boot'" ); generate_boot_filepaths( temp_mount_dir, @@ -579,7 +580,6 @@ fn copy_boot_files_for_uefi_fallback( source_esp_name: &str, servicing_type: &ServicingType, install_index: usize, - slot_mshv: bool, ) -> Result<(), Error> { let esp_dir_path = path::join_relative(mount_point, esp_mount_path).join(ESP_EFI_DIRECTORY); if skip_uefi_fallback_copy( @@ -603,7 +603,8 @@ fn copy_boot_files_for_uefi_fallback( source_esp_dir_path.display(), uefi_fallback_path.display() ); - let result = if slot_mshv { + // Fallback also runs without an image, so detect the selected slot's bundle. + let result = if boot::mshv::has_slot_mshv_bundle(&source_esp_dir_path)? { boot::mshv::replace_bundle(&source_esp_dir_path, &uefi_fallback_path) } else { replace_boot_files(&source_esp_dir_path, &uefi_fallback_path) @@ -721,16 +722,14 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { } /// Seeds missing `EFI/AZLA` from `EFI/BOOT` via a staged directory rename. -/// MSHV validates both bundles when present and preflights space before copying. -/// Existing AZLA contents are never refreshed. -pub fn bootstrap_azla_from_fallback(esp_path: &Path, slot_mshv: bool) -> Result<(), Error> { +/// Detects MSHV from BOOT and preflights capacity before copying. +/// Existing AZLA is validated for MSHV, never refreshed. +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); - if slot_mshv { - boot::mshv::validate_bundle(&boot_esp_path)?; - if azla_esp_path.exists() { - return boot::mshv::validate_bundle(&azla_esp_path); - } + let slot_mshv = boot::mshv::has_slot_mshv_bundle(&boot_esp_path)?; + if slot_mshv && azla_esp_path.exists() { + return boot::mshv::validate_bundle(&azla_esp_path); } trace!("Checking for AZLA volume ESP path at {:?}", &azla_esp_path); if !azla_esp_path.exists() { @@ -1569,7 +1568,7 @@ mod tests { writeln!(file, "{content}").unwrap(); } - bootstrap_azla_from_fallback(esp_dir.path(), false).unwrap(); + bootstrap_azla_from_fallback(esp_dir.path()).unwrap(); for (file_name, _content) in &file_infos { assert!( @@ -1606,7 +1605,7 @@ mod tests { let mut sentinel_file = File::create(&sentinel_path).unwrap(); writeln!(sentinel_file, "Pre-existing AZLA content").unwrap(); - bootstrap_azla_from_fallback(esp_dir.path(), false).unwrap(); + bootstrap_azla_from_fallback(esp_dir.path()).unwrap(); // Ordinary mode neither validates nor refreshes existing AZLA. let contents = fs::read_to_string(&sentinel_path).unwrap(); @@ -1650,7 +1649,7 @@ mod tests { let mut stale_file = File::create(azla_tmp_dir.join("stale-leftover")).unwrap(); writeln!(stale_file, "Leftover from a crashed bootstrap").unwrap(); - bootstrap_azla_from_fallback(esp_dir.path(), false).unwrap(); + bootstrap_azla_from_fallback(esp_dir.path()).unwrap(); // The stale temp dir must be cleaned up, and bootstrapping must // still succeed despite it being present beforehand. @@ -1696,21 +1695,21 @@ mod tests { fs::create_dir_all(&temporary).unwrap(); fs::write(temporary.join("stale"), "incomplete").unwrap(); - bootstrap_azla_from_fallback(esp.path(), true).unwrap(); + bootstrap_azla_from_fallback(esp.path()).unwrap(); for name in files { assert!(files_are_identical(&boot.join(name), &azla.join(name))); } assert!(!temporary.exists()); fs::write(boot.join("HvLoader.efi"), "new fallback").unwrap(); - bootstrap_azla_from_fallback(esp.path(), true).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("Windows/System32/kdstub.dll")).unwrap(); - assert!(bootstrap_azla_from_fallback(esp.path(), true).is_err()); + assert!(bootstrap_azla_from_fallback(esp.path()).is_err()); assert!(!azla.join("Windows/System32/kdstub.dll").exists()); } @@ -1751,7 +1750,7 @@ mod tests { .set_len(length) .unwrap(); - let error = bootstrap_azla_from_fallback(esp.path(), true).unwrap_err(); + let error = bootstrap_azla_from_fallback(esp.path()).unwrap_err(); assert!(error.to_string().contains("Insufficient ESP capacity")); assert!(!temporary.exists()); assert!(!azla.exists()); @@ -1759,7 +1758,7 @@ mod tests { assert_eq!(fs::read(boot.join("HvLoader.efi")).unwrap(), b"retained"); } - /// Incomplete MSHV fallback cannot publish AZLA. + /// Incomplete marked fallback cannot publish AZLA. #[test] fn test_bootstrap_azla_rejects_incomplete_mshv_fallback() { let esp = TempDir::new().unwrap(); @@ -1767,7 +1766,8 @@ mod tests { let azla = esp.path().join(ESP_EFI_DIRECTORY).join("AZLA"); fs::create_dir_all(&boot).unwrap(); fs::write(boot.join(BOOT_EFI), "shim").unwrap(); - assert!(bootstrap_azla_from_fallback(esp.path(), true).is_err()); + fs::write(boot.join("HvLoader.efi"), "loader").unwrap(); + assert!(bootstrap_azla_from_fallback(esp.path()).is_err()); assert!(!azla.exists()); assert_eq!(fs::read_to_string(boot.join(BOOT_EFI)).unwrap(), "shim"); } diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 21534be0a1..591233482c 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -1,19 +1,23 @@ //! Slot-owned MSHV validation and efitreeloader (ETL) ESP definitions. -use sysdefs::arch::SystemArchitecture; -use trident_api::{error::TridentError, status::ServicingType}; +use std::path::Path; -use crate::engine::{ - mshv::{enabled, unsupported, validate_transition}, - EngineContext, +use anyhow::{anyhow, ensure, Context, Error}; +use sysdefs::arch::SystemArchitecture; +use trident_api::{ + constants::ESP_EFI_DIRECTORY, + error::{InvalidInputError, TridentError}, + status::ServicingType, }; +use crate::engine::{boot, EngineContext}; + /// Filename of the second-stage EFI executable for efitreeloader (ETL). pub(super) const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; -/// Enforces support and mode-transition restrictions when slot-owned MSHV is enabled. +/// Enforces support restrictions for images declaring the MSHV bootloader type. pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { - if !enabled(&ctx.spec) { + if !ctx.is_mshv() { return Ok(()); } // The current payload allowlist supports only x86-64. @@ -38,38 +42,63 @@ pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE "Slot-owned MSHV TPM/PCR-bound encryption is not validated", )); } - if ctx.servicing_type != ServicingType::CleanInstall { - validate_transition(&ctx.spec_old, &ctx.spec)?; + Ok(()) +} + +/// Rejects A/B updates that change the retained slot's MSHV layout. +pub(super) 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_bundle = esp_path + .join(ESP_EFI_DIRECTORY) + .join(boot::make_esp_dir_name(ctx.install_index, active_volume)); + ensure!( + boot::mshv::has_slot_mshv_bundle(&active_bundle)? == ctx.is_mshv(), + "Changing slot-owned MSHV mode on an existing installation is not supported" + ); Ok(()) } +/// Reports unsupported MSHV boot configurations. +fn unsupported(reason: &str) -> TridentError { + TridentError::with_source( + InvalidInputError::InvalidBootConfiguration, + anyhow!("{reason}"), + ) +} + #[cfg(test)] mod tests { use super::*; - use trident_api::constants::internal_params::MSHV_SLOT_ESP_PAYLOAD; + use crate::osimage::{mock::MockOsImage, OsImage}; - /// Unsupported MSHV combinations fail only after opt-in. + /// Only metadata-declared MSHV images receive these restrictions. #[test] fn rejects_unsupported_mshv_images_without_affecting_other_images() { - let mut ctx = EngineContext { - is_stream_image: true, - is_uki: Some(true), - servicing_type: ServicingType::CleanInstall, - ..Default::default() - } - .with_image(crate::osimage::mock::MockOsImage { + let mut image = MockOsImage { os_release: osutils::osrelease::OsRelease { id: Some(osutils::osrelease::AZURE_LINUX_DISTRO_ID.into()), variant_id: Some(osutils::osrelease::AZURE_CONTAINER_LINUX_VARIANT_ID.into()), ..Default::default() }, is_uki: true, - ..crate::osimage::mock::MockOsImage::new() - }); + ..MockOsImage::new() + }; + let mut ctx = EngineContext { + is_stream_image: true, + is_uki: Some(true), + servicing_type: ServicingType::CleanInstall, + ..Default::default() + } + .with_image(image.clone()); assert!(validate_configuration(&ctx).is_ok()); - ctx.spec.internal_params.set_flag(MSHV_SLOT_ESP_PAYLOAD); + image.is_mshv = true; + ctx.image = Some(OsImage::mock(image)); assert!(validate_configuration(&ctx).is_err()); ctx.is_stream_image = false; assert_eq!( @@ -82,4 +111,46 @@ mod tests { }); assert!(validate_configuration(&ctx).is_err()); } + + /// Source metadata must match the retained slot, including non-default slots. + #[test] + fn rejects_mshv_layout_changes() { + use trident_api::status::AbVolumeSelection; + + for retained_mshv in [false, true] { + let esp = tempfile::TempDir::new().unwrap(); + if retained_mshv { + for name in [ + "bootx64.efi", + "grubx64.efi", + "second.efi", + "HvLoader.efi", + "lxhvloader.dll", + "Windows/System32/hvix64.exe", + "Windows/System32/hvax64.exe", + "Windows/System32/kdstub.dll", + ] { + let path = esp.path().join("EFI/AZL2B").join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, b"payload").unwrap(); + } + } + let mut ctx = EngineContext { + servicing_type: ServicingType::AbUpdate, + install_index: 1, + ab_active_volume: Some(AbVolumeSelection::VolumeB), + ..Default::default() + }; + for requested_mshv in [false, true] { + ctx.image = Some(OsImage::mock(MockOsImage { + is_mshv: requested_mshv, + ..MockOsImage::new() + })); + assert_eq!( + validate_transition(&ctx, esp.path()).is_ok(), + retained_mshv == requested_mshv + ); + } + } + } } diff --git a/crates/trident/src/subsystems/storage/osimage.rs b/crates/trident/src/subsystems/storage/osimage.rs index 387bb75cd4..0b9db06606 100644 --- a/crates/trident/src/subsystems/storage/osimage.rs +++ b/crates/trident/src/subsystems/storage/osimage.rs @@ -811,6 +811,7 @@ mod tests { }, ], is_uki: false, + is_mshv: false, partitioning_info: None, }; let os_image = OsImage::mock(mock_image.clone()); @@ -862,6 +863,7 @@ mod tests { }, ], is_uki: false, + is_mshv: false, partitioning_info: None, }) .with_spec(HostConfiguration { @@ -920,6 +922,7 @@ mod tests { }, ], is_uki: false, + is_mshv: false, partitioning_info: None, }); @@ -954,6 +957,7 @@ mod tests { }, ], is_uki: false, + is_mshv: false, partitioning_info: None, }; @@ -1005,6 +1009,7 @@ mod tests { verity: None, }], is_uki: false, + is_mshv: false, partitioning_info: None, }; @@ -1468,6 +1473,7 @@ mod tests { }), }], is_uki: false, + is_mshv: false, partitioning_info: None, } } @@ -1668,6 +1674,7 @@ mod functional_test { os_arch: SystemArchitecture::Amd64, os_release: OsRelease::default(), is_uki: false, + is_mshv: false, images: vec![MockImage { mount_point: PathBuf::from("/"), fs_type: OsImageFileSystemType::Ext4, diff --git a/crates/trident_api/src/constants.rs b/crates/trident_api/src/constants.rs index e28f4c4633..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"; - /// Stage a slot-owned MSHV ESP bundle with its OS image. - pub const MSHV_SLOT_ESP_PAYLOAD: &str = "mshvSlotEspPayload"; - /// 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/MSHV.md b/docs/Explanation/MSHV.md index 719797fe2d..8de995dc23 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -78,20 +78,16 @@ for UKI naming and managed boot-directory conventions. ## Enabling Slot-Owned Servicing Use an x86-64 ACL UKI COSI containing the complete BOOT bundle and built with -the matching efitreeloader prefix resolver. Include this flag in the -[Host Configuration](../Reference/Host-Configuration/API-Reference/HostConfiguration.md): +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. -```yaml -internalParams: - mshvSlotEspPayload: true -``` - -Enable the flag during clean installation or first-update ACL adoption, and -keep it enabled for subsequent updates. +Trident selects MSHV servicing from this bootloader type, without a Host +Configuration opt-in. -For first-update adoption, Trident discovers the mode from the installed -image's BOOT bundle and requires the request to match. It seeds the complete -AZLA bundle before persisting the discovered HostStatus. Incomplete MSHV +For first-update adoption, no source COSI describes the installed image. +Trident detects its BOOT bundle and seeds the complete AZLA bundle before +persisting the discovered HostStatus. Incomplete marked MSHV bundles fail discovery; legacy shared files outside BOOT do not establish slot-owned mode. @@ -120,25 +116,15 @@ The current implementation is limited to x86-64 ACL UKI images because the payload definition hardcodes x64 filenames. TPM/PCR-bound encryption is rejected. +Slot-owned MSHV requires file-based ESP deployment, not image streaming. Offline initialization of MSHV-enabled ACL images is not currently supported. -### Changing the Recorded Mode - -Here, "mode" means the `internalParams.mshvSlotEspPayload` flag, not whether -the kernel supports MSHV. An installation is already managed once Trident has -persisted its HostStatus. Subsequent update requests and historical -configurations selected for manual rollback must retain the recorded flag: - -* If recorded as enabled, keep `mshvSlotEspPayload: true`. Setting it to false - or omitting it from an update request is rejected. -* If recorded as disabled, setting `mshvSlotEspPayload: true` is rejected, - even if the new COSI contains an MSHV bundle. +### Changing the Boot Layout -Trident does not convert an existing shared/non-MSHV payload layout into -slot-owned management, or convert a slot-owned installation back out of it. -Normal A/B updates and rollbacks that retain the same flag remain supported. -The initial mode is established during clean installation or discovered -during first-update ACL adoption, before an installation is already managed. +A/B staging compares the source COSI's bootloader type with the retained +slot's actual bundle. 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 diff --git a/docs/Reference/Composable-OS-Image/cosi-metadata-v1.2.schema.json b/docs/Reference/Composable-OS-Image/cosi-metadata-v1.2.schema.json index e1ed2bf45b..44f2093e54 100644 --- a/docs/Reference/Composable-OS-Image/cosi-metadata-v1.2.schema.json +++ b/docs/Reference/Composable-OS-Image/cosi-metadata-v1.2.schema.json @@ -241,10 +241,10 @@ "type": { "description": "The type of the bootloader.", "type": "string", - "enum": ["systemd-boot", "grub"] + "enum": ["systemd-boot", "efitreeloader-mshv-systemd-boot", "grub"] }, "systemdBoot": { - "description": "systemd-boot configuration. Required when `type` == `systemd-boot`; otherwise omitted or null.", + "description": "systemd-boot configuration. Required for systemd-boot and efitreeloader-mshv-systemd-boot; otherwise omitted or null.", "oneOf": [ { "$ref": "#/$defs/SystemDBoot" }, { "type": "null" } @@ -252,7 +252,7 @@ } }, "if": { - "properties": { "type": { "const": "systemd-boot" } }, + "properties": { "type": { "enum": ["systemd-boot", "efitreeloader-mshv-systemd-boot"] } }, "required": ["type"] }, "then": { From c82c8d6ba4ab331d3fc6cb4b9e738257be1e8c25 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Fri, 13 Nov 2026 19:04:18 +0000 Subject: [PATCH 38/82] Align MSHV detection with upstream COSI metadata Reuse the upstream bootloader variant and leave MSHV schema support in COSI 1.3. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: abb45d02-4b14-4d34-aeed-ecf0371fa1ea --- crates/trident/src/osimage/cosi/metadata.rs | 3 --- .../Composable-OS-Image/cosi-metadata-v1.2.schema.json | 6 +++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/crates/trident/src/osimage/cosi/metadata.rs b/crates/trident/src/osimage/cosi/metadata.rs index 2377c842e9..f1e256a488 100644 --- a/crates/trident/src/osimage/cosi/metadata.rs +++ b/crates/trident/src/osimage/cosi/metadata.rs @@ -358,9 +358,6 @@ pub(crate) enum BootloaderType { #[serde(rename = "systemd-boot")] SystemdBoot, - #[serde(rename = "efitreeloader-mshv-systemd-boot")] - EfitreeloaderMshvSystemdBoot, - #[serde(rename = "grub")] Grub, diff --git a/docs/Reference/Composable-OS-Image/cosi-metadata-v1.2.schema.json b/docs/Reference/Composable-OS-Image/cosi-metadata-v1.2.schema.json index 44f2093e54..e1ed2bf45b 100644 --- a/docs/Reference/Composable-OS-Image/cosi-metadata-v1.2.schema.json +++ b/docs/Reference/Composable-OS-Image/cosi-metadata-v1.2.schema.json @@ -241,10 +241,10 @@ "type": { "description": "The type of the bootloader.", "type": "string", - "enum": ["systemd-boot", "efitreeloader-mshv-systemd-boot", "grub"] + "enum": ["systemd-boot", "grub"] }, "systemdBoot": { - "description": "systemd-boot configuration. Required for systemd-boot and efitreeloader-mshv-systemd-boot; otherwise omitted or null.", + "description": "systemd-boot configuration. Required when `type` == `systemd-boot`; otherwise omitted or null.", "oneOf": [ { "$ref": "#/$defs/SystemDBoot" }, { "type": "null" } @@ -252,7 +252,7 @@ } }, "if": { - "properties": { "type": { "enum": ["systemd-boot", "efitreeloader-mshv-systemd-boot"] } }, + "properties": { "type": { "const": "systemd-boot" } }, "required": ["type"] }, "then": { From 3fc019c3e1a92027fa436e6a32dcab7d6700c527 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Fri, 13 Nov 2026 19:23:14 +0000 Subject: [PATCH 39/82] Use shared bootloader model for MSHV detection Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: abb45d02-4b14-4d34-aeed-ecf0371fa1ea --- crates/trident/src/engine/context/image.rs | 1 - crates/trident/src/engine/context/mod.rs | 6 -- crates/trident/src/osimage/bootloader.rs | 2 +- crates/trident/src/osimage/cosi/metadata.rs | 77 +++++++++++-------- crates/trident/src/osimage/cosi/validation.rs | 55 ++++++------- crates/trident/src/osimage/mock.rs | 4 - crates/trident/src/osimage/mod.rs | 10 --- crates/trident/src/subsystems/esp.rs | 3 +- crates/trident/src/subsystems/esp/mshv.rs | 32 +++++--- .../trident/src/subsystems/storage/osimage.rs | 7 -- 10 files changed, 94 insertions(+), 103 deletions(-) diff --git a/crates/trident/src/engine/context/image.rs b/crates/trident/src/engine/context/image.rs index 760f2213f4..3788c65738 100644 --- a/crates/trident/src/engine/context/image.rs +++ b/crates/trident/src/engine/context/image.rs @@ -173,7 +173,6 @@ mod tests { os_arch: SystemArchitecture::Amd64, os_release: OsRelease::default(), is_uki: false, - is_mshv: false, partitioning_info: None, images: mock_entries .clone() diff --git a/crates/trident/src/engine/context/mod.rs b/crates/trident/src/engine/context/mod.rs index 37e72e1408..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() } @@ -432,11 +431,6 @@ impl EngineContext { )) } - /// Returns whether the source image declares an MSHV boot chain. - pub(crate) fn is_mshv(&self) -> bool { - self.image.as_ref().is_some_and(OsImage::is_mshv) - } - /// Returns the zstd max window log required for decompression of files /// coming from the OS image, if available. pub(crate) fn image_zstd_max_window_log(&self) -> Option { 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 f1e256a488..7b2afe28eb 100644 --- a/crates/trident/src/osimage/cosi/metadata.rs +++ b/crates/trident/src/osimage/cosi/metadata.rs @@ -148,13 +148,6 @@ impl CosiMetadata { self.bootloader.as_ref().map(OsImageBootloader::from) } - /// Returns whether the image declares an efitreeloader/MSHV/systemd-boot chain. - pub(crate) fn is_mshv(&self) -> bool { - self.bootloader.as_ref().is_some_and(|bootloader| { - bootloader.bootloader_type == BootloaderType::EfitreeloaderMshvSystemdBoot - }) - } - /// Returns the ESP filesystem image. pub(super) fn get_esp_filesystem(&self) -> Result<&Image, Error> { let matches = self @@ -543,6 +536,8 @@ mod tests { use serde_json::{json, Value}; + use crate::engine::EngineContext; + const SAMPLE_SHA384: &str = "1d0f284efe3edea4b9ca3bd514fa134b17eae361ccc7a1eefeff801b9bd6604e01f21f6bf249ef030599f0c218f2ba8c"; #[test] @@ -561,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 @@ -902,7 +926,7 @@ mod tests { } #[test] - fn test_bootloader_detection() { + fn test_is_uki() { fn parse(value: Value) -> CosiMetadata { serde_json::from_value(value).unwrap() } @@ -937,26 +961,11 @@ mod tests { }); assert!(parse(base.clone()).is_uki()); - assert!(!parse(base.clone()).is_mshv()); - - let mut mshv = base.clone(); - mshv["bootloader"]["type"] = json!("efitreeloader-mshv-systemd-boot"); - let metadata = parse(mshv); - assert!(metadata.is_mshv()); - assert!(metadata.is_uki()); - - for bootloader_type in ["grub", "unknown"] { - let mut other = base.clone(); - other["bootloader"]["type"] = json!(bootloader_type); - assert!(!parse(other).is_mshv()); - } // No bootloader => false. let mut no_bootloader = base.clone(); no_bootloader.as_object_mut().unwrap().remove("bootloader"); - let metadata = parse(no_bootloader); - assert!(!metadata.is_uki()); - assert!(!metadata.is_mshv()); + assert!(!parse(no_bootloader).is_uki()); // No systemdBoot section => false. let mut no_systemd_boot = base.clone(); diff --git a/crates/trident/src/osimage/cosi/validation.rs b/crates/trident/src/osimage/cosi/validation.rs index 2e22417953..4fcc38f8f6 100644 --- a/crates/trident/src/osimage/cosi/validation.rs +++ b/crates/trident/src/osimage/cosi/validation.rs @@ -58,22 +58,24 @@ impl CosiMetadata { Some(systemd_boot), ) => { match systemd_boot.entries.as_slice() { + // No entries is invalid [] => { - return mk_err(CosiMetadataErrorKind::V1_1SystemdBootEmptyEntries); + return mk_err( + CosiMetadataErrorKind::V1_1SystemdBootEmptyEntries, + ); } - // Non-UKI entries only warn here. - [entry, ..] - if !entry.boot_type.eq(&SystemdBootloaderType::UkiStandalone) => - { - warn!("First systemd-boot entry is not of type 'uki-standalone'") - } + // First entry MUST be of type 'uki-standalone' + [entry, ..] if !entry.boot_type.eq(&SystemdBootloaderType::UkiStandalone) => warn!( + "First entry of bootloader type 'systemd-boot' is not of type 'uki-standalone'" + ), - // Additional entries are ignored. - [_, rest @ ..] if !rest.is_empty() => warn!( - "Multiple systemd-boot entries found; only the first entry will be used" + // Having more than one entry is warned about, only the first is used in this version of Trident. + [_, rest @..] if !rest.is_empty() => warn!( + "Bootloader type 'systemd-boot' has more than one entry, only the first entry will be used" ), + // Everything else is OK _ => {} } } @@ -384,24 +386,23 @@ mod tests { CosiMetadataErrorKind::V1_1GrubWithSystemdBootEntries, ); - for bootloader_type in ["systemd-boot", "efitreeloader-mshv-systemd-boot"] { - let mut metadata = base.clone(); - metadata["bootloader"]["type"] = json!(bootloader_type); - parse_and_validate(metadata.clone()).unwrap(); - - let mut missing_entries = metadata.clone(); - missing_entries["bootloader"] - .as_object_mut() - .unwrap() - .remove("systemdBoot"); - assert_validate_err_kind( - missing_entries, - CosiMetadataErrorKind::V1_1SystemdBootMissingEntries, - ); - - metadata["bootloader"]["systemdBoot"]["entries"] = json!([]); - assert_validate_err_kind(metadata, CosiMetadataErrorKind::V1_1SystemdBootEmptyEntries); + // systemd-boot without systemd-boot entries is invalid. + let mut sdb_missing_entries = base.clone(); + if let Some(obj) = sdb_missing_entries["bootloader"].as_object_mut() { + obj.remove("systemdBoot"); } + assert_validate_err_kind( + sdb_missing_entries, + CosiMetadataErrorKind::V1_1SystemdBootMissingEntries, + ); + + // systemd-boot with empty entries is invalid. + let mut sdb_empty_entries = base.clone(); + sdb_empty_entries["bootloader"]["systemdBoot"]["entries"] = json!([]); + assert_validate_err_kind( + sdb_empty_entries, + CosiMetadataErrorKind::V1_1SystemdBootEmptyEntries, + ); // efitreeloader/MSHV uses the same systemd-boot configuration. let mut mshv_sdb = base.clone(); diff --git a/crates/trident/src/osimage/mock.rs b/crates/trident/src/osimage/mock.rs index 4da99479ab..5c9714cb6f 100644 --- a/crates/trident/src/osimage/mock.rs +++ b/crates/trident/src/osimage/mock.rs @@ -42,9 +42,6 @@ pub struct MockOsImage { pub is_uki: bool, - #[serde(default)] - pub is_mshv: bool, - #[serde(skip)] pub partitioning_info: Option, } @@ -129,7 +126,6 @@ impl MockOsImage { os_arch: SystemArchitecture::Amd64, os_release: OsRelease::default(), is_uki: false, - is_mshv: false, images: vec![], partitioning_info: None, } diff --git a/crates/trident/src/osimage/mod.rs b/crates/trident/src/osimage/mod.rs index aa71f59b3d..5b0e55cb03 100644 --- a/crates/trident/src/osimage/mod.rs +++ b/crates/trident/src/osimage/mod.rs @@ -111,15 +111,6 @@ impl OsImage { Ok(os_image) } - /// Returns whether COSI metadata declares an MSHV boot chain. - pub(crate) fn is_mshv(&self) -> bool { - match &self.0 { - OsImageInner::Cosi(cosi) => cosi.metadata.is_mshv(), - #[cfg(test)] - OsImageInner::Mock(mock) => mock.is_mshv, - } - } - pub(crate) fn is_uki(&self) -> bool { match &self.0 { OsImageInner::Cosi(cosi) => cosi.metadata.is_uki(), @@ -515,7 +506,6 @@ mod tests { os_arch: arch, os_release: os_release.clone(), is_uki: false, - is_mshv: false, partitioning_info: None, images: vec![ MockImage::new( diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 805bf9ea11..c6f60a87ed 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -40,6 +40,7 @@ use crate::{ image_streamer, read_monitor::ReadMonitor, }, + osimage::bootloader::Bootloader, }; mod mshv; @@ -363,7 +364,7 @@ fn copy_file_artifacts( debug!("Writing boot files to directory {}", esp_dir_path.display()); // MSHV uses a complete bundle, not the ordinary boot-file list. - let slot_mshv = ctx.is_mshv(); + let slot_mshv = ctx.bootloader().is_some_and(Bootloader::uses_mshv); let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); // Compare source metadata with the retained slot before any ESP writes. mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 591233482c..52b5d6d854 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -10,14 +10,17 @@ use trident_api::{ status::ServicingType, }; -use crate::engine::{boot, EngineContext}; +use crate::{ + engine::{boot, EngineContext}, + osimage::bootloader::Bootloader, +}; /// Filename of the second-stage EFI executable for efitreeloader (ETL). pub(super) const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; /// Enforces support restrictions for images declaring the MSHV bootloader type. pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { - if !ctx.is_mshv() { + if !ctx.bootloader().is_some_and(Bootloader::uses_mshv) { return Ok(()); } // The current payload allowlist supports only x86-64. @@ -57,7 +60,8 @@ pub(super) fn validate_transition(ctx: &EngineContext, esp_path: &Path) -> Resul .join(ESP_EFI_DIRECTORY) .join(boot::make_esp_dir_name(ctx.install_index, active_volume)); ensure!( - boot::mshv::has_slot_mshv_bundle(&active_bundle)? == ctx.is_mshv(), + boot::mshv::has_slot_mshv_bundle(&active_bundle)? + == ctx.bootloader().is_some_and(Bootloader::uses_mshv), "Changing slot-owned MSHV mode on an existing installation is not supported" ); Ok(()) @@ -75,12 +79,12 @@ fn unsupported(reason: &str) -> TridentError { mod tests { use super::*; - use crate::osimage::{mock::MockOsImage, OsImage}; + use crate::osimage::{bootloader::BootloaderType, mock::MockOsImage}; /// Only metadata-declared MSHV images receive these restrictions. #[test] fn rejects_unsupported_mshv_images_without_affecting_other_images() { - let mut image = MockOsImage { + let image = MockOsImage { os_release: osutils::osrelease::OsRelease { id: Some(osutils::osrelease::AZURE_LINUX_DISTRO_ID.into()), variant_id: Some(osutils::osrelease::AZURE_CONTAINER_LINUX_VARIANT_ID.into()), @@ -95,10 +99,12 @@ mod tests { servicing_type: ServicingType::CleanInstall, ..Default::default() } - .with_image(image.clone()); + .with_image(image); assert!(validate_configuration(&ctx).is_ok()); - image.is_mshv = true; - ctx.image = Some(OsImage::mock(image)); + ctx.bootloader = Some(Bootloader::new( + BootloaderType::EfitreeloaderMshvSystemdBoot, + None, + )); assert!(validate_configuration(&ctx).is_err()); ctx.is_stream_image = false; assert_eq!( @@ -142,10 +148,12 @@ mod tests { ..Default::default() }; for requested_mshv in [false, true] { - ctx.image = Some(OsImage::mock(MockOsImage { - is_mshv: requested_mshv, - ..MockOsImage::new() - })); + let bootloader_type = if requested_mshv { + BootloaderType::EfitreeloaderMshvSystemdBoot + } else { + BootloaderType::SystemdBoot + }; + ctx.bootloader = Some(Bootloader::new(bootloader_type, None)); assert_eq!( validate_transition(&ctx, esp.path()).is_ok(), retained_mshv == requested_mshv diff --git a/crates/trident/src/subsystems/storage/osimage.rs b/crates/trident/src/subsystems/storage/osimage.rs index 0b9db06606..387bb75cd4 100644 --- a/crates/trident/src/subsystems/storage/osimage.rs +++ b/crates/trident/src/subsystems/storage/osimage.rs @@ -811,7 +811,6 @@ mod tests { }, ], is_uki: false, - is_mshv: false, partitioning_info: None, }; let os_image = OsImage::mock(mock_image.clone()); @@ -863,7 +862,6 @@ mod tests { }, ], is_uki: false, - is_mshv: false, partitioning_info: None, }) .with_spec(HostConfiguration { @@ -922,7 +920,6 @@ mod tests { }, ], is_uki: false, - is_mshv: false, partitioning_info: None, }); @@ -957,7 +954,6 @@ mod tests { }, ], is_uki: false, - is_mshv: false, partitioning_info: None, }; @@ -1009,7 +1005,6 @@ mod tests { verity: None, }], is_uki: false, - is_mshv: false, partitioning_info: None, }; @@ -1473,7 +1468,6 @@ mod tests { }), }], is_uki: false, - is_mshv: false, partitioning_info: None, } } @@ -1674,7 +1668,6 @@ mod functional_test { os_arch: SystemArchitecture::Amd64, os_release: OsRelease::default(), is_uki: false, - is_mshv: false, images: vec![MockImage { mount_point: PathBuf::from("/"), fs_type: OsImageFileSystemType::Ext4, From a63f54ae47b3e2469aed867ea30ae3e38703d39f Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Sat, 14 Nov 2026 00:10:59 +0000 Subject: [PATCH 40/82] Share MSHV payload paths and correct servicing comments Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 80a35139-3390-48e7-be09-b448aa8769c8 --- crates/trident/src/engine/boot/mshv.rs | 4 +-- .../trident/src/engine/manual_rollback/mod.rs | 2 -- crates/trident/src/engine/mshv.rs | 4 +-- crates/trident/src/engine/rollback.rs | 2 +- crates/trident/src/engine/update.rs | 1 - crates/trident/src/init/acl/mod.rs | 15 +++------- crates/trident/src/init/offline/mod.rs | 2 +- crates/trident/src/subsystems/esp.rs | 29 ++++--------------- crates/trident/src/subsystems/esp/mshv.rs | 16 ++++------ 9 files changed, 20 insertions(+), 55 deletions(-) diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 80037e1745..abafb909a6 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -8,7 +8,7 @@ use trident_api::{config::UefiFallbackMode, constants::EFI_DEFAULT_BIN_RELATIVE_ use crate::engine::{boot::uki, EngineContext}; // This hardcoded x64 payload list limits the current implementation to x86-64. -const FILES: &[&str] = &[ +pub(crate) const FILES: &[&str] = &[ "bootx64.efi", "grubx64.efi", "second.efi", @@ -383,7 +383,7 @@ mod tests { } } - /// Each fallback policy copies whole bundles and preserves the retained slot. + /// Enabled fallback policies copy whole bundles and preserve the retained slot. #[test] fn fallback_modes_use_the_full_selected_bundle_during_trial_commit_and_rollback() { use trident_api::status::{AbVolumeSelection, ServicingState, ServicingType}; diff --git a/crates/trident/src/engine/manual_rollback/mod.rs b/crates/trident/src/engine/manual_rollback/mod.rs index e95e92cadb..0922676212 100644 --- a/crates/trident/src/engine/manual_rollback/mod.rs +++ b/crates/trident/src/engine/manual_rollback/mod.rs @@ -91,8 +91,6 @@ pub fn check_rollback( /// `(ExitKind::Done, ServicingType::NoActiveServicing)` rather than a bare /// `ExitKind::Done` that's indistinguishable from a real rollback at the /// gRPC layer (see `ServicingResponse.servicing_kind` in servicing.proto). -/// -/// Rejects MSHV mode changes before staging a rollback target. pub fn execute_rollback( datastore: &mut DataStore, requested_rollback_kind: ManualRollbackRequestKind, diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index c5dbd5127d..3c1f8fc095 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -10,7 +10,7 @@ use trident_api::{ use super::boot; -/// Checks the expected slot's bundle, but assumes its hypervisor identity matches. +/// Checks the expected boot bundle, but assumes its hypervisor identity matches. pub(crate) fn validate_active_hypervisor( spec: &HostConfiguration, install_index: usize, @@ -30,7 +30,7 @@ pub(crate) fn validate_active_hypervisor( let expected_directory = expected_volume .map(|volume| boot::make_esp_dir_name(install_index, volume)) .unwrap_or_else(|| EFI_DEFAULT_BIN_DIRECTORY.into()); - // Boot validation has no COSI loaded; inspect the expected slot, not fallback. + // No COSI is loaded; inspect the expected slot, or BOOT if no slot is selected. if boot::mshv::has_slot_mshv_bundle(&esp_path.join(ESP_EFI_DIRECTORY).join(&expected_directory)) .structured(InvalidInputError::InvalidBootConfiguration)? { diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 49b6fb6f35..4e9692e9ca 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -38,7 +38,7 @@ pub enum BootValidationResult { InvalidHypervisor(TridentError), } -/// Validates the boot device and calls the MSHV identity hook (currently a success stub). +/// Validates the boot device and installed MSHV bundle, assuming hypervisor identity matches. /// Commits a valid target or reconciles rollback status. Trial A/B validation failures /// can request recovery; recovery failures return errors without another rollback. #[tracing::instrument(skip_all)] diff --git a/crates/trident/src/engine/update.rs b/crates/trident/src/engine/update.rs index ff39e390c4..a57631cfef 100644 --- a/crates/trident/src/engine/update.rs +++ b/crates/trident/src/engine/update.rs @@ -20,7 +20,6 @@ use crate::{ ExitKind, }; -/// Selects and executes update servicing without changing MSHV mode. #[tracing::instrument(skip_all)] pub(crate) fn update( host_config: &HostConfiguration, diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index 9ba51dc1d0..018793e325 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -62,7 +62,7 @@ impl<'a> ExpectedPartition<'a> { /// the expectations of the ACL image layout, and returns a HostStatus /// representing the current state of the host. This will be used to /// initialize the Trident datastore if it has not been created yet. -/// Also discovers MSHV mode without modifying the ESP. +/// Validates any detected MSHV bundle without modifying the ESP. pub fn initial_host_status() -> Result { let blk_devices = lsblk::list().context("Failed to run lsblk")?; let root_blk_device = blk_devices @@ -322,6 +322,8 @@ mod tests { }; use sysdefs::{osuuid::OsUuid, partition_types::DiscoverablePartitionType}; + use crate::engine::boot::mshv::FILES; + enum TestPartitions { Correct, MissingOne, @@ -478,16 +480,7 @@ mod tests { /// Creates a complete BOOT bundle for discovery tests. fn create_mshv_bundle(esp_path: &Path) { - for name in [ - "bootx64.efi", - "grubx64.efi", - "second.efi", - "HvLoader.efi", - "lxhvloader.dll", - "Windows/System32/hvix64.exe", - "Windows/System32/hvax64.exe", - "Windows/System32/kdstub.dll", - ] { + for name in FILES { let path = esp_path.join("EFI/BOOT").join(name); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, b"payload").unwrap(); diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index 7707c25964..270297f6c3 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -459,7 +459,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. -/// Rejects explicit MSHV mode; does not discover MSHV payloads. +/// Rejects detected MSHV bundles, which offline initialization does not support. pub fn execute( hs_path: Option<&Path>, lazy_partitions: &[String], diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index c6f60a87ed..82e5231133 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -724,7 +724,7 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { /// Seeds missing `EFI/AZLA` from `EFI/BOOT` via a staged directory rename. /// Detects MSHV from BOOT and preflights capacity before copying. -/// Existing AZLA is validated for MSHV, never refreshed. +/// When BOOT contains MSHV, existing AZLA is validated but never refreshed. 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); @@ -954,7 +954,7 @@ mod tests { use fs::File; use crate::engine::{ - boot::{get_update_esp_dir_name, make_esp_dir_name_candidates}, + boot::{get_update_esp_dir_name, make_esp_dir_name_candidates, mshv::FILES}, install_index, }; use trident_api::{ @@ -1678,17 +1678,7 @@ mod tests { .path() .join(ESP_EFI_DIRECTORY) .join("AZLA.bootstrap-tmp"); - let files = [ - "bootx64.efi", - "grubx64.efi", - "second.efi", - "HvLoader.efi", - "lxhvloader.dll", - "Windows/System32/hvix64.exe", - "Windows/System32/hvax64.exe", - "Windows/System32/kdstub.dll", - ]; - for name in files { + for name in FILES { let path = boot.join(name); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path, name).unwrap(); @@ -1697,7 +1687,7 @@ mod tests { fs::write(temporary.join("stale"), "incomplete").unwrap(); bootstrap_azla_from_fallback(esp.path()).unwrap(); - for name in files { + for name in FILES { assert!(files_are_identical(&boot.join(name), &azla.join(name))); } assert!(!temporary.exists()); @@ -1724,16 +1714,7 @@ mod tests { .path() .join(ESP_EFI_DIRECTORY) .join("AZLA.bootstrap-tmp"); - for name in [ - "bootx64.efi", - "grubx64.efi", - "second.efi", - "HvLoader.efi", - "lxhvloader.dll", - "Windows/System32/hvix64.exe", - "Windows/System32/hvax64.exe", - "Windows/System32/kdstub.dll", - ] { + for name in FILES { let path = boot.join(name); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path, b"retained").unwrap(); diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 52b5d6d854..5bb0e635ec 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -79,7 +79,10 @@ fn unsupported(reason: &str) -> TridentError { mod tests { use super::*; - use crate::osimage::{bootloader::BootloaderType, mock::MockOsImage}; + use crate::{ + engine::boot::mshv::FILES, + osimage::{bootloader::BootloaderType, mock::MockOsImage}, + }; /// Only metadata-declared MSHV images receive these restrictions. #[test] @@ -126,16 +129,7 @@ mod tests { for retained_mshv in [false, true] { let esp = tempfile::TempDir::new().unwrap(); if retained_mshv { - for name in [ - "bootx64.efi", - "grubx64.efi", - "second.efi", - "HvLoader.efi", - "lxhvloader.dll", - "Windows/System32/hvix64.exe", - "Windows/System32/hvax64.exe", - "Windows/System32/kdstub.dll", - ] { + for name in FILES { let path = esp.path().join("EFI/AZL2B").join(name); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, b"payload").unwrap(); From ce4bd43651cf3263497d45137f1ea80ff4dbe847 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Sat, 14 Nov 2026 01:32:20 +0000 Subject: [PATCH 41/82] Align MSHV imports with module conventions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 80a35139-3390-48e7-be09-b448aa8769c8 --- crates/trident/src/engine/boot/mshv.rs | 85 +++++++++--------- crates/trident/src/engine/mshv.rs | 4 +- crates/trident/src/engine/rollback.rs | 14 +-- crates/trident/src/init/acl/mod.rs | 102 +++++++++------------- crates/trident/src/init/offline/mod.rs | 8 +- crates/trident/src/lib.rs | 18 ++-- crates/trident/src/subsystems/esp.rs | 47 +++++----- crates/trident/src/subsystems/esp/mshv.rs | 34 +++++--- 8 files changed, 155 insertions(+), 157 deletions(-) diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index abafb909a6..c7de0340a6 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -1,11 +1,15 @@ use std::{fs, io::ErrorKind, path::Path}; -use anyhow::{ensure, Context, Result}; -use nix::sys::statvfs::statvfs; -use osutils::uki::uki_addon_dir; +use anyhow::{ensure, Context, Error}; +use nix::sys::statvfs; + +use osutils::uki as uki_utils; use trident_api::{config::UefiFallbackMode, constants::EFI_DEFAULT_BIN_RELATIVE_PATH}; -use crate::engine::{boot::uki, EngineContext}; +use crate::engine::{ + boot::uki::{self, UKI_DIRECTORY}, + EngineContext, +}; // This hardcoded x64 payload list limits the current implementation to x86-64. pub(crate) const FILES: &[&str] = &[ @@ -22,7 +26,7 @@ pub(crate) const FILES: &[&str] = &[ const SPACE_RESERVE: u64 = 1024 * 1024; /// Detects MSHV in an installed bootloader directory; marked bundles must be complete. -pub(crate) fn has_slot_mshv_bundle(bundle: &Path) -> Result { +pub(crate) fn has_slot_mshv_bundle(bundle: &Path) -> Result { for marker in ["HvLoader.efi", "lxhvloader.dll", "Windows"] { match fs::symlink_metadata(bundle.join(marker)) { Ok(_) => { @@ -38,7 +42,7 @@ pub(crate) fn has_slot_mshv_bundle(bundle: &Path) -> Result { /// Checks allowed entries without requiring completeness or following symlinks. /// Matching ignores case; `temporary` also permits known `.new` and `.old` files. -fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { +fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<(), Error> { ensure!( fs::symlink_metadata(directory)?.is_dir(), "Invalid payload directory" @@ -80,7 +84,7 @@ fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<()> { /// Requires the complete allowlisted layout, relying on FAT's case-insensitive lookups. /// Does not validate executable contents or hypervisor identity. -pub(crate) fn validate_bundle(root: &Path) -> Result<()> { +pub(crate) fn validate_bundle(root: &Path) -> Result<(), Error> { validate_tree(root, root, false)?; for name in FILES { ensure!( @@ -95,7 +99,7 @@ pub(crate) fn validate_bundle(root: &Path) -> Result<()> { /// Estimates cluster-rounded file bytes plus one cluster per directory. /// Missing paths contribute zero; symlinks and special files are rejected. -fn allocation(path: &Path, cluster: u64) -> Result { +fn allocation(path: &Path, cluster: u64) -> Result { let metadata = match fs::symlink_metadata(path) { Ok(metadata) => metadata, Err(error) if error.kind() == ErrorKind::NotFound => return Ok(0), @@ -117,7 +121,7 @@ fn allocation(path: &Path, cluster: u64) -> Result { } /// Requires room for the incoming allocation plus a reserve, crediting planned reclamation. -fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<()> { +fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<(), Error> { ensure!( available.saturating_add(reclaimed) >= required.saturating_add(SPACE_RESERVE), "Insufficient ESP capacity: need {required} bytes plus {SPACE_RESERVE} bytes reserve, \ @@ -132,12 +136,12 @@ pub(crate) fn preflight_staging( source_esp: &Path, destination_esp: &Path, target_bundle: &Path, -) -> Result<()> { - let stats = statvfs(destination_esp)?; +) -> Result<(), Error> { + let stats = statvfs::statvfs(destination_esp)?; let cluster = stats.fragment_size(); ensure!(cluster > 0, "Invalid ESP allocation unit"); let bundle = allocation(&source_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH), cluster)?; - let mut required = bundle + allocation(&source_esp.join(uki::UKI_DIRECTORY), cluster)?; + let mut required = bundle + allocation(&source_esp.join(UKI_DIRECTORY), cluster)?; // Account for slot-addon templates whose selected file may replace a smaller live addon. required += allocation(&source_esp.join("acl/uki-addons"), cluster)?; if ctx.spec.os.uefi_fallback != UefiFallbackMode::Disabled { @@ -145,17 +149,17 @@ pub(crate) fn preflight_staging( required += bundle.max(allocation(&existing_fallback, cluster)?); } let mut reclaimed = allocation(target_bundle, cluster)?; - for path in - uki::find_ukis_to_remove_before_staging(ctx, &destination_esp.join(uki::UKI_DIRECTORY))? + for path in uki::find_ukis_to_remove_before_staging(ctx, &destination_esp.join(UKI_DIRECTORY))? { - reclaimed += allocation(&path, cluster)? + allocation(&uki_addon_dir(&path), cluster)?; + reclaimed += + allocation(&path, cluster)? + allocation(&uki_utils::uki_addon_dir(&path), cluster)?; } check_space(stats.blocks_available() * cluster, reclaimed, required) } /// Checks room for a new bundle copy without reclaiming existing ESP contents. -pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<()> { - let stats = statvfs(esp)?; +pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> { + let stats = statvfs::statvfs(esp)?; let cluster = stats.fragment_size(); ensure!(cluster > 0, "Invalid ESP allocation unit"); check_space( @@ -167,7 +171,7 @@ pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<()> { /// Copies a validated bundle non-atomically into an allowlisted destination. /// For atomic publication, copy to a temporary directory and rename it. -pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { +pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<(), Error> { validate_bundle(from)?; fs::create_dir_all(to)?; validate_tree(to, to, false)?; @@ -181,7 +185,7 @@ pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<()> { /// Reconciles `.old` backups and stages all `.new` files before replacing fallback. /// Whole-bundle replacement is not atomic. -pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<()> { +pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<(), Error> { validate_bundle(from)?; match fs::symlink_metadata(to) { Ok(_) => { @@ -194,7 +198,7 @@ pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<()> { Err(error) if error.kind() == ErrorKind::NotFound => {} Err(error) => return Err(error.into()), } - let stats = statvfs(to.parent().context("Missing fallback parent")?)?; + let stats = statvfs::statvfs(to.parent().context("Missing fallback parent")?)?; let cluster = stats.fragment_size(); ensure!(cluster > 0, "Invalid ESP allocation unit"); let required = allocation(from, cluster)?; @@ -237,9 +241,15 @@ pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<()> { #[cfg(test)] mod tests { use super::*; - use std::os::unix::fs::symlink; + + use std::{fs::File, os::unix::fs as unix_fs}; + use tempfile::TempDir; + use trident_api::status::{AbVolumeSelection, ServicingState, ServicingType}; + + use crate::subsystems::esp; + /// Creates a complete test bundle. fn bundle(root: &Path, contents: &[u8]) { for name in FILES { @@ -309,11 +319,11 @@ mod tests { let outside = temp.path().join("outside"); bundle(&source, b"new"); fs::create_dir(&outside).unwrap(); - symlink(&outside, &target).unwrap(); + unix_fs::symlink(&outside, &target).unwrap(); assert!(replace_bundle(&source, &target).is_err()); fs::remove_file(&target).unwrap(); fs::remove_file(source.join("lxhvloader.dll")).unwrap(); - symlink(outside.join("dll"), source.join("lxhvloader.dll")).unwrap(); + unix_fs::symlink(outside.join("dll"), source.join("lxhvloader.dll")).unwrap(); assert!(copy_bundle(&source, &target).is_err()); assert!(fs::read_dir(&outside).unwrap().next().is_none()); } @@ -365,15 +375,15 @@ mod tests { bundle(&source.join(EFI_DEFAULT_BIN_RELATIVE_PATH), b"new"); bundle(&target, b"inactive"); bundle(&retained, b"committed"); - fs::create_dir_all(source.join(uki::UKI_DIRECTORY)).unwrap(); - let stats = statvfs(&destination).unwrap(); - fs::File::create(source.join(uki::UKI_DIRECTORY).join("new.efi")) + fs::create_dir_all(source.join(UKI_DIRECTORY)).unwrap(); + let stats = statvfs::statvfs(&destination).unwrap(); + File::create(source.join(UKI_DIRECTORY).join("new.efi")) .unwrap() .set_len(stats.blocks_available() * stats.fragment_size() + SPACE_RESERVE) .unwrap(); let ctx = EngineContext { - servicing_type: trident_api::status::ServicingType::AbUpdate, - ab_active_volume: Some(trident_api::status::AbVolumeSelection::VolumeA), + servicing_type: ServicingType::AbUpdate, + ab_active_volume: Some(AbVolumeSelection::VolumeA), ..Default::default() }; assert!(preflight_staging(&ctx, &source, &destination, &target).is_err()); @@ -386,7 +396,6 @@ mod tests { /// Enabled fallback policies copy whole bundles and preserve the retained slot. #[test] fn fallback_modes_use_the_full_selected_bundle_during_trial_commit_and_rollback() { - use trident_api::status::{AbVolumeSelection, ServicingState, ServicingType}; for mode in [ UefiFallbackMode::Conservative, UefiFallbackMode::Optimistic, @@ -408,12 +417,8 @@ mod tests { ..Default::default() }; ctx.spec.os.uefi_fallback = mode; - crate::subsystems::esp::set_uefi_fallback_contents( - &ctx, - ServicingState::AbUpdateStaged, - temp.path(), - ) - .unwrap(); + esp::set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateStaged, temp.path()) + .unwrap(); for name in FILES { let expected = if mode == UefiFallbackMode::Optimistic { b"candidate".as_slice() @@ -422,12 +427,8 @@ mod tests { }; assert_eq!(fs::read(fallback.join(name)).unwrap(), expected); } - crate::subsystems::esp::set_uefi_fallback_contents( - &ctx, - ServicingState::AbUpdateFinalized, - temp.path(), - ) - .unwrap(); + esp::set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateFinalized, temp.path()) + .unwrap(); for name in FILES { let expected = if mode == UefiFallbackMode::Disabled { b"retained".as_slice() @@ -439,7 +440,7 @@ mod tests { } ctx.servicing_type = ServicingType::ManualRollbackAb; ctx.ab_active_volume = Some(AbVolumeSelection::VolumeB); - crate::subsystems::esp::set_uefi_fallback_contents( + esp::set_uefi_fallback_contents( &ctx, ServicingState::ManualRollbackAbStaged, temp.path(), diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index 3c1f8fc095..555a29064e 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -8,7 +8,7 @@ use trident_api::{ status::AbVolumeSelection, }; -use super::boot; +use super::boot::{self, mshv as boot_mshv}; /// Checks the expected boot bundle, but assumes its hypervisor identity matches. pub(crate) fn validate_active_hypervisor( @@ -31,7 +31,7 @@ pub(crate) fn validate_active_hypervisor( .map(|volume| boot::make_esp_dir_name(install_index, volume)) .unwrap_or_else(|| EFI_DEFAULT_BIN_DIRECTORY.into()); // No COSI is loaded; inspect the expected slot, or BOOT if no slot is selected. - if boot::mshv::has_slot_mshv_bundle(&esp_path.join(ESP_EFI_DIRECTORY).join(&expected_directory)) + if boot_mshv::has_slot_mshv_bundle(&esp_path.join(ESP_EFI_DIRECTORY).join(&expected_directory)) .structured(InvalidInputError::InvalidBootConfiguration)? { // TODO: Identify the running hypervisor and compare it with the expected OS payload. diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 4e9692e9ca..6e644b1d1c 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -19,8 +19,9 @@ use trident_api::{ use crate::{ engine::{ - bootentries, + boot, bootentries, context::{EngineContext, EngineContextParams}, + mshv, storage::{encryption, verity}, }, health, @@ -116,7 +117,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Result Result { - Ok((ExitKind::Done, servicing_type)) - } - Ok(rollback::BootValidationResult::InvalidHypervisor(e)) - | Ok(rollback::BootValidationResult::ValidBootHealthCheckFailed(e)) => { + Ok(BootValidationResult::ValidBootProvisioned) => Ok((ExitKind::Done, servicing_type)), + Ok(BootValidationResult::InvalidHypervisor(e)) + | Ok(BootValidationResult::ValidBootHealthCheckFailed(e)) => { // The caller must reboot to complete automatic recovery. debug!("Boot validation requires rollback: {e:?}"); Ok((ExitKind::NeedsReboot, servicing_type)) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 82e5231133..686b1db67c 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -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::{ @@ -370,8 +372,8 @@ fn copy_file_artifacts( mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; let boot_files = if slot_mshv { // Validate and budget space before deleting target-slot files. - boot::mshv::validate_bundle(&source_bundle)?; - boot::mshv::preflight_staging( + boot_mshv::validate_bundle(&source_bundle)?; + boot_mshv::preflight_staging( ctx, temp_mount_dir, &path::join_relative(mount_point, &ctx.esp_mount_path), @@ -410,7 +412,7 @@ fn copy_file_artifacts( // Call helper func to copy boot files from temp_mount_dir to esp_dir_path let grub_noprefix = if slot_mshv { - boot::mshv::copy_bundle(&source_bundle, &esp_dir_path)?; + boot_mshv::copy_bundle(&source_bundle, &esp_dir_path)?; false } else { copy_boot_files(temp_mount_dir, &esp_dir_path, boot_files).context(format!( @@ -605,8 +607,8 @@ fn copy_boot_files_for_uefi_fallback( uefi_fallback_path.display() ); // Fallback also runs without an image, so detect the selected slot's bundle. - let result = if boot::mshv::has_slot_mshv_bundle(&source_esp_dir_path)? { - boot::mshv::replace_bundle(&source_esp_dir_path, &uefi_fallback_path) + let result = if boot_mshv::has_slot_mshv_bundle(&source_esp_dir_path)? { + boot_mshv::replace_bundle(&source_esp_dir_path, &uefi_fallback_path) } else { replace_boot_files(&source_esp_dir_path, &uefi_fallback_path) }; @@ -728,9 +730,9 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { 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); - let slot_mshv = boot::mshv::has_slot_mshv_bundle(&boot_esp_path)?; + let slot_mshv = boot_mshv::has_slot_mshv_bundle(&boot_esp_path)?; if slot_mshv && azla_esp_path.exists() { - return boot::mshv::validate_bundle(&azla_esp_path); + return boot_mshv::validate_bundle(&azla_esp_path); } trace!("Checking for AZLA volume ESP path at {:?}", &azla_esp_path); if !azla_esp_path.exists() { @@ -748,8 +750,8 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { } let copy_result = if slot_mshv { // Check capacity after reclaiming stale staging contents. - boot::mshv::preflight_bootstrap(&boot_esp_path, esp_path)?; - boot::mshv::copy_bundle(&boot_esp_path, &azla_tmp_path) + boot_mshv::preflight_bootstrap(&boot_esp_path, esp_path)?; + boot_mshv::copy_bundle(&boot_esp_path, &azla_tmp_path) } else { replace_boot_files(&boot_esp_path, &azla_tmp_path) }; @@ -949,23 +951,24 @@ fn generate_efi_bin_base_dir_path( mod tests { use super::*; - use std::io::Write; + use std::{ + fs::{File, OpenOptions}, + io::Write, + }; - use fs::File; + use nix::sys::statvfs; - use crate::engine::{ - boot::{get_update_esp_dir_name, make_esp_dir_name_candidates, mshv::FILES}, - 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::FILES}, + install_index, + }; + #[test] fn test_generate_efi_bin_base_dir_path_clean_install() { // Clean install EngineContext @@ -1723,9 +1726,9 @@ mod tests { fs::write(temporary.join("stale"), b"abandoned copy").unwrap(); // Force preflight failure with a sparse file, without filling the filesystem. - let stats = nix::sys::statvfs::statvfs(esp.path()).unwrap(); + let stats = statvfs::statvfs(esp.path()).unwrap(); let length = stats.blocks_available() * stats.fragment_size() + 1; - fs::OpenOptions::new() + OpenOptions::new() .write(true) .open(boot.join(BOOT_EFI)) .unwrap() diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 5bb0e635ec..b9e24f2c9f 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -3,6 +3,7 @@ use std::path::Path; use anyhow::{anyhow, ensure, Context, Error}; + use sysdefs::arch::SystemArchitecture; use trident_api::{ constants::ESP_EFI_DIRECTORY, @@ -11,7 +12,10 @@ use trident_api::{ }; use crate::{ - engine::{boot, EngineContext}, + engine::{ + boot::{self, mshv as boot_mshv}, + EngineContext, + }, osimage::bootloader::Bootloader, }; @@ -60,7 +64,7 @@ pub(super) fn validate_transition(ctx: &EngineContext, esp_path: &Path) -> Resul .join(ESP_EFI_DIRECTORY) .join(boot::make_esp_dir_name(ctx.install_index, active_volume)); ensure!( - boot::mshv::has_slot_mshv_bundle(&active_bundle)? + boot_mshv::has_slot_mshv_bundle(&active_bundle)? == ctx.bootloader().is_some_and(Bootloader::uses_mshv), "Changing slot-owned MSHV mode on an existing installation is not supported" ); @@ -79,6 +83,14 @@ fn unsupported(reason: &str) -> TridentError { mod tests { use super::*; + use std::fs; + + use tempfile::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}; + use crate::{ engine::boot::mshv::FILES, osimage::{bootloader::BootloaderType, mock::MockOsImage}, @@ -88,9 +100,9 @@ mod tests { #[test] fn rejects_unsupported_mshv_images_without_affecting_other_images() { let image = MockOsImage { - os_release: osutils::osrelease::OsRelease { - id: Some(osutils::osrelease::AZURE_LINUX_DISTRO_ID.into()), - variant_id: Some(osutils::osrelease::AZURE_CONTAINER_LINUX_VARIANT_ID.into()), + os_release: OsRelease { + id: Some(AZURE_LINUX_DISTRO_ID.into()), + variant_id: Some(AZURE_CONTAINER_LINUX_VARIANT_ID.into()), ..Default::default() }, is_uki: true, @@ -114,8 +126,8 @@ mod tests { validate_configuration(&ctx).is_ok(), SystemArchitecture::current().is_x64(), ); - ctx.spec.storage.encryption = Some(trident_api::config::Encryption { - pcrs: vec![sysdefs::tpm2::Pcr::Pcr4], + ctx.spec.storage.encryption = Some(Encryption { + pcrs: vec![Pcr::Pcr4], ..Default::default() }); assert!(validate_configuration(&ctx).is_err()); @@ -124,15 +136,13 @@ mod tests { /// Source metadata must match the retained slot, including non-default slots. #[test] fn rejects_mshv_layout_changes() { - use trident_api::status::AbVolumeSelection; - for retained_mshv in [false, true] { - let esp = tempfile::TempDir::new().unwrap(); + let esp = TempDir::new().unwrap(); if retained_mshv { for name in FILES { let path = esp.path().join("EFI/AZL2B").join(name); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, b"payload").unwrap(); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"payload").unwrap(); } } let mut ctx = EngineContext { From 44043875bbe18510078f36070f4a8f09e8731801 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Sat, 14 Nov 2026 01:45:10 +0000 Subject: [PATCH 42/82] Discover image-specific MSHV secondary payloads Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 80a35139-3390-48e7-be09-b448aa8769c8 --- crates/trident/src/engine/boot/mshv.rs | 276 ++++++++++++++++++---- crates/trident/src/subsystems/esp.rs | 16 +- crates/trident/src/subsystems/esp/mshv.rs | 2 +- 3 files changed, 249 insertions(+), 45 deletions(-) diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index c7de0340a6..54ae24e0e7 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -1,4 +1,9 @@ -use std::{fs, io::ErrorKind, path::Path}; +use std::{ + collections::BTreeSet, + fs, + io::ErrorKind, + path::{Path, PathBuf}, +}; use anyhow::{ensure, Context, Error}; use nix::sys::statvfs; @@ -11,18 +16,16 @@ use crate::engine::{ EngineContext, }; -// This hardcoded x64 payload list limits the current implementation to x86-64. +// Required top-level x64 boot files; secondary payloads vary between images. pub(crate) const FILES: &[&str] = &[ "bootx64.efi", "grubx64.efi", "second.efi", "HvLoader.efi", "lxhvloader.dll", - "Windows/System32/hvix64.exe", - "Windows/System32/hvax64.exe", - "Windows/System32/kdstub.dll", ]; +const MSHV_ESP_PAYLOAD_DIR: &str = "Windows/System32"; const SPACE_RESERVE: u64 = 1024 * 1024; /// Detects MSHV in an installed bootloader directory; marked bundles must be complete. @@ -40,13 +43,19 @@ pub(crate) fn has_slot_mshv_bundle(bundle: &Path) -> Result { Ok(false) } -/// Checks allowed entries without requiring completeness or following symlinks. -/// Matching ignores case; `temporary` also permits known `.new` and `.old` files. -fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<(), Error> { +/// Validates entries and discovers files without requiring completeness or following symlinks. +/// System32 subdirectories are ignored; `.new` and `.old` suffixes are reserved for staging. +fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result, Error> { ensure!( fs::symlink_metadata(directory)?.is_dir(), "Invalid payload directory" ); + let secondary = directory + .strip_prefix(root)? + .to_str() + .context("Non-UTF-8 MSHV payload path")? + .eq_ignore_ascii_case(MSHV_ESP_PAYLOAD_DIR); + let mut files = Vec::new(); for entry in fs::read_dir(directory)? { let entry = entry?; let path = entry.path(); @@ -54,13 +63,16 @@ fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<(), E let relative_name = relative.to_str().context("Non-UTF-8 MSHV payload path")?; let kind = entry.file_type()?; if kind.is_dir() { + if secondary { + continue; + } ensure!( relative_name.eq_ignore_ascii_case("Windows") - || relative_name.eq_ignore_ascii_case("Windows/System32"), + || relative_name.eq_ignore_ascii_case(MSHV_ESP_PAYLOAD_DIR), "Unexpected payload directory: {}", relative.display() ); - validate_tree(root, &path, temporary)?; + files.extend(validate_tree(root, &path, temporary)?); } else { ensure!( kind.is_file(), @@ -68,24 +80,29 @@ fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result<(), E path.display() ); ensure!( - FILES.iter().any(|name| { - relative_name.eq_ignore_ascii_case(name) - || temporary - && (relative_name.eq_ignore_ascii_case(&format!("{name}.new")) - || relative_name.eq_ignore_ascii_case(&format!("{name}.old"))) - }), + secondary + && (temporary + || !relative_name.rsplit_once('.').is_some_and(|(_, suffix)| { + suffix.eq_ignore_ascii_case("new") || suffix.eq_ignore_ascii_case("old") + })) + || FILES.iter().any(|name| { + relative_name.eq_ignore_ascii_case(name) + || temporary + && (relative_name.eq_ignore_ascii_case(&format!("{name}.new")) + || relative_name.eq_ignore_ascii_case(&format!("{name}.old"))) + }), "Unexpected payload file: {}", relative.display() ); + files.push(relative_name.to_owned()); } } - Ok(()) + Ok(files) } -/// Requires the complete allowlisted layout, relying on FAT's case-insensitive lookups. -/// Does not validate executable contents or hypervisor identity. -pub(crate) fn validate_bundle(root: &Path) -> Result<(), Error> { - validate_tree(root, root, false)?; +/// Discovers a complete bundle, relying on FAT's case-insensitive lookups. +fn bundle_files(root: &Path) -> Result, Error> { + let mut files = validate_tree(root, root, false)?; for name in FILES { ensure!( fs::symlink_metadata(root.join(name)) @@ -94,6 +111,14 @@ pub(crate) fn validate_bundle(root: &Path) -> Result<(), Error> { "Invalid MSHV payload file: {name}" ); } + files.sort(); + Ok(files) +} + +/// Requires the top-level boot files; optional System32 payloads are discovered. +/// Does not validate executable contents or hypervisor identity. +pub(crate) fn validate_bundle(root: &Path) -> Result<(), Error> { + bundle_files(root)?; Ok(()) } @@ -120,6 +145,22 @@ fn allocation(path: &Path, cluster: u64) -> Result { Ok(total) } +/// Budgets selected bundle files and their parents, excluding ignored subdirectories. +fn bundle_allocation(root: &Path, cluster: u64) -> Result { + match fs::symlink_metadata(root) { + Ok(_) => {} + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(0), + Err(error) => return Err(error.into()), + } + let mut directories = BTreeSet::from([PathBuf::new()]); + let mut total = 0; + for name in validate_tree(root, root, true)? { + total += allocation(&root.join(&name), cluster)?; + directories.extend(Path::new(&name).ancestors().skip(1).map(Path::to_path_buf)); + } + Ok(total + directories.len() as u64 * cluster) +} + /// Requires room for the incoming allocation plus a reserve, crediting planned reclamation. fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<(), Error> { ensure!( @@ -140,13 +181,13 @@ pub(crate) fn preflight_staging( let stats = statvfs::statvfs(destination_esp)?; let cluster = stats.fragment_size(); ensure!(cluster > 0, "Invalid ESP allocation unit"); - let bundle = allocation(&source_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH), cluster)?; + let bundle = bundle_allocation(&source_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH), cluster)?; let mut required = bundle + allocation(&source_esp.join(UKI_DIRECTORY), cluster)?; // Account for slot-addon templates whose selected file may replace a smaller live addon. required += allocation(&source_esp.join("acl/uki-addons"), cluster)?; if ctx.spec.os.uefi_fallback != UefiFallbackMode::Disabled { let existing_fallback = destination_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH); - required += bundle.max(allocation(&existing_fallback, cluster)?); + required += bundle.max(bundle_allocation(&existing_fallback, cluster)?); } let mut reclaimed = allocation(target_bundle, cluster)?; for path in uki::find_ukis_to_remove_before_staging(ctx, &destination_esp.join(UKI_DIRECTORY))? @@ -165,17 +206,17 @@ pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> check_space( stats.blocks_available() * cluster, 0, - allocation(from, cluster)?, + bundle_allocation(from, cluster)?, ) } -/// Copies a validated bundle non-atomically into an allowlisted destination. +/// Copies a validated bundle, including discovered System32 files, non-atomically. /// For atomic publication, copy to a temporary directory and rename it. pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<(), Error> { - validate_bundle(from)?; + let files = bundle_files(from)?; fs::create_dir_all(to)?; validate_tree(to, to, false)?; - for name in FILES { + for name in &files { let destination = to.join(name); fs::create_dir_all(destination.parent().context("Missing payload parent")?)?; fs::copy(from.join(name), destination)?; @@ -184,30 +225,32 @@ pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<(), Error> { } /// Reconciles `.old` backups and stages all `.new` files before replacing fallback. +/// Removes retired secondary payload files after publishing the selected bundle. /// Whole-bundle replacement is not atomic. pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<(), Error> { - validate_bundle(from)?; - match fs::symlink_metadata(to) { + let files = bundle_files(from)?; + let existing = match fs::symlink_metadata(to) { Ok(_) => { - validate_tree(to, to, true)?; + let existing = validate_tree(to, to, true)?; ensure!( fs::canonicalize(from)? != fs::canonicalize(to)?, "Source and fallback directories must differ" ); + existing } - Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) if error.kind() == ErrorKind::NotFound => Vec::new(), Err(error) => return Err(error.into()), - } + }; let stats = statvfs::statvfs(to.parent().context("Missing fallback parent")?)?; let cluster = stats.fragment_size(); ensure!(cluster > 0, "Invalid ESP allocation unit"); - let required = allocation(from, cluster)?; + let required = bundle_allocation(from, cluster)?; let mut reclaimed = 0; - for name in FILES { + for name in &files { reclaimed += allocation(&to.join(format!("{name}.new")), cluster)?; } check_space(stats.blocks_available() * cluster, reclaimed, required)?; - for name in FILES { + for name in &files { let destination = to.join(name); let previous = to.join(format!("{name}.old")); fs::create_dir_all(destination.parent().context("Missing payload parent")?)?; @@ -220,21 +263,32 @@ pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<(), Error> { } fs::copy(from.join(name), to.join(format!("{name}.new")))?; } - for name in FILES { + for name in &files { let destination = to.join(name); if destination.exists() { fs::rename(&destination, to.join(format!("{name}.old")))?; } } - for name in FILES { + for name in &files { fs::rename(to.join(format!("{name}.new")), to.join(name))?; } - for name in FILES { + for name in &files { let previous = to.join(format!("{name}.old")); if previous.exists() { fs::remove_file(previous)?; } } + for name in existing { + let base = name + .rsplit_once('.') + .filter(|(_, suffix)| { + suffix.eq_ignore_ascii_case("new") || suffix.eq_ignore_ascii_case("old") + }) + .map_or(name.as_str(), |(base, _)| base); + if !files.iter().any(|file| file.eq_ignore_ascii_case(base)) { + fs::remove_file(to.join(name))?; + } + } Ok(()) } @@ -275,6 +329,136 @@ mod tests { } } + #[test] + fn discovers_optional_secondary_payload_without_recursing() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let target = temp.path().join("target"); + let secondary = source.join("Windows/System32"); + bundle(&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_bundle(&source, &target).unwrap(); + assert_eq!( + fs::read(target.join("Windows/System32/image-specific.bin")).unwrap(), + b"\0\xffpayload" + ); + assert!(!target.join("Windows/System32/drivers").exists()); + assert!(has_slot_mshv_bundle(&target).unwrap()); + + fs::remove_dir_all(source.join("Windows")).unwrap(); + let without_secondary = temp.path().join("without-secondary"); + copy_bundle(&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_bundle(&source, &empty_secondary).unwrap(); + assert!(!empty_secondary.join("Windows").exists()); + + for name in ["payload.dll.new", "payload.dll.old"] { + let path = secondary.join(name); + fs::write(&path, b"reserved temporary name").unwrap(); + assert!(validate_bundle(&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_bundle(&source, &rejected).is_err()); + assert!(!rejected.exists()); + } + + #[test] + fn replaces_changing_secondary_payload_and_recovers_partial_publication() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let fallback = temp.path().join("fallback"); + bundle(&source, b"new"); + bundle(&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_bundle(&source, &fallback).unwrap(); + replace_bundle(&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_bundle(&source, &fallback).unwrap(); + assert!(!fallback.join(secondary).join("current.dll").exists()); + validate_bundle(&fallback).unwrap(); + } + + #[test] + fn budgets_discovered_secondary_payload_but_not_ignored_subdirectories() { + 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/AZLB"); + bundle(&source, b"new"); + bundle(&fallback, b"retained"); + let secondary = source.join("Windows/System32"); + fs::create_dir_all(&secondary).unwrap(); + let large = secondary.join("image-specific.bin"); + let stats = statvfs::statvfs(&esp).unwrap(); + File::create(&large) + .unwrap() + .set_len(stats.blocks_available() * stats.fragment_size() + SPACE_RESERVE) + .unwrap(); + let mut ctx = EngineContext { + servicing_type: ServicingType::AbUpdate, + ab_active_volume: Some(AbVolumeSelection::VolumeA), + ..Default::default() + }; + ctx.spec.os.uefi_fallback = UefiFallbackMode::Disabled; + + assert!(preflight_staging(&ctx, &source_esp, &esp, &target).is_err()); + assert!(preflight_bootstrap(&source, &esp).is_err()); + assert!(replace_bundle(&source, &fallback).is_err()); + assert_eq!( + fs::read(fallback.join("HvLoader.efi")).unwrap(), + b"retained" + ); + assert!(!target.exists()); + + fs::create_dir(secondary.join("ignored")).unwrap(); + fs::rename(&large, secondary.join("ignored/large.bin")).unwrap(); + preflight_staging(&ctx, &source_esp, &esp, &target).unwrap(); + preflight_bootstrap(&source, &esp).unwrap(); + replace_bundle(&source, &fallback).unwrap(); + assert_eq!(fs::read(fallback.join("HvLoader.efi")).unwrap(), b"new"); + assert!(!fallback.join("Windows/System32/ignored").exists()); + } + /// Allowlist matching ignores case; temporary names require opt-in. #[test] fn accepts_fat_filename_casing_but_rejects_unknown_entries() { @@ -409,6 +593,16 @@ mod tests { bundle(&active, b"retained"); bundle(&target, b"candidate"); bundle(&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), @@ -419,7 +613,7 @@ mod tests { ctx.spec.os.uefi_fallback = mode; esp::set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateStaged, temp.path()) .unwrap(); - for name in FILES { + for name in FILES.iter().copied().chain([secondary]) { let expected = if mode == UefiFallbackMode::Optimistic { b"candidate".as_slice() } else { @@ -429,7 +623,7 @@ mod tests { } esp::set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateFinalized, temp.path()) .unwrap(); - for name in FILES { + for name in FILES.iter().copied().chain([secondary]) { let expected = if mode == UefiFallbackMode::Disabled { b"retained".as_slice() } else { @@ -446,7 +640,7 @@ mod tests { temp.path(), ) .unwrap(); - for name in FILES { + for name in FILES.iter().copied().chain([secondary]) { assert_eq!(fs::read(fallback.join(name)).unwrap(), b"retained"); } } diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 686b1db67c..6f19c30c91 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -1671,7 +1671,7 @@ mod tests { } } - /// MSHV copies nested files and validates, but never refreshes, existing AZLA. + /// MSHV discovers secondary files and validates, but never refreshes, existing AZLA. #[test] fn test_bootstrap_azla_from_mshv_fallback() { let esp = TempDir::new().unwrap(); @@ -1686,6 +1686,9 @@ mod tests { 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(); @@ -1693,6 +1696,10 @@ mod tests { for name in 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(); @@ -1702,9 +1709,12 @@ mod tests { "HvLoader.efi" ); - fs::remove_file(azla.join("Windows/System32/kdstub.dll")).unwrap(); + 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(); assert!(bootstrap_azla_from_fallback(esp.path()).is_err()); - assert!(!azla.join("Windows/System32/kdstub.dll").exists()); + assert!(!azla.join("lxhvloader.dll").exists()); } /// Failed preflight follows stale-copy cleanup and leaves BOOT untouched. diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index b9e24f2c9f..e15f79d8d0 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -27,7 +27,7 @@ pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE if !ctx.bootloader().is_some_and(Bootloader::uses_mshv) { return Ok(()); } - // The current payload allowlist supports only x86-64. + // The required bootloader files currently support only x86-64. if !SystemArchitecture::current().is_x64() || !ctx.image_distro().is_acl() || !ctx.is_uki()? { return Err(unsupported( "Slot-owned MSHV requires an x86-64 ACL UKI image", From a9a4140a549bb33e7424e88c835d03877de04426 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Sat, 14 Nov 2026 02:25:02 +0000 Subject: [PATCH 43/82] Restore detailed servicing comments Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 80a35139-3390-48e7-be09-b448aa8769c8 --- crates/trident/src/engine/boot/mshv.rs | 13 +++- crates/trident/src/engine/boot/uki.rs | 33 +++++++-- crates/trident/src/engine/rollback.rs | 22 ++++-- crates/trident/src/lib.rs | 9 ++- crates/trident/src/subsystems/esp.rs | 92 ++++++++++++++++++-------- 5 files changed, 129 insertions(+), 40 deletions(-) diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 54ae24e0e7..b831c55da0 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -9,6 +9,7 @@ use anyhow::{ensure, Context, Error}; use nix::sys::statvfs; use osutils::uki as uki_utils; + use trident_api::{config::UefiFallbackMode, constants::EFI_DEFAULT_BIN_RELATIVE_PATH}; use crate::engine::{ @@ -25,6 +26,9 @@ pub(crate) const FILES: &[&str] = &[ "lxhvloader.dll", ]; +/// Optional bundle-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 = "Windows/System32"; const SPACE_RESERVE: u64 = 1024 * 1024; @@ -210,7 +214,14 @@ pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> ) } -/// Copies a validated bundle, including discovered System32 files, non-atomically. +/// Copies the required top-level boot files listed in `FILES` and any direct +/// secondary MSHV payload files from the optional `MSHV_ESP_PAYLOAD_DIR`, +/// preserving bundle-relative paths. Subdirectories are ignored, and an absent +/// secondary directory is allowed. +/// +/// Validates and discovers the source payload before writing, so missing +/// required files or traversal errors do not leave a partially copied payload. +/// Copying itself is non-atomic and can leave partial output on an I/O failure. /// For atomic publication, copy to a temporary directory and rename it. pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<(), Error> { let files = bundle_files(from)?; diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index f002c39702..e297f3e13c 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -220,9 +220,21 @@ fn remove_uki_and_addons(path: &Path) -> Result<(), Error> { Ok(()) } -/// Frees ESP space by removing target-slot/OS-index UKIs and their addon directories. -/// Also removes original UKIs for OS index 0 once Trident manages its active slot. -/// Other slots and OS indices are preserved. +/// 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 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` +/// files when staging for slot A OS 0, regardless of update index). +/// 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, @@ -255,15 +267,24 @@ pub(crate) fn find_ukis_to_remove_before_staging( let active_suffix = format!("{active_slot}.efi"); let trident_ukis = enumerate_trident_managed_ukis(esp_uki_directory)?; - // Select all update indices for the target slot and OS index. + // 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 { removals.push(path.clone()); } } - // Only OS 0 owns the original UKI. Its managed active slot is sufficient - // rollback; requiring both slots would leave too little ESP space to stage. + // 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); diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 6e644b1d1c..774fc6ad7d 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -39,9 +39,17 @@ pub enum BootValidationResult { InvalidHypervisor(TridentError), } -/// Validates the boot device and installed MSHV bundle, assuming hypervisor identity matches. -/// Commits a valid target or reconciles rollback status. Trial A/B validation failures -/// can request recovery; recovery failures return errors without another rollback. +/// Validates that the firmware correctly booted from the expected target OS +/// image rather than rolling back, and reconciles the Host Status accordingly. +/// +/// Checks the boot device and installed MSHV bundle. The hypervisor identity +/// hook currently assumes success rather than verifying the running hypervisor. +/// +/// 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 or hypervisor validation 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"); @@ -52,7 +60,9 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result datastore.host_status().ab_active_volume, - // Invert the context volume so recovery targets the retained servicing OS. + // For AbUpdateHealthCheckFailed or AbUpdateHypervisorCheckFailed, 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 | ServicingState::AbUpdateHypervisorCheckFailed => { match datastore.host_status().ab_active_volume { @@ -156,7 +166,9 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result { - // Failed recovery leaves Host Status unchanged. + // For an A/B update whose health or hypervisor validation 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/lib.rs b/crates/trident/src/lib.rs index 792a236500..fa95fdc2e1 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -305,7 +305,10 @@ impl Trident { where F: FnOnce(&mut DataStore) -> Result, { - // A recovery error must not replace the original health/hypervisor failure. + // AbUpdateHealthCheckFailed and AbUpdateHypervisorCheckFailed are + // special cases where the last error must be preserved across failed + // recovery attempts. This keeps the original health/hypervisor failure + // visible instead of replacing it with a secondary recovery error. debug!( "Execute and record error with servicing state: {:?} and last error: {:?}", datastore.host_status().servicing_state, @@ -818,7 +821,9 @@ impl Trident { &mut self, datastore: &mut DataStore, ) -> Result<(ExitKind, ServicingType), TridentError> { - // Validate finalized boots and health/hypervisor recovery. + // If the host's servicing state is *Finalized, AbUpdateHealthCheckFailed, + // or AbUpdateHypervisorCheckFailed, re-evaluate the current state of + // the host to validate either the target boot or the recovery boot. let servicing_state = datastore.host_status().servicing_state; if !matches!( servicing_state, diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 6f19c30c91..7e7f01e1a7 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -81,8 +81,9 @@ impl Subsystem for EspSubsystem { /// UEFI fallback is handled in two stages: /// 1. During finalize: /// * Clean install copies the target OS boot files (always volume A). -/// * A/B update copies the candidate in optimistic mode or the retained slot -/// in conservative mode. +/// * 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. @@ -330,7 +331,11 @@ where Ok((temp_image, computed_hash)) } -/// Deploys boot files, preflighting MSHV capacity before reclaiming target-slot 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. For MSHV, validates the bundle +/// and preflights capacity before reclaiming target-slot boot files and UKIs. /// Retained-slot payloads are preserved. fn copy_file_artifacts( temp_image_path: &Path, @@ -387,6 +392,8 @@ fn copy_file_artifacts( !source_bundle.join("HvLoader.efi").try_exists()?, "An MSHV image must declare COSI bootloader type 'efitreeloader-mshv-systemd-boot'" ); + // Generate the ordinary boot-file paths from the temporary directory + // where the source ESP image is mounted. generate_boot_filepaths( temp_mount_dir, ctx.is_uki().unstructured("UKI setting unknown")?, @@ -426,8 +433,12 @@ fn copy_file_artifacts( // Prepare ESP directory structure for UKI boot uki::prepare_esp_for_uki(mount_point, &ctx.esp_mount_path)?; - // MSHV cleaned up after preflight; other UKI images reclaim space here. - // A crash before staging may lose the target UKI, but preserves the active slot. + // Clean up old UKIs for the target slot before staging the new one. + // MSHV already did this after its capacity preflight; other UKI images + // reclaim space here because the ESP may not fit old and new UKIs + // simultaneously (e.g. on a 128 MB ESP). A crash between cleanup and + // staging can remove the target slot's old UKI without a replacement, + // but the active slot's UKI is preserved, retaining a bootable rollback. if !slot_mshv { uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; } @@ -480,17 +491,29 @@ fn copy_file_artifacts( Ok(()) } -/// Selects the slot to copy into `EFI/BOOT`; `None` leaves fallback unchanged. +/// Determines the source directory to copy UEFI fallback boot files from. +/// This varies based on the servicing state and UEFI fallback mode. /// -/// | Servicing state | Optimistic | Conservative | -/// | --- | --- | --- | -/// | CleanInstallStaged | A | A | -/// | AbUpdateStaged | Candidate | Retained | -/// | AbUpdateFinalized | None | Validated target | -/// | ManualRollbackAbStaged | Rollback target | Rollback target | +/// 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. /// -/// Disabled fallback and unlisted states return `None`. -/// A missing active slot defaults to A in the two A/B staging cases. +/// 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, @@ -575,7 +598,11 @@ fn skip_uefi_fallback_copy( false } -/// Replaces fallback with nested MSHV or top-level ordinary files. +/// Copies boot files from the `source_esp_name` folder to the UEFI fallback +/// folder, `EFI/BOOT`. +/// +/// Copies the complete nested bundle for MSHV, 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, @@ -724,9 +751,14 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { Ok(()) } -/// Seeds missing `EFI/AZLA` from `EFI/BOOT` via a staged directory rename. -/// Detects MSHV from BOOT and preflights capacity before copying. -/// When BOOT contains MSHV, existing AZLA is validated but never refreshed. +/// 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. +/// +/// Detects MSHV from BOOT, preflights capacity for its bundle, and publishes a +/// complete copy via a staged directory rename. Existing AZLA is never refreshed: +/// it is validated when BOOT contains MSHV, or left untouched for ordinary BOOT. 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); @@ -740,7 +772,12 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { "AZLA volume ESP path {:?} does not exist, attempting to copy from fallback location", azla_esp_path ); - // An incomplete published AZLA would be skipped or rejected on retry. + // Stage the copy in a temporary sibling directory and publish it via + // an atomic rename only once the copy has fully succeeded. Creating + // AZLA directly before the copy completes could leave a partially + // populated directory on failure. Ordinary-mode retries would skip + // that directory because it exists, while MSHV retries would reject + // its incomplete bundle rather than repair it. 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!( @@ -1223,7 +1260,7 @@ mod tests { UefiFallbackMode::Conservative, Some(AbVolumeSelection::VolumeA), ServicingType::CleanInstall, - Some("AZLA".to_string()), // before reboot, copy the clean-install target + Some("AZLA".to_string()), // in finalize, with 'conservative', copy from volume A (volume we just put COSI files on) "Validate CleanInstallStaged + Conservative + active volume A ==> AZLA", ), ( @@ -1231,7 +1268,7 @@ mod tests { UefiFallbackMode::Optimistic, Some(AbVolumeSelection::VolumeA), ServicingType::CleanInstall, - Some("AZLA".to_string()), // before reboot, copy the clean-install target + Some("AZLA".to_string()), // in finalize, with 'optimistic', copy from volume A (volume we just put COSI files on) "Validate CleanInstallStaged + Optimistic + active volume A ==> AZLA", ), ( @@ -1239,7 +1276,7 @@ mod tests { UefiFallbackMode::Conservative, Some(AbVolumeSelection::VolumeA), ServicingType::AbUpdate, - Some("AZLA".to_string()), // before reboot, preserve the retained slot as fallback + Some("AZLA".to_string()), // in finalize, with 'conservative', copy from active volume (the COSI bits have not been validated yet) "Validate AbUpdateStaged + Conservative + active volume A ==> AZLA", ), ( @@ -1247,7 +1284,7 @@ mod tests { UefiFallbackMode::Optimistic, Some(AbVolumeSelection::VolumeA), ServicingType::AbUpdate, - Some("AZLB".to_string()), // before reboot, copy the staged candidate + Some("AZLB".to_string()), // in finalize, with 'optimistic', copy from inactive volume (that we just put COSI files on) "Validate AbUpdateStaged + Optimistic + active volume A ==> AZLB", ), ( @@ -1263,7 +1300,9 @@ mod tests { UefiFallbackMode::Conservative, Some(AbVolumeSelection::VolumeA), ServicingType::AbUpdate, - Some("AZLB".to_string()), // in commit, copy from the validated update target + // 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", ), ( @@ -1279,7 +1318,7 @@ mod tests { UefiFallbackMode::Optimistic, Some(AbVolumeSelection::VolumeA), ServicingType::AbUpdate, - None, // optimistic fallback already contains the candidate + None, // in commit, with 'optimistic', no copy is needed because it was done in finalize "Validate AbUpdateFinalized + Optimistic + active volume A ==> None", ), ( @@ -1611,7 +1650,8 @@ mod tests { bootstrap_azla_from_fallback(esp_dir.path()).unwrap(); - // Ordinary mode neither validates nor refreshes existing AZLA. + // 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(), From a31dd269265869c3f4238374bbea87b0848db3ee Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Sat, 14 Nov 2026 02:54:06 +0000 Subject: [PATCH 44/82] Fix MSHV fallback cleanup and deployment restrictions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 80a35139-3390-48e7-be09-b448aa8769c8 --- crates/trident/src/init/offline/mod.rs | 17 +----- crates/trident/src/subsystems/esp.rs | 68 +++++++++++++++++++---- crates/trident/src/subsystems/esp/mshv.rs | 15 ++--- 3 files changed, 67 insertions(+), 33 deletions(-) diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index 441c0f2c0f..bb6ddacb33 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -19,9 +19,7 @@ use trident_api::{ MountOptions, MountPoint, Partition, PartitionSize, PartitionTableType, PartitionType, VerityCorruptionOption, VerityDevice, }, - constants::{ - internal_params::ENABLE_UKI_SUPPORT, EFI_DEFAULT_BIN_RELATIVE_PATH, ROOT_MOUNT_POINT_PATH, - }, + constants::{internal_params::ENABLE_UKI_SUPPORT, ROOT_MOUNT_POINT_PATH}, error::{ ExecutionEnvironmentMisconfigurationError, InitializationError, InternalError, InvalidInputError, ReportError, TridentError, TridentResultExt, @@ -31,7 +29,7 @@ use trident_api::{ }; use uuid::Uuid; -use crate::{datastore::DataStore, engine::boot::mshv, subsystems::esp}; +use crate::{datastore::DataStore, subsystems::esp}; #[derive(Clone, Debug, serde::Deserialize)] struct PrismPartition { @@ -459,7 +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. -/// Rejects detected MSHV bundles, which offline initialization does not support. +/// Seeds a missing AZLA from the installed fallback, validating any detected MSHV bundle. pub fn execute( hs_path: Option<&Path>, lazy_partitions: &[String], @@ -536,15 +534,6 @@ pub fn execute( "Failed to find ESP filesystem in Host Status, validation should have failed if this was the case", )))?; - // Offline initialization has no source COSI; inspect the installed BOOT bundle. - if mshv::has_slot_mshv_bundle(&esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH)) - .structured(InvalidInputError::InvalidBootConfiguration)? - { - return Err(TridentError::new( - InvalidInputError::InvalidBootConfiguration, - )) - .message("Offline initialization of slot-owned MSHV images is not supported"); - } esp::bootstrap_azla_from_fallback(esp_path) .structured(InvalidInputError::InvalidBootConfiguration) .message("Failed to bootstrap AZLA from fallback")?; diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 7e7f01e1a7..f0b80f1b5f 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -59,11 +59,8 @@ impl Subsystem for EspSubsystem { mshv::validate_configuration(ctx) } - /// Revalidates MSHV restrictions before file-based ESP deployment. #[tracing::instrument(name = "esp_provision", skip_all)] fn provision(&mut self, ctx: &EngineContext, mount_path: &Path) -> Result<(), TridentError> { - // Recheck constraints even if prior validation was skipped. - mshv::validate_configuration(ctx)?; // Perform file-based deployment of ESP images, if needed, after filesystems have been // mounted and initialized. @@ -679,15 +676,16 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { }) .context("Failed to copy files")?; - // Rename all pre-existing files from to_dir/ to to_dir/.old + // Rename pre-existing entries 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") { + // Leave staged files and pending cleanup entries in place. + if !orig_file_name_string.ends_with(".new") && !orig_file_name_string.ends_with(".old") + { 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!( @@ -731,7 +729,7 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { }) .context("Failed to rename copied files")?; - // Remove all preexisting files .old + // Remove retired files and the known MSHV payload directory. fs::read_dir(to_dir)? .collect::, _>>()? .iter() @@ -739,11 +737,23 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { 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 '{}'", + let result = if orig_path.file_type()?.is_dir() + && orig_file_name + .to_string_lossy() + .eq_ignore_ascii_case("Windows.old") + { + fs::remove_dir_all(orig_path.path()) + } else { + fs::remove_file(orig_path.path()) + }; + result.context(format!( + "Failed to remove pre-existing entry '{}'", orig_path.path().display() ))?; - trace!("Removed pre-existing file '{}'", orig_path.path().display()); + trace!( + "Removed pre-existing entry '{}'", + orig_path.path().display() + ); } Ok::<(), Error>(()) }) @@ -1592,6 +1602,44 @@ 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 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(); + + replace_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_preserves_unrelated_directories() { + 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("unrelated")).unwrap(); + fs::write(destination.path().join("unrelated/keep"), b"unrelated data").unwrap(); + + assert!(replace_boot_files(source.path(), destination.path()).is_err()); + assert_eq!( + fs::read(destination.path().join("unrelated.old/keep")).unwrap(), + b"unrelated data" + ); + } + /// Ordinary bootstrap copies top-level boot files. #[test] fn test_bootstrap_azla_from_fallback() { diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index e15f79d8d0..3bdf330eba 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -22,9 +22,9 @@ use crate::{ /// Filename of the second-stage EFI executable for efitreeloader (ETL). pub(super) const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; -/// Enforces support restrictions for images declaring the MSHV bootloader type. +/// Enforces support restrictions for file-based deployment of MSHV images. pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { - if !ctx.bootloader().is_some_and(Bootloader::uses_mshv) { + if ctx.is_stream_image || !ctx.bootloader().is_some_and(Bootloader::uses_mshv) { return Ok(()); } // The required bootloader files currently support only x86-64. @@ -33,11 +33,6 @@ pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE "Slot-owned MSHV requires an x86-64 ACL UKI image", )); } - if ctx.is_stream_image { - return Err(unsupported( - "Slot-owned MSHV requires file-based ESP deployment", - )); - } if ctx .spec .storage @@ -96,7 +91,7 @@ mod tests { osimage::{bootloader::BootloaderType, mock::MockOsImage}, }; - /// Only metadata-declared MSHV images receive these restrictions. + /// 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 { @@ -120,7 +115,7 @@ mod tests { BootloaderType::EfitreeloaderMshvSystemdBoot, None, )); - assert!(validate_configuration(&ctx).is_err()); + assert!(validate_configuration(&ctx).is_ok()); ctx.is_stream_image = false; assert_eq!( validate_configuration(&ctx).is_ok(), @@ -131,6 +126,8 @@ mod tests { ..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. From f0c172bae12af70b44a595d92377488b84ceb021 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 00:45:18 +0000 Subject: [PATCH 45/82] Generalize commit failure state and gate MSHV validation on runtime device Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d7cd5420-e0f6-473c-ba87-89266961d637 --- crates/trident-client/src/preview.rs | 2 +- crates/trident-client/src/protocol.rs | 4 +- crates/trident-client/src/tests.rs | 4 +- .../src/engine/manual_rollback/utils.rs | 5 +- crates/trident/src/engine/mshv.rs | 109 +++++++++++++----- crates/trident/src/engine/rollback.rs | 53 ++++----- crates/trident/src/lib.rs | 11 +- .../src/server/tridentserver/datastore.rs | 8 +- crates/trident_api/src/status.rs | 24 +++- proto/trident/v1preview/status_service.proto | 4 +- 10 files changed, 140 insertions(+), 84 deletions(-) diff --git a/crates/trident-client/src/preview.rs b/crates/trident-client/src/preview.rs index 5bfd62d3e4..04946a60d7 100644 --- a/crates/trident-client/src/preview.rs +++ b/crates/trident-client/src/preview.rs @@ -49,7 +49,7 @@ pub enum ServicingState { ManualRollbackAbFinalized, Provisioned, AbUpdateHealthCheckFailed, - AbUpdateHypervisorCheckFailed, + CommitFailed, Unknown(i32), } diff --git a/crates/trident-client/src/protocol.rs b/crates/trident-client/src/protocol.rs index 9c072f4cb0..a3a3bc3003 100644 --- a/crates/trident-client/src/protocol.rs +++ b/crates/trident-client/src/protocol.rs @@ -308,9 +308,7 @@ pub(crate) fn decode_servicing_state(state: i32) -> ServicingState { Ok(ProtoServicingState::UpdateAbHealthCheckFailed) => { ServicingState::AbUpdateHealthCheckFailed } - Ok(ProtoServicingState::UpdateAbHypervisorCheckFailed) => { - ServicingState::AbUpdateHypervisorCheckFailed - } + Ok(ProtoServicingState::CommitFailed) => ServicingState::CommitFailed, Err(_) => ServicingState::Unknown(state), } } diff --git a/crates/trident-client/src/tests.rs b/crates/trident-client/src/tests.rs index b71cfda596..cad3ee0149 100644 --- a/crates/trident-client/src/tests.rs +++ b/crates/trident-client/src/tests.rs @@ -1491,8 +1491,8 @@ async fn preview_status_validation_and_rollback_use_domain_types() { async fn preview_status_enums_preserve_known_unspecified_and_unknown_values() { let servicing_states = [ ( - ProtoServicingState::UpdateAbHypervisorCheckFailed as i32, - ServicingState::AbUpdateHypervisorCheckFailed, + ProtoServicingState::CommitFailed as i32, + ServicingState::CommitFailed, ), ( ProtoServicingState::Provisioned as i32, diff --git a/crates/trident/src/engine/manual_rollback/utils.rs b/crates/trident/src/engine/manual_rollback/utils.rs index a08e8e3492..962d6f7d53 100644 --- a/crates/trident/src/engine/manual_rollback/utils.rs +++ b/crates/trident/src/engine/manual_rollback/utils.rs @@ -352,8 +352,7 @@ impl ManualRollbackContext { current_operation.kind = OperationKind::RuntimeManualRollback; current_operation.operation_host_status = Some(current_hs.clone()); } - ServicingState::AbUpdateHealthCheckFailed - | ServicingState::AbUpdateHypervisorCheckFailed => { + ServicingState::AbUpdateHealthCheckFailed | ServicingState::CommitFailed => { // Do not offer the rejected candidate as a rollback target. current_operation.kind = OperationKind::AbUpdateAutoRollback; trace!("Detected AbUpdateAutoRollback operation, ending parsing here."); @@ -1037,7 +1036,7 @@ mod tests { prov(VOL_A, false, vec![], MIN), inter(VOL_A, AB_STAGE, MIN), inter(VOL_A, AB_FINAL, MIN), - inter(VOL_A, ServicingState::AbUpdateHypervisorCheckFailed, MIN), + inter(VOL_A, ServicingState::CommitFailed, MIN), prov_e( VOL_A, false, diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index 555a29064e..0e24349311 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -1,44 +1,95 @@ +use std::path::Path; + use log::warn; -use osutils::container; use trident_api::{ - config::HostConfiguration, - constants::{EFI_DEFAULT_BIN_DIRECTORY, ESP_EFI_DIRECTORY}, - error::{InvalidInputError, ReportError, TridentError, TridentResultExt}, - status::AbVolumeSelection, + constants::EFI_DEFAULT_BIN_DIRECTORY, error::TridentError, status::AbVolumeSelection, }; -use super::boot::{self, mshv as boot_mshv}; +use super::boot; + +const MSHV_DEVICE_PATH: &str = "/dev/mshv"; -/// Checks the expected boot bundle, but assumes its hypervisor identity matches. +/// Calls the identity hook only when the MSHV device is present. pub(crate) fn validate_active_hypervisor( - spec: &HostConfiguration, install_index: usize, expected_volume: Option, ) -> Result<(), TridentError> { - let Some(esp_path) = spec - .storage - .filesystems - .iter() - .find(|filesystem| filesystem.is_esp) - .and_then(|filesystem| filesystem.mount_point_path()) - else { - return Ok(()); - }; - let esp_path = container::get_host_relative_path(esp_path.to_path_buf()) - .message("Failed to resolve ESP path for MSHV validation")?; + validate_if_mshv_present(Path::new(MSHV_DEVICE_PATH), || { + validate_hypervisor_identity(install_index, expected_volume) + }) +} + +fn validate_if_mshv_present( + device: &Path, + check: impl FnOnce() -> Result<(), TridentError>, +) -> Result<(), TridentError> { + // Presence is a best-effort gate, not evidence of the expected hypervisor identity. + if device.exists() { + check()?; + } + Ok(()) +} + +fn validate_hypervisor_identity( + install_index: usize, + expected_volume: Option, +) -> Result<(), TridentError> { let expected_directory = expected_volume .map(|volume| boot::make_esp_dir_name(install_index, volume)) .unwrap_or_else(|| EFI_DEFAULT_BIN_DIRECTORY.into()); - // No COSI is loaded; inspect the expected slot, or BOOT if no slot is selected. - if boot_mshv::has_slot_mshv_bundle(&esp_path.join(ESP_EFI_DIRECTORY).join(&expected_directory)) - .structured(InvalidInputError::InvalidBootConfiguration)? - { - // TODO: Identify the running hypervisor and compare it with the expected OS payload. - warn!( - "MSHV hypervisor identity validation is not implemented; assuming success for {:?}", - expected_directory - ); - } + // TODO: Identify the running hypervisor and compare it with the expected OS payload. + warn!( + "MSHV hypervisor identity validation is not implemented; assuming success for {:?}", + expected_directory + ); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + use std::fs; + + use tempfile::TempDir; + + use trident_api::error::{ErrorKind, ServicingError}; + + #[test] + fn missing_mshv_device_skips_identity_validation() { + let temp = TempDir::new().unwrap(); + validate_if_mshv_present(&temp.path().join("mshv"), || { + panic!("Identity validation must not run without the MSHV device") + }) + .unwrap(); + } + + #[test] + fn present_mshv_device_runs_identity_validation_and_propagates_failure() { + let temp = TempDir::new().unwrap(); + let device = temp.path().join("mshv"); + fs::write(&device, []).unwrap(); + let mut checked = false; + validate_if_mshv_present(&device, || { + checked = true; + Ok(()) + }) + .unwrap(); + assert!(checked); + + let error = validate_if_mshv_present(&device, || { + Err(TridentError::new( + ServicingError::ValidateAbActiveHypervisor { + expected_slot: "AZLB".into(), + observed_slot: Some("AZLA".into()), + }, + )) + }) + .unwrap_err(); + assert!(matches!( + error.kind(), + ErrorKind::Servicing(ServicingError::ValidateAbActiveHypervisor { .. }) + )); + } +} diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 774fc6ad7d..1000eef68c 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -42,8 +42,8 @@ pub enum BootValidationResult { /// Validates that the firmware correctly booted from the expected target OS /// image rather than rolling back, and reconciles the Host Status accordingly. /// -/// Checks the boot device and installed MSHV bundle. The hypervisor identity -/// hook currently assumes success rather than verifying the running hypervisor. +/// Checks the boot device and calls the identity hook when `/dev/mshv` is present. +/// The hook currently assumes success rather than verifying the running hypervisor. /// /// A successful finalized boot continues the commit process. An unexpected boot /// device returns an error, updating Host Status where rollback reconciliation @@ -60,11 +60,10 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result datastore.host_status().ab_active_volume, - // For AbUpdateHealthCheckFailed or AbUpdateHypervisorCheckFailed, use + // For AbUpdateHealthCheckFailed or CommitFailed, 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 - | ServicingState::AbUpdateHypervisorCheckFailed => { + ServicingState::AbUpdateHealthCheckFailed | ServicingState::CommitFailed => { match datastore.host_status().ab_active_volume { Some(AbVolumeSelection::VolumeB) => Some(AbVolumeSelection::VolumeA), Some(AbVolumeSelection::VolumeA) => Some(AbVolumeSelection::VolumeB), @@ -82,7 +81,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result ServicingType::AbUpdate, + | ServicingState::CommitFailed => ServicingType::AbUpdate, ServicingState::CleanInstallFinalized => ServicingType::CleanInstall, ServicingState::ManualRollbackAbFinalized => ServicingType::ManualRollbackAb, _ => ServicingType::NoActiveServicing, @@ -91,7 +90,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Result Result { + | (false, ServicingState::CommitFailed) => { // For an A/B update whose health or hypervisor validation failed, // failure to boot back into the retained servicing OS is a failed // recovery: report the error and leave Host Status unchanged. @@ -205,7 +198,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result { + (true, ServicingState::CommitFailed) => { // Restore the retained OS's status, but still report the rejected update's failure. info!("Rollback to servicing OS succeeded, setting host status from {current_servicing_state:?} to Provisioned"); datastore.with_host_status(|host_status| { @@ -276,7 +269,7 @@ fn record_hypervisor_failure( if state == ServicingState::AbUpdateFinalized { let serialized = serde_yaml::to_value(&error).structured(InternalError::SerializeError)?; datastore.with_host_status(|status| { - status.servicing_state = ServicingState::AbUpdateHypervisorCheckFailed; + status.servicing_state = ServicingState::CommitFailed; status.last_error = Some(serialized); })?; Ok(BootValidationResult::InvalidHypervisor(error)) @@ -900,7 +893,7 @@ mod tests { assert!(matches!(result, BootValidationResult::InvalidHypervisor(_))); assert_eq!( datastore.host_status().servicing_state, - ServicingState::AbUpdateHypervisorCheckFailed + ServicingState::CommitFailed ); assert_eq!( datastore.host_status().last_error.as_ref(), @@ -910,7 +903,7 @@ mod tests { let datastore = DataStore::open(&path).unwrap(); assert_eq!( datastore.host_status().servicing_state, - ServicingState::AbUpdateHypervisorCheckFailed + ServicingState::CommitFailed ); assert_eq!( datastore.host_status().last_error.as_ref(), @@ -926,22 +919,20 @@ mod tests { DataStore::open_or_create(&temp.path().join("datastore.sqlite")).unwrap(); datastore .with_host_status(|status| { - status.servicing_state = ServicingState::AbUpdateHypervisorCheckFailed; + status.servicing_state = ServicingState::CommitFailed; }) .unwrap(); let error = TridentError::new(ServicingError::ValidateAbActiveHypervisor { expected_slot: "AZLA".into(), observed_slot: None, }); - assert!(record_hypervisor_failure( - &mut datastore, - ServicingState::AbUpdateHypervisorCheckFailed, - error, - ) - .is_err()); + assert!( + record_hypervisor_failure(&mut datastore, ServicingState::CommitFailed, error,) + .is_err() + ); assert_eq!( datastore.host_status().servicing_state, - ServicingState::AbUpdateHypervisorCheckFailed + ServicingState::CommitFailed ); } diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index fa95fdc2e1..d8618bd10f 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -305,7 +305,7 @@ impl Trident { where F: FnOnce(&mut DataStore) -> Result, { - // AbUpdateHealthCheckFailed and AbUpdateHypervisorCheckFailed are + // AbUpdateHealthCheckFailed and CommitFailed are // special cases where the last error must be preserved across failed // recovery attempts. This keeps the original health/hypervisor failure // visible instead of replacing it with a secondary recovery error. @@ -316,8 +316,7 @@ impl Trident { ); let last_error_to_preserve = if matches!( datastore.host_status().servicing_state, - ServicingState::AbUpdateHealthCheckFailed - | ServicingState::AbUpdateHypervisorCheckFailed + ServicingState::AbUpdateHealthCheckFailed | ServicingState::CommitFailed ) { datastore.host_status().last_error.clone() } else { @@ -822,7 +821,7 @@ impl Trident { datastore: &mut DataStore, ) -> Result<(ExitKind, ServicingType), TridentError> { // If the host's servicing state is *Finalized, AbUpdateHealthCheckFailed, - // or AbUpdateHypervisorCheckFailed, re-evaluate the current state of + // or CommitFailed, re-evaluate the current state of // the host to validate either the target boot or the recovery boot. let servicing_state = datastore.host_status().servicing_state; if !matches!( @@ -830,7 +829,7 @@ impl Trident { ServicingState::CleanInstallFinalized | ServicingState::AbUpdateFinalized | ServicingState::AbUpdateHealthCheckFailed - | ServicingState::AbUpdateHypervisorCheckFailed + | ServicingState::CommitFailed | ServicingState::ManualRollbackAbFinalized ) { info!( @@ -843,7 +842,7 @@ impl Trident { let servicing_type = match servicing_state { ServicingState::AbUpdateFinalized | ServicingState::AbUpdateHealthCheckFailed - | ServicingState::AbUpdateHypervisorCheckFailed => ServicingType::AbUpdate, + | ServicingState::CommitFailed => ServicingType::AbUpdate, ServicingState::CleanInstallFinalized => ServicingType::CleanInstall, ServicingState::ManualRollbackAbFinalized => ServicingType::ManualRollbackAb, _ => ServicingType::NoActiveServicing, diff --git a/crates/trident/src/server/tridentserver/datastore.rs b/crates/trident/src/server/tridentserver/datastore.rs index a5a1023f89..c2e0c8b877 100644 --- a/crates/trident/src/server/tridentserver/datastore.rs +++ b/crates/trident/src/server/tridentserver/datastore.rs @@ -50,9 +50,7 @@ mod preview { ServicingState::AbUpdateHealthCheckFailed => { ProtoServicingState::UpdateAbHealthCheckFailed } - ServicingState::AbUpdateHypervisorCheckFailed => { - ProtoServicingState::UpdateAbHypervisorCheckFailed - } + ServicingState::CommitFailed => ProtoServicingState::CommitFailed, } } @@ -116,8 +114,8 @@ mod preview { ProtoServicingState::UpdateAbHealthCheckFailed, ), ( - ServicingState::AbUpdateHypervisorCheckFailed, - ProtoServicingState::UpdateAbHypervisorCheckFailed, + ServicingState::CommitFailed, + ProtoServicingState::CommitFailed, ), ]; diff --git a/crates/trident_api/src/status.rs b/crates/trident_api/src/status.rs index 638a056697..2f4cb08e61 100644 --- a/crates/trident_api/src/status.rs +++ b/crates/trident_api/src/status.rs @@ -133,8 +133,9 @@ pub enum ServicingState { Provisioned, /// A/B update has been completed, the host booted into the target OS but the health checks failed. AbUpdateHealthCheckFailed, - /// The trial OS booted, but its hypervisor failed validation; recovery is pending. - AbUpdateHypervisorCheckFailed, + /// Commit failed and rollback to the retained OS is required. + #[serde(alias = "ab-update-hypervisor-check-failed")] + CommitFailed, } /// A/B volume selection. Determines which set of volumes are currently @@ -319,6 +320,25 @@ pub fn decode_host_status(mut yaml: Value) -> Result Date: Tue, 17 Nov 2026 01:46:26 +0000 Subject: [PATCH 46/82] Remove obsolete hypervisor failure state alias Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d7cd5420-e0f6-473c-ba87-89266961d637 --- crates/trident_api/src/status.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/trident_api/src/status.rs b/crates/trident_api/src/status.rs index 2f4cb08e61..6dbc216679 100644 --- a/crates/trident_api/src/status.rs +++ b/crates/trident_api/src/status.rs @@ -134,7 +134,6 @@ pub enum ServicingState { /// A/B update has been completed, the host booted into the target OS but the health checks failed. AbUpdateHealthCheckFailed, /// Commit failed and rollback to the retained OS is required. - #[serde(alias = "ab-update-hypervisor-check-failed")] CommitFailed, } @@ -321,15 +320,16 @@ mod tests { use super::*; #[test] - fn commit_failure_accepts_previous_name_without_merging_health_failure() { - for name in ["commit-failed", "ab-update-hypervisor-check-failed"] { - let state: ServicingState = serde_yaml::from_str(name).unwrap(); - assert_eq!(state, ServicingState::CommitFailed); - assert_eq!( - serde_yaml::to_string(&state).unwrap().trim(), - "commit-failed" - ); - } + fn commit_failure_roundtrips_without_previous_hypervisor_alias() { + let state: ServicingState = serde_yaml::from_str("commit-failed").unwrap(); + assert_eq!(state, ServicingState::CommitFailed); + assert_eq!( + serde_yaml::to_string(&state).unwrap().trim(), + "commit-failed" + ); + assert!( + serde_yaml::from_str::("ab-update-hypervisor-check-failed").is_err() + ); let health: ServicingState = serde_yaml::from_str("ab-update-health-check-failed").unwrap(); assert_eq!(health, ServicingState::AbUpdateHealthCheckFailed); From 7abbc1c46832bc28363bbc1089ffe000222ada24 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 05:29:16 +0000 Subject: [PATCH 47/82] Remove MSHV slot-staging capacity prediction Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d7cd5420-e0f6-473c-ba87-89266961d637 --- crates/trident/src/engine/boot/mshv.rs | 84 ++------------------------ crates/trident/src/subsystems/esp.rs | 13 +--- 2 files changed, 9 insertions(+), 88 deletions(-) diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index b831c55da0..29f15b21fe 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -8,15 +8,6 @@ use std::{ use anyhow::{ensure, Context, Error}; use nix::sys::statvfs; -use osutils::uki as uki_utils; - -use trident_api::{config::UefiFallbackMode, constants::EFI_DEFAULT_BIN_RELATIVE_PATH}; - -use crate::engine::{ - boot::uki::{self, UKI_DIRECTORY}, - EngineContext, -}; - // Required top-level x64 boot files; secondary payloads vary between images. pub(crate) const FILES: &[&str] = &[ "bootx64.efi", @@ -175,33 +166,6 @@ fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<(), Erro Ok(()) } -/// Budgets bundles, UKIs, addons, and fallback, crediting planned pre-staging cleanup. -pub(crate) fn preflight_staging( - ctx: &EngineContext, - source_esp: &Path, - destination_esp: &Path, - target_bundle: &Path, -) -> Result<(), Error> { - let stats = statvfs::statvfs(destination_esp)?; - let cluster = stats.fragment_size(); - ensure!(cluster > 0, "Invalid ESP allocation unit"); - let bundle = bundle_allocation(&source_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH), cluster)?; - let mut required = bundle + allocation(&source_esp.join(UKI_DIRECTORY), cluster)?; - // Account for slot-addon templates whose selected file may replace a smaller live addon. - required += allocation(&source_esp.join("acl/uki-addons"), cluster)?; - if ctx.spec.os.uefi_fallback != UefiFallbackMode::Disabled { - let existing_fallback = destination_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH); - required += bundle.max(bundle_allocation(&existing_fallback, cluster)?); - } - let mut reclaimed = allocation(target_bundle, cluster)?; - for path in uki::find_ukis_to_remove_before_staging(ctx, &destination_esp.join(UKI_DIRECTORY))? - { - reclaimed += - allocation(&path, cluster)? + allocation(&uki_utils::uki_addon_dir(&path), cluster)?; - } - check_space(stats.blocks_available() * cluster, reclaimed, required) -} - /// Checks room for a new bundle copy without reclaiming existing ESP contents. pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> { let stats = statvfs::statvfs(esp)?; @@ -311,9 +275,13 @@ mod tests { use tempfile::TempDir; - use trident_api::status::{AbVolumeSelection, ServicingState, ServicingType}; + use trident_api::{ + config::UefiFallbackMode, + constants::EFI_DEFAULT_BIN_RELATIVE_PATH, + status::{AbVolumeSelection, ServicingState, ServicingType}, + }; - use crate::subsystems::esp; + use crate::{engine::EngineContext, subsystems::esp}; /// Creates a complete test bundle. fn bundle(root: &Path, contents: &[u8]) { @@ -434,7 +402,6 @@ mod tests { 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/AZLB"); bundle(&source, b"new"); bundle(&fallback, b"retained"); let secondary = source.join("Windows/System32"); @@ -445,25 +412,15 @@ mod tests { .unwrap() .set_len(stats.blocks_available() * stats.fragment_size() + SPACE_RESERVE) .unwrap(); - let mut ctx = EngineContext { - servicing_type: ServicingType::AbUpdate, - ab_active_volume: Some(AbVolumeSelection::VolumeA), - ..Default::default() - }; - ctx.spec.os.uefi_fallback = UefiFallbackMode::Disabled; - - assert!(preflight_staging(&ctx, &source_esp, &esp, &target).is_err()); assert!(preflight_bootstrap(&source, &esp).is_err()); assert!(replace_bundle(&source, &fallback).is_err()); assert_eq!( fs::read(fallback.join("HvLoader.efi")).unwrap(), b"retained" ); - assert!(!target.exists()); fs::create_dir(secondary.join("ignored")).unwrap(); fs::rename(&large, secondary.join("ignored/large.bin")).unwrap(); - preflight_staging(&ctx, &source_esp, &esp, &target).unwrap(); preflight_bootstrap(&source, &esp).unwrap(); replace_bundle(&source, &fallback).unwrap(); assert_eq!(fs::read(fallback.join("HvLoader.efi")).unwrap(), b"new"); @@ -559,35 +516,6 @@ mod tests { assert!(check_space(SPACE_RESERVE, 4096, 4096).is_ok()); } - /// Failed preflight leaves both slots untouched. - #[test] - fn preflight_rejects_peak_allocation_before_mutating_inactive_or_retained_files() { - let temp = TempDir::new().unwrap(); - let source = temp.path().join("source"); - let destination = temp.path().join("esp"); - let target = destination.join("EFI/AZLB"); - let retained = destination.join("EFI/AZLA"); - bundle(&source.join(EFI_DEFAULT_BIN_RELATIVE_PATH), b"new"); - bundle(&target, b"inactive"); - bundle(&retained, b"committed"); - fs::create_dir_all(source.join(UKI_DIRECTORY)).unwrap(); - let stats = statvfs::statvfs(&destination).unwrap(); - File::create(source.join(UKI_DIRECTORY).join("new.efi")) - .unwrap() - .set_len(stats.blocks_available() * stats.fragment_size() + SPACE_RESERVE) - .unwrap(); - let ctx = EngineContext { - servicing_type: ServicingType::AbUpdate, - ab_active_volume: Some(AbVolumeSelection::VolumeA), - ..Default::default() - }; - assert!(preflight_staging(&ctx, &source, &destination, &target).is_err()); - for name in FILES { - assert_eq!(fs::read(target.join(name)).unwrap(), b"inactive"); - assert_eq!(fs::read(retained.join(name)).unwrap(), b"committed"); - } - } - /// Enabled fallback policies copy whole bundles and preserve the retained slot. #[test] fn fallback_modes_use_the_full_selected_bundle_during_trial_commit_and_rollback() { diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index f0b80f1b5f..f658507aa8 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -332,8 +332,7 @@ where /// /// Mounts the source ESP image, copies boot files into the selected target-slot /// directory, and stages the UKI when applicable. For MSHV, validates the bundle -/// and preflights capacity before reclaiming target-slot boot files and UKIs. -/// Retained-slot payloads are preserved. +/// before reclaiming target-slot boot files and UKIs. Retained-slot payloads are preserved. fn copy_file_artifacts( temp_image_path: &Path, ctx: &EngineContext, @@ -373,14 +372,8 @@ fn copy_file_artifacts( // Compare source metadata with the retained slot before any ESP writes. mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; let boot_files = if slot_mshv { - // Validate and budget space before deleting target-slot files. + // Validate the source before deleting target-slot files. boot_mshv::validate_bundle(&source_bundle)?; - boot_mshv::preflight_staging( - ctx, - temp_mount_dir, - &path::join_relative(mount_point, &ctx.esp_mount_path), - &esp_dir_path, - )?; uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; Vec::new() } else { @@ -431,7 +424,7 @@ fn copy_file_artifacts( uki::prepare_esp_for_uki(mount_point, &ctx.esp_mount_path)?; // Clean up old UKIs for the target slot before staging the new one. - // MSHV already did this after its capacity preflight; other UKI images + // MSHV already did this before copying its bundle; other UKI images // reclaim space here because the ESP may not fit old and new UKIs // simultaneously (e.g. on a 128 MB ESP). A crash between cleanup and // staging can remove the target slot's old UKI without a replacement, From a3403346b77c0ddbb05348332684a225acaca01d Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 05:37:56 +0000 Subject: [PATCH 48/82] Update cleanup documentation after preflight removal Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d7cd5420-e0f6-473c-ba87-89266961d637 --- crates/trident/src/engine/boot/uki.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index e297f3e13c..9440729025 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -248,7 +248,7 @@ pub fn cleanup_ukis_before_staging( Ok(()) } -/// Lists cleanup candidates without mutation, also used to budget reclaimable space. +/// Lists cleanup candidates without mutation. pub(crate) fn find_ukis_to_remove_before_staging( ctx: &EngineContext, esp_uki_directory: &Path, From f255519df9d74456f73ae5893ebdc69b0cfadaf1 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 05:48:01 +0000 Subject: [PATCH 49/82] Gate UKI staging cleanup independently of MSHV Validate source boot files before UKI-only cleanup, and reclaim space before copying either payload. Cover both bootloader/UKI predicates and invalid-source preservation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d7cd5420-e0f6-473c-ba87-89266961d637 --- crates/trident/src/subsystems/esp.rs | 178 +++++++++++++++++++++------ 1 file changed, 142 insertions(+), 36 deletions(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index f658507aa8..c9f91517a1 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -331,8 +331,8 @@ where /// 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. For MSHV, validates the bundle -/// before reclaiming target-slot boot files and UKIs. Retained-slot payloads are preserved. +/// directory, and stages the UKI when applicable. Source validation precedes +/// target-slot cleanup; UKI cleanup runs only for UKI images, before payload copying. fn copy_file_artifacts( temp_image_path: &Path, ctx: &EngineContext, @@ -369,27 +369,7 @@ fn copy_file_artifacts( // MSHV uses a complete bundle, not the ordinary boot-file list. let slot_mshv = ctx.bootloader().is_some_and(Bootloader::uses_mshv); let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); - // Compare source metadata with the retained slot before any ESP writes. - mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; - let boot_files = if slot_mshv { - // Validate the source before deleting target-slot files. - boot_mshv::validate_bundle(&source_bundle)?; - uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; - Vec::new() - } else { - // Ordinary copying would omit required MSHV payload files. - ensure!( - !source_bundle.join("HvLoader.efi").try_exists()?, - "An MSHV image must declare COSI bootloader type 'efitreeloader-mshv-systemd-boot'" - ); - // Generate the ordinary boot-file paths from the temporary directory - // where the source ESP image is mounted. - generate_boot_filepaths( - temp_mount_dir, - ctx.is_uki().unstructured("UKI setting unknown")?, - ) - .context("Failed to generate boot filepaths")? - }; + let boot_files = prepare_boot_files_for_staging(temp_mount_dir, ctx, mount_point)?; // Clear esp_dir_path if it exists if esp_dir_path.exists() { @@ -423,16 +403,6 @@ fn copy_file_artifacts( // 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. - // MSHV already did this before copying its bundle; other UKI images - // reclaim space here because the ESP may not fit old and new UKIs - // simultaneously (e.g. on a 128 MB ESP). A crash between cleanup and - // staging can remove the target slot's old UKI without a replacement, - // but the active slot's UKI is preserved, retaining a bootable rollback. - if !slot_mshv { - 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)?; @@ -481,6 +451,36 @@ fn copy_file_artifacts( Ok(()) } +/// Validates source boot files and prepares target UKIs before payload copies. +fn prepare_boot_files_for_staging( + temp_mount_dir: &Path, + ctx: &EngineContext, + mount_point: &Path, +) -> Result, Error> { + let is_uki = ctx.is_uki().unstructured("UKI setting unknown")?; + let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + // Compare source metadata with the retained slot before any ESP writes. + mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; + let boot_files = if ctx.bootloader().is_some_and(Bootloader::uses_mshv) { + boot_mshv::validate_bundle(&source_bundle)?; + Vec::new() + } else { + // Ordinary copying would omit required MSHV payload files. + ensure!( + !source_bundle.join("HvLoader.efi").try_exists()?, + "An MSHV image must declare COSI bootloader type 'efitreeloader-mshv-systemd-boot'" + ); + generate_boot_filepaths(temp_mount_dir, is_uki) + .context("Failed to generate boot filepaths")? + }; + if is_uki { + // Reclaim target-slot space before copying, preserving the active slot. + // A failed copy can leave the target without its previous UKI. + uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; + } + Ok(boot_files) +} + /// Determines the source directory to copy UEFI fallback boot files from. /// This varies based on the servicing state and UEFI fallback mode. /// @@ -1004,11 +1004,117 @@ mod tests { status::{AbVolumeSelection, ServicingType}, }; - use crate::engine::{ - boot::{get_update_esp_dir_name, make_esp_dir_name_candidates, mshv::FILES}, - install_index, + use crate::{ + engine::{ + boot::{get_update_esp_dir_name, make_esp_dir_name_candidates, mshv::FILES}, + install_index, + }, + osimage::bootloader::BootloaderType, }; + 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 { + 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(); + } + } + let ukis = esp.path().join(uki::UKI_DIRECTORY); + fs::create_dir_all(&ukis).unwrap(); + for name in ["vmlinuz-100-azla1.efi", "vmlinuz-100-azlb1.efi"] { + fs::write(ukis.join(name), b"kernel").unwrap(); + let addons = ukis.join(format!("{name}.extra.d")); + fs::create_dir(&addons).unwrap(); + fs::write(addons.join("payload.addon.efi"), b"addon").unwrap(); + } + (source, esp, ctx) + } + + #[test] + fn test_prepare_boot_files_for_staging_skips_cleanup_for_non_uki_images() { + // MSHV and UKI are independent predicates, despite current deployment restrictions. + for is_mshv in [false, true] { + let (source, esp, ctx) = boot_file_staging_fixture(is_mshv, false); + prepare_boot_files_for_staging(source.path(), &ctx, esp.path()).unwrap(); + let ukis = esp.path().join(uki::UKI_DIRECTORY); + for name in ["vmlinuz-100-azla1.efi", "vmlinuz-100-azlb1.efi"] { + assert_eq!(fs::read(ukis.join(name)).unwrap(), b"kernel"); + assert_eq!( + fs::read(ukis.join(format!("{name}.extra.d/payload.addon.efi"))).unwrap(), + b"addon" + ); + } + } + } + + #[test] + fn test_prepare_boot_files_for_staging_cleans_target_ukis_for_uki_images() { + for is_mshv in [false, true] { + let (source, esp, ctx) = boot_file_staging_fixture(is_mshv, true); + prepare_boot_files_for_staging(source.path(), &ctx, esp.path()).unwrap(); + let ukis = esp.path().join(uki::UKI_DIRECTORY); + assert!(!ukis.join("vmlinuz-100-azlb1.efi").exists()); + assert!(!ukis.join("vmlinuz-100-azlb1.efi.extra.d").exists()); + assert_eq!( + fs::read(ukis.join("vmlinuz-100-azla1.efi")).unwrap(), + b"kernel" + ); + assert_eq!( + fs::read(ukis.join("vmlinuz-100-azla1.efi.extra.d/payload.addon.efi")).unwrap(), + b"addon" + ); + } + } + + #[test] + fn test_prepare_boot_files_for_staging_validates_source_before_cleanup() { + let (source, esp, ctx) = boot_file_staging_fixture(true, true); + fs::remove_file( + source + .path() + .join(EFI_DEFAULT_BIN_RELATIVE_PATH) + .join("lxhvloader.dll"), + ) + .unwrap(); + assert!(prepare_boot_files_for_staging(source.path(), &ctx, esp.path()).is_err()); + let ukis = esp.path().join(uki::UKI_DIRECTORY); + for name in ["vmlinuz-100-azla1.efi", "vmlinuz-100-azlb1.efi"] { + assert_eq!(fs::read(ukis.join(name)).unwrap(), b"kernel"); + assert_eq!( + fs::read(ukis.join(format!("{name}.extra.d/payload.addon.efi"))).unwrap(), + b"addon" + ); + } + } + #[test] fn test_generate_efi_bin_base_dir_path_clean_install() { // Clean install EngineContext From dd3faf5e09e3d00059bd2de17b40b4a0d95a151c Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Mon, 16 Nov 2026 18:30:29 +0000 Subject: [PATCH 50/82] Ignore unrelated second-stage EFI files Keep second.efi handling in the metadata-selected MSHV bundle path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: cf4aff87-8d88-493e-b82b-256374bcaef8 --- crates/trident/src/subsystems/esp.rs | 62 ++++++----------------- crates/trident/src/subsystems/esp/mshv.rs | 3 -- 2 files changed, 16 insertions(+), 49 deletions(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index c9f91517a1..923159b83a 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -942,25 +942,6 @@ fn generate_boot_filepaths(temp_mount_dir: &Path, is_uki: bool) -> Result (TempDir, TempDir, EngineContext) { let source = TempDir::new().unwrap(); let esp = TempDir::new().unwrap(); @@ -1965,7 +1948,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 @@ -2005,7 +1988,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 @@ -2163,10 +2146,8 @@ 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_ignores_unrelated_second_stage() { for is_uki in [false, true] { for grub_filename in [GRUB_EFI, GRUB_NOPREFIX_EFI] { let source = TempDir::new().unwrap(); @@ -2178,55 +2159,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(), 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(); 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).unwrap(), + expected_paths, + "unrelated second-stage directory: is_uki={is_uki}, grub={grub_filename}" ); } } diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 3bdf330eba..3265d113a4 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -19,9 +19,6 @@ use crate::{ osimage::bootloader::Bootloader, }; -/// Filename of the second-stage EFI executable for efitreeloader (ETL). -pub(super) const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; - /// Enforces support restrictions for file-based deployment of MSHV images. pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { if ctx.is_stream_image || !ctx.bootloader().is_some_and(Bootloader::uses_mshv) { From 1f6840d43023151ebf3f21e309a2a8a0aa60a605 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Mon, 16 Nov 2026 21:54:12 +0000 Subject: [PATCH 51/82] Allow MSHV fallback over ordinary GRUB files Keep incoming bundles strict while recognizing ordinary fallback files and retry remnants during destination accounting and replacement. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d7cd5420-e0f6-473c-ba87-89266961d637 --- crates/trident/src/engine/boot/mshv.rs | 164 ++++++++++++++++++++++--- 1 file changed, 146 insertions(+), 18 deletions(-) diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 29f15b21fe..d53b10423d 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -8,6 +8,10 @@ use std::{ use anyhow::{ensure, Context, Error}; use nix::sys::statvfs; +use osutils::bootloaders::GRUB_NOPREFIX_EFI; + +use trident_api::constants::GRUB2_CONFIG_FILENAME; + // Required top-level x64 boot files; secondary payloads vary between images. pub(crate) const FILES: &[&str] = &[ "bootx64.efi", @@ -17,6 +21,15 @@ pub(crate) const FILES: &[&str] = &[ "lxhvloader.dll", ]; +const ORDINARY_FALLBACK_FILES: &[&str] = &[GRUB2_CONFIG_FILENAME, GRUB_NOPREFIX_EFI]; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum TreePolicy { + Source, + Staging, + ExistingFallback, +} + /// Optional bundle-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. @@ -38,9 +51,11 @@ pub(crate) fn has_slot_mshv_bundle(bundle: &Path) -> Result { Ok(false) } -/// Validates entries and discovers files without requiring completeness or following symlinks. -/// System32 subdirectories are ignored; `.new` and `.old` suffixes are reserved for staging. -fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result, Error> { +/// Discovers selected regular files without following symlinks or requiring completeness. +/// Existing fallback may also contain ordinary GRUB files; only sources reject staging suffixes. +/// System32 subdirectories are ignored. +fn validate_tree(root: &Path, directory: &Path, policy: TreePolicy) -> Result, Error> { + let temporary = policy != TreePolicy::Source; ensure!( fs::symlink_metadata(directory)?.is_dir(), "Invalid payload directory" @@ -67,7 +82,7 @@ fn validate_tree(root: &Path, directory: &Path, temporary: bool) -> Result Result Result Result, Error> { - let mut files = validate_tree(root, root, false)?; + let mut files = validate_tree(root, root, TreePolicy::Source)?; for name in FILES { ensure!( fs::symlink_metadata(root.join(name)) @@ -149,7 +172,7 @@ fn bundle_allocation(root: &Path, cluster: u64) -> Result { } let mut directories = BTreeSet::from([PathBuf::new()]); let mut total = 0; - for name in validate_tree(root, root, true)? { + for name in validate_tree(root, root, TreePolicy::Staging)? { total += allocation(&root.join(&name), cluster)?; directories.extend(Path::new(&name).ancestors().skip(1).map(Path::to_path_buf)); } @@ -190,7 +213,7 @@ pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<(), Error> { let files = bundle_files(from)?; fs::create_dir_all(to)?; - validate_tree(to, to, false)?; + validate_tree(to, to, TreePolicy::Source)?; for name in &files { let destination = to.join(name); fs::create_dir_all(destination.parent().context("Missing payload parent")?)?; @@ -206,7 +229,7 @@ pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<(), Error> { let files = bundle_files(from)?; let existing = match fs::symlink_metadata(to) { Ok(_) => { - let existing = validate_tree(to, to, true)?; + let existing = validate_tree(to, to, TreePolicy::ExistingFallback)?; ensure!( fs::canonicalize(from)? != fs::canonicalize(to)?, "Source and fallback directories must differ" @@ -273,6 +296,7 @@ mod tests { use std::{fs::File, os::unix::fs as unix_fs}; + use nix::{sys::stat::Mode, unistd}; use tempfile::TempDir; use trident_api::{ @@ -292,6 +316,110 @@ mod tests { } } + #[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"); + bundle(&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_bundle(&source, &target).unwrap(); + for _ in 0..2 { + esp::set_uefi_fallback_contents(&ctx, ServicingState::CleanInstallStaged, &esp) + .unwrap(); + } + validate_bundle(&fallback).unwrap(); + for name in 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 !FILES.iter().any(|name| entry.file_name() == *name) { + assert!(!fallback.join(entry.file_name()).exists()); + } + } + } + } + + #[test] + fn rejects_ordinary_fallback_files_in_incoming_mshv_bundles() { + for name in [ + "grub.cfg", + "grub.cfg.new", + "grub.cfg.old", + "grubx64-noprefix.efi", + "grubx64-noprefix.efi.new", + "grubx64-noprefix.efi.old", + ] { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let fallback = temp.path().join("fallback"); + let target = temp.path().join("target"); + bundle(&source, b"mshv"); + bundle(&fallback, b"retained"); + fs::write(source.join(name), b"ordinary").unwrap(); + validate_bundle(&source).unwrap_err(); + copy_bundle(&source, &target).unwrap_err(); + replace_bundle(&source, &fallback).unwrap_err(); + assert!(!target.exists()); + assert_eq!(fs::read(fallback.join("bootx64.efi")).unwrap(), b"retained"); + } + } + + #[test] + fn rejects_unsafe_ordinary_fallback_entries_before_mutation() { + for kind in ["symlink", "fifo", "directory", "unknown"] { + 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"); + bundle(&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(), + "directory" => fs::create_dir(ordinary).unwrap(), + "unknown" => fs::write(fallback.join("unowned.bin"), b"unowned").unwrap(), + _ => unreachable!(), + } + replace_bundle(&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_complete_bundle_without_touching_other_slots() { @@ -436,14 +564,14 @@ mod tests { fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path, b"payload").unwrap(); } - validate_tree(temp.path(), temp.path(), false).unwrap(); + validate_tree(temp.path(), temp.path(), TreePolicy::Source).unwrap(); let pending = temp.path().join("SECOND.EFI.NEW"); fs::write(&pending, b"pending").unwrap(); - assert!(validate_tree(temp.path(), temp.path(), false).is_err()); - validate_tree(temp.path(), temp.path(), true).unwrap(); + assert!(validate_tree(temp.path(), temp.path(), TreePolicy::Source).is_err()); + validate_tree(temp.path(), temp.path(), TreePolicy::Staging).unwrap(); fs::remove_file(pending).unwrap(); fs::write(temp.path().join("IDENTITY.JSON"), b"unexpected").unwrap(); - assert!(validate_tree(temp.path(), temp.path(), true).is_err()); + assert!(validate_tree(temp.path(), temp.path(), TreePolicy::Staging).is_err()); } /// Invalid sources fail before destination creation. From 8c56b2c5f7ad926043ecf2882db43fca376f4f05 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 16:28:12 +0000 Subject: [PATCH 52/82] Use MSHV boot component terminology Distinguish MSHV boot components from supporting slot boot files. Update private helpers, diagnostics, tests, and current documentation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/engine/boot/mshv.rs | 202 ++++++++++--------- crates/trident/src/engine/mshv.rs | 2 +- crates/trident/src/init/acl/mod.rs | 24 +-- crates/trident/src/init/offline/mod.rs | 2 +- crates/trident/src/subsystems/esp.rs | 40 ++-- crates/trident/src/subsystems/esp/mshv.rs | 4 +- docs/Explanation/Bootloader-Configuration.md | 2 +- docs/Explanation/MSHV.md | 88 ++++---- 8 files changed, 193 insertions(+), 171 deletions(-) diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index d53b10423d..4ddf4a5d3b 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -12,7 +12,7 @@ use osutils::bootloaders::GRUB_NOPREFIX_EFI; use trident_api::constants::GRUB2_CONFIG_FILENAME; -// Required top-level x64 boot files; secondary payloads vary between images. +// Required top-level x64 boot files; secondary MSHV boot components vary between images. pub(crate) const FILES: &[&str] = &[ "bootx64.efi", "grubx64.efi", @@ -30,22 +30,22 @@ enum TreePolicy { ExistingFallback, } -/// Optional bundle-relative directory containing secondary MSHV payload binaries. +/// Optional directory of secondary MSHV boot components, relative to the boot directory. /// 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 = "Windows/System32"; +const MSHV_BOOT_COMPONENTS_DIR: &str = "Windows/System32"; const SPACE_RESERVE: u64 = 1024 * 1024; -/// Detects MSHV in an installed bootloader directory; marked bundles must be complete. -pub(crate) fn has_slot_mshv_bundle(bundle: &Path) -> Result { +/// Detects MSHV boot components and validates all required slot boot files. +pub(crate) fn has_slot_mshv_boot_components(boot_dir: &Path) -> Result { for marker in ["HvLoader.efi", "lxhvloader.dll", "Windows"] { - match fs::symlink_metadata(bundle.join(marker)) { + match fs::symlink_metadata(boot_dir.join(marker)) { Ok(_) => { - validate_bundle(bundle)?; + validate_boot_files(boot_dir)?; return Ok(true); } Err(error) if error.kind() == ErrorKind::NotFound => {} - Err(error) => return Err(error).context("Failed to inspect MSHV boot payload"), + Err(error) => return Err(error).context("Failed to inspect MSHV boot components"), } } Ok(false) @@ -58,19 +58,21 @@ fn validate_tree(root: &Path, directory: &Path, policy: TreePolicy) -> Result Result Result Result Result, Error> { +/// Discovers MSHV boot components and supporting boot files using FAT case-insensitive lookups. +fn boot_files(root: &Path) -> Result, Error> { let mut files = validate_tree(root, root, TreePolicy::Source)?; for name in FILES { ensure!( fs::symlink_metadata(root.join(name)) - .with_context(|| format!("Missing MSHV payload file: {name}"))? + .with_context(|| format!("Missing MSHV boot component: {name}"))? .is_file(), - "Invalid MSHV payload file: {name}" + "Invalid MSHV boot component: {name}" ); } files.sort(); Ok(files) } -/// Requires the top-level boot files; optional System32 payloads are discovered. +/// Requires the top-level boot files and discovers optional System32 MSHV boot components. /// Does not validate executable contents or hypervisor identity. -pub(crate) fn validate_bundle(root: &Path) -> Result<(), Error> { - bundle_files(root)?; +pub(crate) fn validate_boot_files(root: &Path) -> Result<(), Error> { + boot_files(root)?; Ok(()) } @@ -163,8 +165,8 @@ fn allocation(path: &Path, cluster: u64) -> Result { Ok(total) } -/// Budgets selected bundle files and their parents, excluding ignored subdirectories. -fn bundle_allocation(root: &Path, cluster: u64) -> Result { +/// Budgets selected boot files and their parents, excluding ignored subdirectories. +fn boot_file_allocation(root: &Path, cluster: u64) -> Result { match fs::symlink_metadata(root) { Ok(_) => {} Err(error) if error.kind() == ErrorKind::NotFound => return Ok(0), @@ -189,7 +191,7 @@ fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<(), Erro Ok(()) } -/// Checks room for a new bundle copy without reclaiming existing ESP contents. +/// Checks room for a new copy of slot boot files without reclaiming ESP contents. pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> { let stats = statvfs::statvfs(esp)?; let cluster = stats.fragment_size(); @@ -197,36 +199,40 @@ pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> check_space( stats.blocks_available() * cluster, 0, - bundle_allocation(from, cluster)?, + boot_file_allocation(from, cluster)?, ) } /// Copies the required top-level boot files listed in `FILES` and any direct -/// secondary MSHV payload files from the optional `MSHV_ESP_PAYLOAD_DIR`, -/// preserving bundle-relative paths. Subdirectories are ignored, and an absent +/// secondary MSHV boot components from the optional `MSHV_BOOT_COMPONENTS_DIR`, +/// preserving boot-directory-relative paths. Subdirectories are ignored, and an absent /// secondary directory is allowed. /// -/// Validates and discovers the source payload before writing, so missing -/// required files or traversal errors do not leave a partially copied payload. +/// Validates and discovers source boot files before writing, so missing +/// required files or traversal errors do not leave partially copied boot files. /// Copying itself is non-atomic and can leave partial output on an I/O failure. /// For atomic publication, copy to a temporary directory and rename it. -pub(crate) fn copy_bundle(from: &Path, to: &Path) -> Result<(), Error> { - let files = bundle_files(from)?; +pub(crate) fn copy_boot_files(from: &Path, to: &Path) -> Result<(), Error> { + let files = boot_files(from)?; fs::create_dir_all(to)?; validate_tree(to, to, TreePolicy::Source)?; for name in &files { let destination = to.join(name); - fs::create_dir_all(destination.parent().context("Missing payload parent")?)?; + fs::create_dir_all( + destination + .parent() + .context("Missing boot component parent")?, + )?; fs::copy(from.join(name), destination)?; } Ok(()) } /// Reconciles `.old` backups and stages all `.new` files before replacing fallback. -/// Removes retired secondary payload files after publishing the selected bundle. -/// Whole-bundle replacement is not atomic. -pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<(), Error> { - let files = bundle_files(from)?; +/// Removes retired secondary MSHV boot components after publishing the selected boot files. +/// Replacing the complete set of boot files is not atomic. +pub(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { + let files = boot_files(from)?; let existing = match fs::symlink_metadata(to) { Ok(_) => { let existing = validate_tree(to, to, TreePolicy::ExistingFallback)?; @@ -242,7 +248,7 @@ pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<(), Error> { let stats = statvfs::statvfs(to.parent().context("Missing fallback parent")?)?; let cluster = stats.fragment_size(); ensure!(cluster > 0, "Invalid ESP allocation unit"); - let required = bundle_allocation(from, cluster)?; + let required = boot_file_allocation(from, cluster)?; let mut reclaimed = 0; for name in &files { reclaimed += allocation(&to.join(format!("{name}.new")), cluster)?; @@ -251,7 +257,11 @@ pub(crate) fn replace_bundle(from: &Path, to: &Path) -> Result<(), Error> { for name in &files { let destination = to.join(name); let previous = to.join(format!("{name}.old")); - fs::create_dir_all(destination.parent().context("Missing payload parent")?)?; + fs::create_dir_all( + destination + .parent() + .context("Missing boot component parent")?, + )?; if previous.exists() { if destination.exists() { fs::remove_file(&previous)?; @@ -307,8 +317,8 @@ mod tests { use crate::{engine::EngineContext, subsystems::esp}; - /// Creates a complete test bundle. - fn bundle(root: &Path, contents: &[u8]) { + /// Creates all required slot boot files for tests. + fn create_boot_files(root: &Path, contents: &[u8]) { for name in FILES { let path = root.join(name); fs::create_dir_all(path.parent().unwrap()).unwrap(); @@ -326,7 +336,7 @@ mod tests { let fallback = esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH); let target = esp.join("EFI/AZLA"); let retained = esp.join("EFI/AZL2A"); - bundle(&source, b"mshv"); + create_boot_files(&source, b"mshv"); fs::create_dir_all(&fallback).unwrap(); fs::create_dir_all(&retained).unwrap(); for root in [&fallback, &retained] { @@ -349,12 +359,12 @@ mod tests { ..Default::default() }; ctx.spec.os.uefi_fallback = mode; - copy_bundle(&source, &target).unwrap(); + copy_boot_files(&source, &target).unwrap(); for _ in 0..2 { esp::set_uefi_fallback_contents(&ctx, ServicingState::CleanInstallStaged, &esp) .unwrap(); } - validate_bundle(&fallback).unwrap(); + validate_boot_files(&fallback).unwrap(); for name in FILES { assert_eq!(fs::read(fallback.join(name)).unwrap(), b"mshv"); } @@ -369,7 +379,7 @@ mod tests { } #[test] - fn rejects_ordinary_fallback_files_in_incoming_mshv_bundles() { + fn rejects_ordinary_fallback_files_in_incoming_mshv_source() { for name in [ "grub.cfg", "grub.cfg.new", @@ -382,12 +392,12 @@ mod tests { let source = temp.path().join("source"); let fallback = temp.path().join("fallback"); let target = temp.path().join("target"); - bundle(&source, b"mshv"); - bundle(&fallback, b"retained"); + create_boot_files(&source, b"mshv"); + create_boot_files(&fallback, b"retained"); fs::write(source.join(name), b"ordinary").unwrap(); - validate_bundle(&source).unwrap_err(); - copy_bundle(&source, &target).unwrap_err(); - replace_bundle(&source, &fallback).unwrap_err(); + validate_boot_files(&source).unwrap_err(); + copy_boot_files(&source, &target).unwrap_err(); + replace_boot_files(&source, &fallback).unwrap_err(); assert!(!target.exists()); assert_eq!(fs::read(fallback.join("bootx64.efi")).unwrap(), b"retained"); } @@ -402,7 +412,7 @@ mod tests { let esp = temp.path().join("esp"); let fallback = esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH); let outside = temp.path().join("outside"); - bundle(&source, b"mshv"); + 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(); @@ -414,7 +424,7 @@ mod tests { "unknown" => fs::write(fallback.join("unowned.bin"), b"unowned").unwrap(), _ => unreachable!(), } - replace_bundle(&source, &fallback).unwrap_err(); + replace_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"); } @@ -422,14 +432,14 @@ mod tests { /// Candidate copying preserves the retained slot. #[test] - fn copies_complete_bundle_without_touching_other_slots() { + 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"); - bundle(&source, b"new"); - bundle(&active, b"retained"); - copy_bundle(&source, &target).unwrap(); + create_boot_files(&source, b"new"); + create_boot_files(&active, b"retained"); + copy_boot_files(&source, &target).unwrap(); for name in FILES { assert_eq!(fs::read(target.join(name)).unwrap(), b"new"); assert_eq!(fs::read(active.join(name)).unwrap(), b"retained"); @@ -437,52 +447,52 @@ mod tests { } #[test] - fn discovers_optional_secondary_payload_without_recursing() { + fn discovers_optional_boot_components_without_recursing() { let temp = TempDir::new().unwrap(); let source = temp.path().join("source"); let target = temp.path().join("target"); let secondary = source.join("Windows/System32"); - bundle(&source, b"new"); + 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_bundle(&source, &target).unwrap(); + copy_boot_files(&source, &target).unwrap(); assert_eq!( fs::read(target.join("Windows/System32/image-specific.bin")).unwrap(), b"\0\xffpayload" ); assert!(!target.join("Windows/System32/drivers").exists()); - assert!(has_slot_mshv_bundle(&target).unwrap()); + assert!(has_slot_mshv_boot_components(&target).unwrap()); fs::remove_dir_all(source.join("Windows")).unwrap(); let without_secondary = temp.path().join("without-secondary"); - copy_bundle(&source, &without_secondary).unwrap(); + copy_boot_files(&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_bundle(&source, &empty_secondary).unwrap(); + copy_boot_files(&source, &empty_secondary).unwrap(); assert!(!empty_secondary.join("Windows").exists()); for name in ["payload.dll.new", "payload.dll.old"] { let path = secondary.join(name); fs::write(&path, b"reserved temporary name").unwrap(); - assert!(validate_bundle(&source).is_err()); + assert!(validate_boot_files(&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_bundle(&source, &rejected).is_err()); + assert!(copy_boot_files(&source, &rejected).is_err()); assert!(!rejected.exists()); } #[test] - fn replaces_changing_secondary_payload_and_recovers_partial_publication() { + 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"); - bundle(&source, b"new"); - bundle(&fallback, b"old"); + 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(); @@ -501,8 +511,8 @@ mod tests { fs::write(fallback.join(secondary).join(name), b"obsolete").unwrap(); } - replace_bundle(&source, &fallback).unwrap(); - replace_bundle(&source, &fallback).unwrap(); + replace_boot_files(&source, &fallback).unwrap(); + replace_boot_files(&source, &fallback).unwrap(); assert_eq!( fs::read(fallback.join(secondary).join("current.dll")).unwrap(), b"current" @@ -518,20 +528,20 @@ mod tests { } fs::remove_dir_all(source.join("Windows")).unwrap(); - replace_bundle(&source, &fallback).unwrap(); + replace_boot_files(&source, &fallback).unwrap(); assert!(!fallback.join(secondary).join("current.dll").exists()); - validate_bundle(&fallback).unwrap(); + validate_boot_files(&fallback).unwrap(); } #[test] - fn budgets_discovered_secondary_payload_but_not_ignored_subdirectories() { + fn budgets_discovered_boot_components_but_not_ignored_subdirectories() { 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); - bundle(&source, b"new"); - bundle(&fallback, b"retained"); + create_boot_files(&source, b"new"); + create_boot_files(&fallback, b"retained"); let secondary = source.join("Windows/System32"); fs::create_dir_all(&secondary).unwrap(); let large = secondary.join("image-specific.bin"); @@ -541,7 +551,7 @@ mod tests { .set_len(stats.blocks_available() * stats.fragment_size() + SPACE_RESERVE) .unwrap(); assert!(preflight_bootstrap(&source, &esp).is_err()); - assert!(replace_bundle(&source, &fallback).is_err()); + assert!(replace_boot_files(&source, &fallback).is_err()); assert_eq!( fs::read(fallback.join("HvLoader.efi")).unwrap(), b"retained" @@ -550,7 +560,7 @@ mod tests { fs::create_dir(secondary.join("ignored")).unwrap(); fs::rename(&large, secondary.join("ignored/large.bin")).unwrap(); preflight_bootstrap(&source, &esp).unwrap(); - replace_bundle(&source, &fallback).unwrap(); + replace_boot_files(&source, &fallback).unwrap(); assert_eq!(fs::read(fallback.join("HvLoader.efi")).unwrap(), b"new"); assert!(!fallback.join("Windows/System32/ignored").exists()); } @@ -576,17 +586,17 @@ mod tests { /// Invalid sources fail before destination creation. #[test] - fn rejects_incomplete_and_unexpected_payload_before_copy() { + fn rejects_incomplete_and_unexpected_boot_components_before_copy() { let temp = TempDir::new().unwrap(); let source = temp.path().join("source"); let target = temp.path().join("target"); - bundle(&source, b"new"); + create_boot_files(&source, b"new"); fs::remove_file(source.join("lxhvloader.dll")).unwrap(); - assert!(copy_bundle(&source, &target).is_err()); + assert!(copy_boot_files(&source, &target).is_err()); assert!(!target.exists()); - bundle(&source, b"new"); + create_boot_files(&source, b"new"); fs::write(source.join("identity.json"), b"unexpected").unwrap(); - assert!(copy_bundle(&source, &target).is_err()); + assert!(copy_boot_files(&source, &target).is_err()); assert!(!target.exists()); } @@ -597,14 +607,14 @@ mod tests { let source = temp.path().join("source"); let target = temp.path().join("target"); let outside = temp.path().join("outside"); - bundle(&source, b"new"); + create_boot_files(&source, b"new"); fs::create_dir(&outside).unwrap(); unix_fs::symlink(&outside, &target).unwrap(); - assert!(replace_bundle(&source, &target).is_err()); + assert!(replace_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_bundle(&source, &target).is_err()); + assert!(copy_boot_files(&source, &target).is_err()); assert!(fs::read_dir(&outside).unwrap().next().is_none()); } @@ -614,8 +624,8 @@ mod tests { let temp = TempDir::new().unwrap(); let source = temp.path().join("AZLB"); let fallback = temp.path().join("BOOT"); - bundle(&source, b"new"); - bundle(&fallback, b"old"); + create_boot_files(&source, b"new"); + create_boot_files(&fallback, b"old"); fs::rename( fallback.join("HvLoader.efi"), fallback.join("HvLoader.efi.old"), @@ -623,15 +633,15 @@ mod tests { .unwrap(); fs::write(fallback.join("second.efi.new"), b"partial").unwrap(); fs::write(fallback.join("lxhvloader.dll.old"), b"stale").unwrap(); - replace_bundle(&source, &fallback).unwrap(); - replace_bundle(&source, &fallback).unwrap(); - validate_bundle(&fallback).unwrap(); + replace_boot_files(&source, &fallback).unwrap(); + replace_boot_files(&source, &fallback).unwrap(); + validate_boot_files(&fallback).unwrap(); for name in 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_bundle(&source, &source).is_err()); + assert!(replace_boot_files(&source, &source).is_err()); } /// Capacity includes cluster rounding, reclamation, and a reserve. @@ -644,9 +654,9 @@ mod tests { assert!(check_space(SPACE_RESERVE, 4096, 4096).is_ok()); } - /// Enabled fallback policies copy whole bundles and preserve the retained slot. + /// Enabled fallback policies copy all slot boot files and preserve the retained slot. #[test] - fn fallback_modes_use_the_full_selected_bundle_during_trial_commit_and_rollback() { + fn fallback_modes_use_selected_boot_files_during_trial_commit_and_rollback() { for mode in [ UefiFallbackMode::Conservative, UefiFallbackMode::Optimistic, @@ -657,9 +667,9 @@ mod tests { let active = efi.join("AZL2A"); let target = efi.join("AZL2B"); let fallback = efi.join("BOOT"); - bundle(&active, b"retained"); - bundle(&target, b"candidate"); - bundle(&fallback, b"retained"); + 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()), diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index 0e24349311..bdc9b65183 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -38,7 +38,7 @@ fn validate_hypervisor_identity( let expected_directory = expected_volume .map(|volume| boot::make_esp_dir_name(install_index, volume)) .unwrap_or_else(|| EFI_DEFAULT_BIN_DIRECTORY.into()); - // TODO: Identify the running hypervisor and compare it with the expected OS payload. + // TODO: Identify the running hypervisor and compare it with the expected OS's MSHV boot components. warn!( "MSHV hypervisor identity validation is not implemented; assuming success for {:?}", expected_directory diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index c601e6b588..bc1e7e3048 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -62,7 +62,7 @@ impl<'a> ExpectedPartition<'a> { /// the expectations of the ACL image layout, and returns a HostStatus /// representing the current state of the host. This will be used to /// initialize the Trident datastore if it has not been created yet. -/// Validates any detected MSHV bundle without modifying the ESP. +/// Validates any detected MSHV boot components without modifying the ESP. pub fn initial_host_status() -> Result { let blk_devices = lsblk::list().context("Failed to run lsblk")?; let root_blk_device = blk_devices @@ -89,7 +89,7 @@ pub fn initial_host_status() -> Result { /// initial ACL HostStatus, separated from the code that gets the /// Host's current disk information. This allows for easier testing /// of the HostStatus creation logic. -/// Rejects incomplete MSHV bundles without modifying the ESP. +/// Rejects incomplete MSHV boot components without modifying the ESP. fn inner_initial_host_status( disk_information: &SfDisk, root_blk_device: &BlockDevice, @@ -306,7 +306,7 @@ fn inner_initial_host_status( partition_paths, ..Default::default() }; - mshv::has_slot_mshv_bundle(&esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH))?; + mshv::has_slot_mshv_boot_components(&esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH))?; Ok(host_status) } @@ -480,8 +480,8 @@ mod tests { } } - /// Creates a complete BOOT bundle for discovery tests. - fn create_mshv_bundle(esp_path: &Path) { + /// Creates complete BOOT files with MSHV boot components for discovery tests. + fn create_mshv_boot_files(esp_path: &Path) { for name in FILES { let path = esp_path.join("EFI/BOOT").join(name); fs::create_dir_all(path.parent().unwrap()).unwrap(); @@ -507,17 +507,17 @@ mod tests { let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); assert_eq!(status.spec, ordinary.spec); - create_mshv_bundle(esp.path()); + create_mshv_boot_files(esp.path()); let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); assert_eq!(status.spec, ordinary.spec); assert!(!esp.path().join("EFI/AZLA").exists()); } - /// Incomplete marked bundles fail discovery without creating AZLA. + /// Incomplete MSHV boot components fail discovery without creating AZLA. #[test] - fn initial_host_status_rejects_incomplete_slot_mshv_payload() { + fn initial_host_status_rejects_incomplete_slot_mshv_boot_components() { let esp = TempDir::new().unwrap(); - create_mshv_bundle(esp.path()); + create_mshv_boot_files(esp.path()); fs::remove_file(esp.path().join("EFI/BOOT/HvLoader.efi")).unwrap(); let error = inner_initial_host_status( &create_sfdisk("EFI-SYSTEM", TestPartitions::Correct), @@ -527,7 +527,7 @@ mod tests { .unwrap_err(); assert!(error .to_string() - .contains("Missing MSHV payload file: HvLoader.efi")); + .contains("Missing MSHV boot component: HvLoader.efi")); assert!(!esp.path().join("EFI/AZLA").exists()); } @@ -542,7 +542,7 @@ mod tests { } } - /// Ordinary ACL discovery needs no MSHV payload. + /// Ordinary ACL discovery needs no MSHV boot components. #[test] fn test_inner_initial_host_status_success() { let sfdisk = create_sfdisk("efi-system", TestPartitions::Correct); @@ -664,7 +664,7 @@ mod tests { assert!(volume_pairs.iter().all(|p| p.id != "usr-hash-sig")); } - /// Unexpected ESP labels fail before payload discovery. + /// Unexpected ESP labels fail before MSHV boot component discovery. #[test] fn test_inner_initial_host_status_unexpected_part_name() { let wrong_label = "wrong-label"; diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index bb6ddacb33..ac166b237d 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -457,7 +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 from the installed fallback, validating any detected MSHV bundle. +/// Seeds a missing AZLA from the installed fallback, validating any detected MSHV boot components. pub fn execute( hs_path: Option<&Path>, lazy_partitions: &[String], diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 923159b83a..aaa183c793 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -85,7 +85,7 @@ impl Subsystem for EspSubsystem { /// 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 the complete nested bundle. +/// 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, @@ -332,7 +332,7 @@ where /// /// 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 payload copying. +/// target-slot cleanup; UKI cleanup runs only for UKI images, before boot-file copying. fn copy_file_artifacts( temp_image_path: &Path, ctx: &EngineContext, @@ -366,9 +366,9 @@ 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()); - // MSHV uses a complete bundle, not the ordinary boot-file list. + // MSHV boot components require additional files beyond the ordinary boot-file list. let slot_mshv = ctx.bootloader().is_some_and(Bootloader::uses_mshv); - let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let source_boot_dir = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); let boot_files = prepare_boot_files_for_staging(temp_mount_dir, ctx, mount_point)?; // Clear esp_dir_path if it exists @@ -389,7 +389,7 @@ fn copy_file_artifacts( // Call helper func to copy boot files from temp_mount_dir to esp_dir_path let grub_noprefix = if slot_mshv { - boot_mshv::copy_bundle(&source_bundle, &esp_dir_path)?; + boot_mshv::copy_boot_files(&source_boot_dir, &esp_dir_path)?; false } else { copy_boot_files(temp_mount_dir, &esp_dir_path, boot_files).context(format!( @@ -451,23 +451,23 @@ fn copy_file_artifacts( Ok(()) } -/// Validates source boot files and prepares target UKIs before payload copies. +/// Validates source boot files and prepares target UKIs before boot-file copies. fn prepare_boot_files_for_staging( temp_mount_dir: &Path, ctx: &EngineContext, mount_point: &Path, ) -> Result, Error> { let is_uki = ctx.is_uki().unstructured("UKI setting unknown")?; - let source_bundle = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let source_boot_dir = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); // Compare source metadata with the retained slot before any ESP writes. mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; let boot_files = if ctx.bootloader().is_some_and(Bootloader::uses_mshv) { - boot_mshv::validate_bundle(&source_bundle)?; + boot_mshv::validate_boot_files(&source_boot_dir)?; Vec::new() } else { - // Ordinary copying would omit required MSHV payload files. + // Ordinary copying would omit required MSHV boot components. ensure!( - !source_bundle.join("HvLoader.efi").try_exists()?, + !source_boot_dir.join("HvLoader.efi").try_exists()?, "An MSHV image must declare COSI bootloader type 'efitreeloader-mshv-systemd-boot'" ); generate_boot_filepaths(temp_mount_dir, is_uki) @@ -591,7 +591,7 @@ fn skip_uefi_fallback_copy( /// Copies boot files from the `source_esp_name` folder to the UEFI fallback /// folder, `EFI/BOOT`. /// -/// Copies the complete nested bundle for MSHV, or top-level files for ordinary +/// 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( @@ -623,9 +623,9 @@ fn copy_boot_files_for_uefi_fallback( source_esp_dir_path.display(), uefi_fallback_path.display() ); - // Fallback also runs without an image, so detect the selected slot's bundle. - let result = if boot_mshv::has_slot_mshv_bundle(&source_esp_dir_path)? { - boot_mshv::replace_bundle(&source_esp_dir_path, &uefi_fallback_path) + // Fallback also runs without an image, so detect the selected slot's MSHV boot components. + let result = if boot_mshv::has_slot_mshv_boot_components(&source_esp_dir_path)? { + boot_mshv::replace_boot_files(&source_esp_dir_path, &uefi_fallback_path) } else { replace_boot_files(&source_esp_dir_path, &uefi_fallback_path) }; @@ -722,7 +722,7 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { }) .context("Failed to rename copied files")?; - // Remove retired files and the known MSHV payload directory. + // Remove retired files and the known MSHV boot component directory. fs::read_dir(to_dir)? .collect::, _>>()? .iter() @@ -759,15 +759,15 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { /// 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. /// -/// Detects MSHV from BOOT, preflights capacity for its bundle, and publishes a +/// Detects MSHV boot components in BOOT, preflights boot-file capacity, and publishes a /// complete copy via a staged directory rename. Existing AZLA is never refreshed: /// it is validated when BOOT contains MSHV, or left untouched for ordinary BOOT. 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); - let slot_mshv = boot_mshv::has_slot_mshv_bundle(&boot_esp_path)?; + let slot_mshv = boot_mshv::has_slot_mshv_boot_components(&boot_esp_path)?; if slot_mshv && azla_esp_path.exists() { - return boot_mshv::validate_bundle(&azla_esp_path); + return boot_mshv::validate_boot_files(&azla_esp_path); } trace!("Checking for AZLA volume ESP path at {:?}", &azla_esp_path); if !azla_esp_path.exists() { @@ -780,7 +780,7 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { // AZLA directly before the copy completes could leave a partially // populated directory on failure. Ordinary-mode retries would skip // that directory because it exists, while MSHV retries would reject - // its incomplete bundle rather than repair it. + // its incomplete MSHV boot components rather than repair them. 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!( @@ -791,7 +791,7 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { let copy_result = if slot_mshv { // Check capacity after reclaiming stale staging contents. boot_mshv::preflight_bootstrap(&boot_esp_path, esp_path)?; - boot_mshv::copy_bundle(&boot_esp_path, &azla_tmp_path) + boot_mshv::copy_boot_files(&boot_esp_path, &azla_tmp_path) } else { replace_boot_files(&boot_esp_path, &azla_tmp_path) }; diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 3265d113a4..b91019ea12 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -52,11 +52,11 @@ pub(super) fn validate_transition(ctx: &EngineContext, esp_path: &Path) -> Resul let active_volume = ctx .ab_active_volume .context("A/B active volume is not set")?; - let active_bundle = esp_path + 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_bundle(&active_bundle)? + 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" ); diff --git a/docs/Explanation/Bootloader-Configuration.md b/docs/Explanation/Bootloader-Configuration.md index 2c77c56d9e..9413572589 100644 --- a/docs/Explanation/Bootloader-Configuration.md +++ b/docs/Explanation/Bootloader-Configuration.md @@ -49,7 +49,7 @@ 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 payload layout, and servicing requirements. +slot-owned MSHV boot component layout, and servicing requirements. :::note Trident handles bootloader servicing for A/B updates without any required user diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index 8de995dc23..1dc8539705 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -2,9 +2,9 @@ Azure Container Linux (ACL) images with MSHV support boot Linux as the root partition of the Microsoft hypervisor. Servicing these images requires keeping -the hypervisor's boot payload together with the OS version that uses it. +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 -that payload alongside each OS slot. +those components alongside each OS slot. ## How MSHV Boot Differs @@ -17,32 +17,40 @@ components before systemd-boot: UEFI -> shim (bootx64.efi) -> efitreeloader (grubx64.efi) - -> HvLoader.efi -> lxhvloader.dll -> hypervisor payload preparation + -> HvLoader.efi -> lxhvloader.dll -> hypervisor preparation -> systemd-boot (second.efi) -> selected UKI -> Linux with MSHV support ``` -Despite its filename, `grubx64.efi` in this bundle is efitreeloader, not GRUB. +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 hypervisor components outside the slot +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 payload used by the retained OS. +also change the MSHV boot components used by the retained OS. -Slot-owned servicing instead keeps the complete boot payload in each slot -directory. The matching efitreeloader prefix resolver locates its dependencies -relative to the directory from which it runs. The same bundle can consequently -run from a managed slot or from the UEFI fallback directory without referring -to another slot's hypervisor files. +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. -## Payload Layout +## Boot Component Layout -The source COSI must contain this complete bundle. Paths below are relative -to the EFI System Partition (ESP), independent of its Linux mount point. +The MSHV boot components are `HvLoader.efi`, `lxhvloader.dll`, and any +hypervisor or support binaries under `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/System32` 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/ @@ -59,25 +67,26 @@ EFI/ `-- kdstub.dll ``` -Trident copies all eight files, preserving the nested directories. For the -first OS installation, the managed layout is: +Trident copies the five top-level boot files and discovers direct files in +`Windows/System32`, preserving their relative paths. Subdirectories under +`System32` are ignored. For the first OS installation, the managed layout is: ```text EFI/ -+-- BOOT/ (fallback copy of a selected slot's complete bundle) -+-- AZLA/ (complete slot A bundle) -+-- AZLB/ (complete slot B bundle, populated when staged) ++-- 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 bundles. See [Bootloader Configuration](./Bootloader-Configuration.md) +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 complete BOOT bundle and built with +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. @@ -86,50 +95,53 @@ 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. -Trident detects its BOOT bundle and seeds the complete AZLA bundle before -persisting the discovered HostStatus. Incomplete marked MSHV -bundles fail discovery; legacy shared files outside BOOT do not establish -slot-owned mode. +Trident detects MSHV boot components in BOOT and seeds the AZLA boot files +before persisting the discovered HostStatus. Incomplete MSHV boot components +fail discovery; legacy shared files outside BOOT do not establish slot-owned +mode. ## Updates, Fallback, and Rollback -Staging validates the source bundle and estimates the ESP space required -before clearing the target slot directory. It then copies the complete -bundle into the inactive slot and stages the OS's UKI and addons using the -normal UKI servicing flow. The retained slot's bundle is not replaced. +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. -[UEFI fallback modes](./UEFI-Fallback.md) apply to the complete BOOT bundle: +[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 bundle. | Commit refreshes BOOT from the validated update target. | -| `optimistic` | BOOT already contains the update target's bundle. | No further fallback copy is needed. | +| `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` | Trident does not populate BOOT. | No fallback copy is performed. | -Rollback selects the retained OS slot and its corresponding payload. +Rollback selects the retained OS slot and its corresponding MSHV boot components. A separate hypervisor-validation failure state supports automatic recovery without classifying an identity failure as a user health-check failure. ## Current Limitations The current implementation is limited to x86-64 ACL UKI images because the -payload definition hardcodes x64 filenames. TPM/PCR-bound encryption is +boot-file definition hardcodes x64 filenames. TPM/PCR-bound encryption is rejected. -Slot-owned MSHV requires file-based ESP deployment, not image streaming. -Offline initialization of MSHV-enabled ACL images is not currently supported. +These restrictions apply to file-based ESP deployment; streamed images do +not use this file-copy path. Offline initialization validates detected MSHV +boot components and seeds AZLA when needed. ### Changing the Boot Layout A/B staging compares the source COSI's bootloader type with the retained -slot's actual bundle. Converting between MSHV and ordinary boot layouts is +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 currently assumes success**, meaning that the -running hypervisor matches the hypervisor payload in the active OS slot's +running hypervisor matches the MSHV boot components in the active OS slot's `EFI/AZLA` or `EFI/AZLB` directory. 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 From 7de7c0a3f94d8e05957cb2fb6638d76e8c08e411 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 17:12:24 +0000 Subject: [PATCH 53/82] Consolidate commit success reporting Report success in the provisioned result arm without changing recovery or error handling. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/lib.rs | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index d8618bd10f..9341764f2c 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -854,21 +854,16 @@ impl Trident { ) }); - // Report success only after provisioning, not when rollback is required. - if matches!( - rollback_result, - 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()), - )) - } - } - match rollback_result { - Ok(BootValidationResult::ValidBootProvisioned) => Ok((ExitKind::Done, servicing_type)), + 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(BootValidationResult::InvalidHypervisor(e)) | Ok(BootValidationResult::ValidBootHealthCheckFailed(e)) => { // The caller must reboot to complete automatic recovery. From 539aae89a93adf3faf2c7e1d301dec504d8cdc9a Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 17:48:53 +0000 Subject: [PATCH 54/82] Separate bootloader staging from installed boot-tree copying Select ETL and MSHV requirements independently, reuse common boot-file copying, and replace complete installed boot trees with retryable staging. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/engine/boot/files.rs | 678 ++++++++++++++++++++++ crates/trident/src/engine/boot/mod.rs | 1 + crates/trident/src/engine/boot/mshv.rs | 731 ++---------------------- crates/trident/src/init/acl/mod.rs | 3 +- crates/trident/src/init/offline/mod.rs | 5 +- crates/trident/src/subsystems/esp.rs | 461 ++++++++------- docs/Explanation/MSHV.md | 36 +- 7 files changed, 1020 insertions(+), 895 deletions(-) create mode 100644 crates/trident/src/engine/boot/files.rs diff --git a/crates/trident/src/engine/boot/files.rs b/crates/trident/src/engine/boot/files.rs new file mode 100644 index 0000000000..96bbdec440 --- /dev/null +++ b/crates/trident/src/engine/boot/files.rs @@ -0,0 +1,678 @@ +//! Copies complete installed boot trees without interpreting their bootloader. + +use std::{ + fs, + io::ErrorKind, + path::{Path, PathBuf}, +}; + +use anyhow::{ensure, Context, Error}; +use nix::sys::statvfs; + +const SPACE_RESERVE: u64 = 1024 * 1024; + +fn scan( + root: &Path, + directory: &Path, + temporary: bool, + files: &mut Vec, +) -> Result<(), Error> { + ensure!( + fs::symlink_metadata(directory)?.is_dir(), + "Invalid boot directory: {}", + directory.display() + ); + for entry in fs::read_dir(directory)? { + let entry = entry?; + let path = entry.path(); + let name = entry.file_name(); + let name = name.to_str().context("Non-UTF-8 boot file name")?; + ensure!( + temporary || !is_temporary(name), + "Reserved boot file name: {name}" + ); + let kind = entry.file_type()?; + if kind.is_dir() { + scan(root, &path, temporary, files)?; + } else { + ensure!( + kind.is_file(), + "Not a regular boot file: {}", + path.display() + ); + files.push(path.strip_prefix(root)?.to_path_buf()); + } + } + Ok(()) +} + +fn boot_files(root: &Path, temporary: bool) -> Result, Error> { + let mut files = Vec::new(); + scan(root, root, temporary, &mut files)?; + files.sort(); + Ok(files) +} + +/// Enumerates regular files recursively without following links. +pub(crate) fn filepaths(root: &Path) -> Result, Error> { + Ok(boot_files(root, false)? + .into_iter() + .map(|path| root.join(path)) + .collect()) +} + +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") + }) +} + +fn canonical_path(path: &Path) -> Result { + match fs::canonicalize(path) { + Ok(path) => Ok(path), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(canonical_path( + path.parent().context("Missing boot directory parent")?, + )? + .join(path.file_name().context("Missing boot directory name")?)), + Err(error) => Err(error.into()), + } +} + +fn ensure_disjoint(from: &Path, to: &Path) -> Result<(), Error> { + let from = canonical_path(from)?; + let to = canonical_path(to)?; + ensure!( + !from.starts_with(&to) && !to.starts_with(&from), + "Source and destination boot trees overlap" + ); + Ok(()) +} + +fn copy_entry(from: &Path, to: &Path) -> Result<(), Error> { + if fs::symlink_metadata(from)?.is_dir() { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + copy_entry(&entry.path(), &to.join(entry.file_name()))?; + } + } else { + fs::copy(from, to)?; + } + Ok(()) +} + +fn remove_entry(path: &Path) -> Result<(), Error> { + 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(()) +} + +/// Copies every file and directory after validating both trees. +/// The caller supplies an empty destination when an exact copy is required. +pub(crate) fn copy_boot_files(from: &Path, to: &Path) -> Result<(), Error> { + boot_files(from, false)?; + if to.try_exists()? { + boot_files(to, true)?; + } + ensure_disjoint(from, to)?; + copy_entry(from, to) +} + +/// Estimates cluster-rounded file bytes plus one cluster per directory. +/// Missing paths contribute zero; links and special files are rejected. +fn allocation(path: &Path, cluster: u64) -> Result { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(0), + Err(error) => return Err(error.into()), + }; + if metadata.is_file() { + return Ok(metadata.len().div_ceil(cluster) * cluster); + } + ensure!( + metadata.is_dir(), + "Not a regular file or directory: {}", + path.display() + ); + let mut total = cluster; + for entry in fs::read_dir(path)? { + total += allocation(&entry?.path(), cluster)?; + } + Ok(total) +} + +fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<(), Error> { + ensure!(available.saturating_add(reclaimed) >= required.saturating_add(SPACE_RESERVE), + "Insufficient ESP capacity: need {required} bytes plus {SPACE_RESERVE} bytes reserve, have {available} bytes free and {reclaimed} bytes reclaimable"); + Ok(()) +} + +/// Checks room for a complete new boot tree without reclaiming ESP contents. +pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> { + boot_files(from, false)?; + let stats = statvfs::statvfs(esp)?; + let cluster = stats.fragment_size(); + ensure!(cluster > 0, "Invalid ESP allocation unit"); + check_space( + stats.blocks_available() * cluster, + 0, + allocation(from, cluster)?, + ) +} + +/// Stages complete top-level entries as `.new`, backs up the old entries, +/// then publishes and retires backups. Directory entries include their full +/// subtrees. Publication across entries is not atomic; retries discard partial +/// staging and recover a selected `.old` entry when its current entry is absent. +pub(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { + boot_files(from, false)?; + if to.try_exists()? { + boot_files(to, true)?; + } + ensure_disjoint(from, to)?; + let mut entries = fs::read_dir(from)? + .map(|entry| entry.map(|entry| entry.file_name())) + .collect::, _>>()?; + entries.sort(); + let stats = statvfs::statvfs(to.parent().context("Missing fallback parent")?)?; + let cluster = stats.fragment_size(); + ensure!(cluster > 0, "Invalid ESP allocation unit"); + let mut reclaimed = 0; + for name in &entries { + reclaimed += allocation(&to.join(format!("{}.new", name.to_string_lossy())), cluster)?; + } + check_space( + stats.blocks_available() * cluster, + reclaimed, + allocation(from, cluster)?, + )?; + fs::create_dir_all(to)?; + for name in &entries { + let destination = to.join(name); + let previous = to.join(format!("{}.old", name.to_string_lossy())); + if previous.try_exists()? { + if destination.try_exists()? { + remove_entry(&previous)?; + } else { + fs::rename(&previous, &destination)?; + } + } + let staged = to.join(format!("{}.new", name.to_string_lossy())); + remove_entry(&staged)?; + copy_entry(&from.join(name), &staged)?; + } + 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")); + remove_entry(&previous)?; + fs::rename(entry.path(), previous)?; + } + } + for name in &entries { + fs::rename( + to.join(format!("{}.new", name.to_string_lossy())), + to.join(name), + )?; + } + for entry in fs::read_dir(to)?.collect::, _>>()? { + if is_temporary( + entry + .file_name() + .to_str() + .context("Non-UTF-8 boot file name")?, + ) { + remove_entry(&entry.path())?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::{fs::File, 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::FILES, EngineContext}, + subsystems::esp, + }; + + /// Creates all required slot boot files for tests. + fn create_boot_files(root: &Path, contents: &[u8]) { + for name in 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_boot_files(&source, &target).unwrap(); + for _ in 0..2 { + esp::set_uefi_fallback_contents(&ctx, ServicingState::CleanInstallStaged, &esp) + .unwrap(); + } + filepaths(&fallback).unwrap(); + for name in 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 !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_boot_files(&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_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_boot_files(&source, &target).unwrap(); + for name in 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_boot_files(&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_boot_files(&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_boot_files(&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_boot_files(&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_boot_files(&source, &target).unwrap(); + replace_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_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_boot_files(&source, &fallback).unwrap(); + replace_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_boot_files(&source, &fallback).unwrap(); + assert!(!fallback.join(secondary).join("current.dll").exists()); + filepaths(&fallback).unwrap(); + } + + #[test] + fn budgets_all_files_including_nested_subdirectories() { + 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); + create_boot_files(&source, b"new"); + create_boot_files(&fallback, b"retained"); + let secondary = source.join("Windows/System32"); + fs::create_dir_all(&secondary).unwrap(); + let large = secondary.join("image-specific.bin"); + let stats = statvfs::statvfs(&esp).unwrap(); + File::create(&large) + .unwrap() + .set_len(stats.blocks_available() * stats.fragment_size() + SPACE_RESERVE) + .unwrap(); + assert!(preflight_bootstrap(&source, &esp).is_err()); + assert!(replace_boot_files(&source, &fallback).is_err()); + assert_eq!( + fs::read(fallback.join("HvLoader.efi")).unwrap(), + b"retained" + ); + + fs::create_dir(secondary.join("ignored")).unwrap(); + fs::rename(&large, secondary.join("ignored/large.bin")).unwrap(); + assert!(preflight_bootstrap(&source, &esp).is_err()); + assert!(replace_boot_files(&source, &fallback).is_err()); + fs::remove_file(secondary.join("ignored/large.bin")).unwrap(); + preflight_bootstrap(&source, &esp).unwrap(); + replace_boot_files(&source, &fallback).unwrap(); + assert_eq!(fs::read(fallback.join("HvLoader.efi")).unwrap(), b"new"); + assert!(fallback.join("Windows/System32/ignored").is_dir()); + } + + /// 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 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_boot_files(&source, &target).unwrap_err(); + assert!(!target.exists()); + } + + /// Validation rejects source and destination symlinks. + #[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_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_boot_files(&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_boot_files(&source, &fallback).unwrap(); + replace_boot_files(&source, &fallback).unwrap(); + filepaths(&fallback).unwrap(); + for name in 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_boot_files(&source, &source).is_err()); + } + + /// Capacity includes cluster rounding, reclamation, and a reserve. + #[test] + fn capacity_accounts_for_clusters_and_preserves_a_reserve() { + let temp = TempDir::new().unwrap(); + fs::write(temp.path().join("file"), b"x").unwrap(); + assert_eq!(allocation(&temp.path().join("file"), 4096).unwrap(), 4096); + assert!(check_space(SPACE_RESERVE, 0, 1).is_err()); + assert!(check_space(SPACE_RESERVE, 4096, 4096).is_ok()); + } + + /// 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 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 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 FILES.iter().copied().chain([secondary]) { + assert_eq!(fs::read(fallback.join(name)).unwrap(), b"retained"); + } + } + } +} diff --git a/crates/trident/src/engine/boot/mod.rs b/crates/trident/src/engine/boot/mod.rs index 745e2a7539..d02e4107b8 100644 --- a/crates/trident/src/engine/boot/mod.rs +++ b/crates/trident/src/engine/boot/mod.rs @@ -11,6 +11,7 @@ use crate::engine::Subsystem; use super::EngineContext; +pub(crate) mod files; pub(super) mod grub; pub(crate) mod mshv; pub mod uki; diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 4ddf4a5d3b..43c901d46a 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -1,47 +1,26 @@ -use std::{ - collections::BTreeSet, - fs, - io::ErrorKind, - path::{Path, PathBuf}, -}; +//! Validates MSHV boot components independently of the surrounding bootloader chain. -use anyhow::{ensure, Context, Error}; -use nix::sys::statvfs; - -use osutils::bootloaders::GRUB_NOPREFIX_EFI; +use std::{fs, io::ErrorKind, path::Path}; -use trident_api::constants::GRUB2_CONFIG_FILENAME; - -// Required top-level x64 boot files; secondary MSHV boot components vary between images. -pub(crate) const FILES: &[&str] = &[ - "bootx64.efi", - "grubx64.efi", - "second.efi", - "HvLoader.efi", - "lxhvloader.dll", -]; +use anyhow::{ensure, Context, Error}; -const ORDINARY_FALLBACK_FILES: &[&str] = &[GRUB2_CONFIG_FILENAME, GRUB_NOPREFIX_EFI]; +use trident_api::constants::{EFI_DEFAULT_BIN_RELATIVE_PATH, ESP_EFI_DIRECTORY}; -#[derive(Clone, Copy, PartialEq, Eq)] -enum TreePolicy { - Source, - Staging, - ExistingFallback, -} +use super::files; -/// Optional directory of secondary MSHV boot components, relative to the boot directory. -/// Contents vary between images, so discover its direct files instead of -/// maintaining a fixed binary list. Subdirectories are ignored. -const MSHV_BOOT_COMPONENTS_DIR: &str = "Windows/System32"; -const SPACE_RESERVE: u64 = 1024 * 1024; +const MSHV_BOOT_FILES: &[&str] = &["HvLoader.efi", "lxhvloader.dll"]; +const MSHV_BOOT_COMPONENTS_DIR: &str = "Windows"; -/// Detects MSHV boot components and validates all required slot boot files. +/// Detects MSHV boot components and validates their required loader files. pub(crate) fn has_slot_mshv_boot_components(boot_dir: &Path) -> Result { - for marker in ["HvLoader.efi", "lxhvloader.dll", "Windows"] { + for marker in MSHV_BOOT_FILES + .iter() + .copied() + .chain([MSHV_BOOT_COMPONENTS_DIR]) + { match fs::symlink_metadata(boot_dir.join(marker)) { Ok(_) => { - validate_boot_files(boot_dir)?; + validate_boot_components(boot_dir)?; return Ok(true); } Err(error) if error.kind() == ErrorKind::NotFound => {} @@ -51,675 +30,45 @@ pub(crate) fn has_slot_mshv_boot_components(boot_dir: &Path) -> Result Result, Error> { - let temporary = policy != TreePolicy::Source; - ensure!( - fs::symlink_metadata(directory)?.is_dir(), - "Invalid MSHV boot component directory" - ); - let secondary = directory - .strip_prefix(root)? - .to_str() - .context("Non-UTF-8 MSHV boot component path")? - .eq_ignore_ascii_case(MSHV_BOOT_COMPONENTS_DIR); - let mut files = Vec::new(); - for entry in fs::read_dir(directory)? { - let entry = entry?; - let path = entry.path(); - let relative = path.strip_prefix(root)?; - let relative_name = relative - .to_str() - .context("Non-UTF-8 MSHV boot component path")?; - let kind = entry.file_type()?; - if kind.is_dir() { - if secondary { - continue; - } - ensure!( - relative_name.eq_ignore_ascii_case("Windows") - || relative_name.eq_ignore_ascii_case(MSHV_BOOT_COMPONENTS_DIR), - "Unexpected MSHV boot component directory: {}", - relative.display() - ); - files.extend(validate_tree(root, &path, policy)?); - } else { - ensure!( - kind.is_file(), - "MSHV boot component is not a regular file: {}", - path.display() - ); - ensure!( - secondary - && (temporary - || !relative_name.rsplit_once('.').is_some_and(|(_, suffix)| { - suffix.eq_ignore_ascii_case("new") || suffix.eq_ignore_ascii_case("old") - })) - || FILES - .iter() - .chain( - ORDINARY_FALLBACK_FILES - .iter() - .filter(|_| policy == TreePolicy::ExistingFallback), - ) - .any(|name| { - relative_name.eq_ignore_ascii_case(name) - || temporary - && (relative_name.eq_ignore_ascii_case(&format!("{name}.new")) - || relative_name - .eq_ignore_ascii_case(&format!("{name}.old"))) - }), - "Unexpected MSHV boot component file: {}", - relative.display() - ); - files.push(relative_name.to_owned()); - } - } - Ok(files) -} - -/// Discovers MSHV boot components and supporting boot files using FAT case-insensitive lookups. -fn boot_files(root: &Path) -> Result, Error> { - let mut files = validate_tree(root, root, TreePolicy::Source)?; - for name in FILES { +/// Requires the MSHV loaders and validates the optional Windows tree. +/// Supporting bootloaders, including ETL's second stage, are validated separately. +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(root.join(name)) + fs::symlink_metadata(&path) .with_context(|| format!("Missing MSHV boot component: {name}"))? .is_file(), "Invalid MSHV boot component: {name}" ); } - files.sort(); - Ok(files) -} - -/// Requires the top-level boot files and discovers optional System32 MSHV boot components. -/// Does not validate executable contents or hypervisor identity. -pub(crate) fn validate_boot_files(root: &Path) -> Result<(), Error> { - boot_files(root)?; - Ok(()) -} - -/// Estimates cluster-rounded file bytes plus one cluster per directory. -/// Missing paths contribute zero; symlinks and special files are rejected. -fn allocation(path: &Path, cluster: u64) -> Result { - let metadata = match fs::symlink_metadata(path) { - Ok(metadata) => metadata, - Err(error) if error.kind() == ErrorKind::NotFound => return Ok(0), - Err(error) => return Err(error.into()), - }; - if metadata.is_file() { - return Ok(metadata.len().div_ceil(cluster) * cluster); - } - ensure!( - metadata.is_dir(), - "Not a regular file or directory: {}", - path.display() - ); - let mut total = cluster; - for entry in fs::read_dir(path)? { - total += allocation(&entry?.path(), cluster)?; - } - Ok(total) -} - -/// Budgets selected boot files and their parents, excluding ignored subdirectories. -fn boot_file_allocation(root: &Path, cluster: u64) -> Result { - match fs::symlink_metadata(root) { - Ok(_) => {} - Err(error) if error.kind() == ErrorKind::NotFound => return Ok(0), - Err(error) => return Err(error.into()), - } - let mut directories = BTreeSet::from([PathBuf::new()]); - let mut total = 0; - for name in validate_tree(root, root, TreePolicy::Staging)? { - total += allocation(&root.join(&name), cluster)?; - directories.extend(Path::new(&name).ancestors().skip(1).map(Path::to_path_buf)); - } - Ok(total + directories.len() as u64 * cluster) -} - -/// Requires room for the incoming allocation plus a reserve, crediting planned reclamation. -fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<(), Error> { - ensure!( - available.saturating_add(reclaimed) >= required.saturating_add(SPACE_RESERVE), - "Insufficient ESP capacity: need {required} bytes plus {SPACE_RESERVE} bytes reserve, \ - have {available} bytes free and {reclaimed} bytes reclaimable from the inactive slot" - ); - Ok(()) -} - -/// Checks room for a new copy of slot boot files without reclaiming ESP contents. -pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> { - let stats = statvfs::statvfs(esp)?; - let cluster = stats.fragment_size(); - ensure!(cluster > 0, "Invalid ESP allocation unit"); - check_space( - stats.blocks_available() * cluster, - 0, - boot_file_allocation(from, cluster)?, - ) -} - -/// Copies the required top-level boot files listed in `FILES` and any direct -/// secondary MSHV boot components from the optional `MSHV_BOOT_COMPONENTS_DIR`, -/// preserving boot-directory-relative paths. Subdirectories are ignored, and an absent -/// secondary directory is allowed. -/// -/// Validates and discovers source boot files before writing, so missing -/// required files or traversal errors do not leave partially copied boot files. -/// Copying itself is non-atomic and can leave partial output on an I/O failure. -/// For atomic publication, copy to a temporary directory and rename it. -pub(crate) fn copy_boot_files(from: &Path, to: &Path) -> Result<(), Error> { - let files = boot_files(from)?; - fs::create_dir_all(to)?; - validate_tree(to, to, TreePolicy::Source)?; - for name in &files { - let destination = to.join(name); - fs::create_dir_all( - destination - .parent() - .context("Missing boot component parent")?, - )?; - fs::copy(from.join(name), destination)?; + let windows = boot_dir.join(MSHV_BOOT_COMPONENTS_DIR); + match fs::symlink_metadata(&windows) { + Ok(_) => { + files::filepaths(&windows)?; + } + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error).context("Failed to inspect MSHV boot component directory"), } Ok(()) } -/// Reconciles `.old` backups and stages all `.new` files before replacing fallback. -/// Removes retired secondary MSHV boot components after publishing the selected boot files. -/// Replacing the complete set of boot files is not atomic. -pub(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { - let files = boot_files(from)?; - let existing = match fs::symlink_metadata(to) { - Ok(_) => { - let existing = validate_tree(to, to, TreePolicy::ExistingFallback)?; - ensure!( - fs::canonicalize(from)? != fs::canonicalize(to)?, - "Source and fallback directories must differ" - ); - existing - } - Err(error) if error.kind() == ErrorKind::NotFound => Vec::new(), - Err(error) => return Err(error.into()), - }; - let stats = statvfs::statvfs(to.parent().context("Missing fallback parent")?)?; - let cluster = stats.fragment_size(); - ensure!(cluster > 0, "Invalid ESP allocation unit"); - let required = boot_file_allocation(from, cluster)?; - let mut reclaimed = 0; - for name in &files { - reclaimed += allocation(&to.join(format!("{name}.new")), cluster)?; - } - check_space(stats.blocks_available() * cluster, reclaimed, required)?; - for name in &files { - let destination = to.join(name); - let previous = to.join(format!("{name}.old")); - fs::create_dir_all( - destination - .parent() - .context("Missing boot component parent")?, - )?; - if previous.exists() { - if destination.exists() { - fs::remove_file(&previous)?; - } else { - fs::rename(&previous, &destination)?; - } - } - fs::copy(from.join(name), to.join(format!("{name}.new")))?; - } - for name in &files { - let destination = to.join(name); - if destination.exists() { - fs::rename(&destination, to.join(format!("{name}.old")))?; - } - } - for name in &files { - fs::rename(to.join(format!("{name}.new")), to.join(name))?; - } - for name in &files { - let previous = to.join(format!("{name}.old")); - if previous.exists() { - fs::remove_file(previous)?; - } - } - for name in existing { - let base = name - .rsplit_once('.') - .filter(|(_, suffix)| { - suffix.eq_ignore_ascii_case("new") || suffix.eq_ignore_ascii_case("old") - }) - .map_or(name.as_str(), |(base, _)| base); - if !files.iter().any(|file| file.eq_ignore_ascii_case(base)) { - fs::remove_file(to.join(name))?; +/// Validates discovered installed MSHV components before initializing Host Status. +pub(crate) fn validate_installed_boot_files(esp: &Path) -> Result<(), Error> { + if has_slot_mshv_boot_components(&esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH))? { + let installed = esp.join(ESP_EFI_DIRECTORY).join("AZLA"); + if installed.try_exists()? { + validate_boot_components(&installed)?; } } Ok(()) } #[cfg(test)] -mod tests { - use super::*; - - use std::{fs::File, 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::EngineContext, subsystems::esp}; - - /// Creates all required slot boot files for tests. - fn create_boot_files(root: &Path, contents: &[u8]) { - for name in 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_boot_files(&source, &target).unwrap(); - for _ in 0..2 { - esp::set_uefi_fallback_contents(&ctx, ServicingState::CleanInstallStaged, &esp) - .unwrap(); - } - validate_boot_files(&fallback).unwrap(); - for name in 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 !FILES.iter().any(|name| entry.file_name() == *name) { - assert!(!fallback.join(entry.file_name()).exists()); - } - } - } - } - - #[test] - fn rejects_ordinary_fallback_files_in_incoming_mshv_source() { - for name in [ - "grub.cfg", - "grub.cfg.new", - "grub.cfg.old", - "grubx64-noprefix.efi", - "grubx64-noprefix.efi.new", - "grubx64-noprefix.efi.old", - ] { - let temp = TempDir::new().unwrap(); - let source = temp.path().join("source"); - let fallback = temp.path().join("fallback"); - let target = temp.path().join("target"); - create_boot_files(&source, b"mshv"); - create_boot_files(&fallback, b"retained"); - fs::write(source.join(name), b"ordinary").unwrap(); - validate_boot_files(&source).unwrap_err(); - copy_boot_files(&source, &target).unwrap_err(); - replace_boot_files(&source, &fallback).unwrap_err(); - assert!(!target.exists()); - assert_eq!(fs::read(fallback.join("bootx64.efi")).unwrap(), b"retained"); - } - } - - #[test] - fn rejects_unsafe_ordinary_fallback_entries_before_mutation() { - for kind in ["symlink", "fifo", "directory", "unknown"] { - 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(), - "directory" => fs::create_dir(ordinary).unwrap(), - "unknown" => fs::write(fallback.join("unowned.bin"), b"unowned").unwrap(), - _ => unreachable!(), - } - replace_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_boot_files(&source, &target).unwrap(); - for name in FILES { - assert_eq!(fs::read(target.join(name)).unwrap(), b"new"); - assert_eq!(fs::read(active.join(name)).unwrap(), b"retained"); - } - } - - #[test] - fn discovers_optional_boot_components_without_recursing() { - 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_boot_files(&source, &target).unwrap(); - assert_eq!( - fs::read(target.join("Windows/System32/image-specific.bin")).unwrap(), - b"\0\xffpayload" - ); - assert!(!target.join("Windows/System32/drivers").exists()); - assert!(has_slot_mshv_boot_components(&target).unwrap()); - - fs::remove_dir_all(source.join("Windows")).unwrap(); - let without_secondary = temp.path().join("without-secondary"); - copy_boot_files(&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_boot_files(&source, &empty_secondary).unwrap(); - assert!(!empty_secondary.join("Windows").exists()); - - for name in ["payload.dll.new", "payload.dll.old"] { - let path = secondary.join(name); - fs::write(&path, b"reserved temporary name").unwrap(); - assert!(validate_boot_files(&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_boot_files(&source, &rejected).is_err()); - assert!(!rejected.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_boot_files(&source, &fallback).unwrap(); - replace_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_boot_files(&source, &fallback).unwrap(); - assert!(!fallback.join(secondary).join("current.dll").exists()); - validate_boot_files(&fallback).unwrap(); - } - - #[test] - fn budgets_discovered_boot_components_but_not_ignored_subdirectories() { - 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); - create_boot_files(&source, b"new"); - create_boot_files(&fallback, b"retained"); - let secondary = source.join("Windows/System32"); - fs::create_dir_all(&secondary).unwrap(); - let large = secondary.join("image-specific.bin"); - let stats = statvfs::statvfs(&esp).unwrap(); - File::create(&large) - .unwrap() - .set_len(stats.blocks_available() * stats.fragment_size() + SPACE_RESERVE) - .unwrap(); - assert!(preflight_bootstrap(&source, &esp).is_err()); - assert!(replace_boot_files(&source, &fallback).is_err()); - assert_eq!( - fs::read(fallback.join("HvLoader.efi")).unwrap(), - b"retained" - ); - - fs::create_dir(secondary.join("ignored")).unwrap(); - fs::rename(&large, secondary.join("ignored/large.bin")).unwrap(); - preflight_bootstrap(&source, &esp).unwrap(); - replace_boot_files(&source, &fallback).unwrap(); - assert_eq!(fs::read(fallback.join("HvLoader.efi")).unwrap(), b"new"); - assert!(!fallback.join("Windows/System32/ignored").exists()); - } - - /// Allowlist matching ignores case; temporary names require opt-in. - #[test] - fn accepts_fat_filename_casing_but_rejects_unknown_entries() { - let temp = TempDir::new().unwrap(); - for name in FILES { - let path = temp.path().join(name.to_ascii_uppercase()); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, b"payload").unwrap(); - } - validate_tree(temp.path(), temp.path(), TreePolicy::Source).unwrap(); - let pending = temp.path().join("SECOND.EFI.NEW"); - fs::write(&pending, b"pending").unwrap(); - assert!(validate_tree(temp.path(), temp.path(), TreePolicy::Source).is_err()); - validate_tree(temp.path(), temp.path(), TreePolicy::Staging).unwrap(); - fs::remove_file(pending).unwrap(); - fs::write(temp.path().join("IDENTITY.JSON"), b"unexpected").unwrap(); - assert!(validate_tree(temp.path(), temp.path(), TreePolicy::Staging).is_err()); - } - - /// Invalid sources fail before destination creation. - #[test] - fn rejects_incomplete_and_unexpected_boot_components_before_copy() { - let temp = TempDir::new().unwrap(); - let source = temp.path().join("source"); - let target = temp.path().join("target"); - create_boot_files(&source, b"new"); - fs::remove_file(source.join("lxhvloader.dll")).unwrap(); - assert!(copy_boot_files(&source, &target).is_err()); - assert!(!target.exists()); - create_boot_files(&source, b"new"); - fs::write(source.join("identity.json"), b"unexpected").unwrap(); - assert!(copy_boot_files(&source, &target).is_err()); - assert!(!target.exists()); - } - - /// Validation rejects source and destination symlinks. - #[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_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_boot_files(&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_only_known_temporary_files() { - 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_boot_files(&source, &fallback).unwrap(); - replace_boot_files(&source, &fallback).unwrap(); - validate_boot_files(&fallback).unwrap(); - for name in 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_boot_files(&source, &source).is_err()); - } - - /// Capacity includes cluster rounding, reclamation, and a reserve. - #[test] - fn capacity_accounts_for_clusters_and_preserves_a_reserve() { - let temp = TempDir::new().unwrap(); - fs::write(temp.path().join("file"), b"x").unwrap(); - assert_eq!(allocation(&temp.path().join("file"), 4096).unwrap(), 4096); - assert!(check_space(SPACE_RESERVE, 0, 1).is_err()); - assert!(check_space(SPACE_RESERVE, 4096, 4096).is_ok()); - } - - /// 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 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 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 FILES.iter().copied().chain([secondary]) { - assert_eq!(fs::read(fallback.join(name)).unwrap(), b"retained"); - } - } - } -} +pub(crate) const FILES: &[&str] = &[ + "bootx64.efi", + "grubx64.efi", + "second.efi", + "HvLoader.efi", + "lxhvloader.dll", +]; diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index bc1e7e3048..2344fe62f2 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -20,7 +20,6 @@ use trident_api::{ MountOptions, MountPoint, Partition, PartitionSize, PartitionTableType, PartitionType, Storage, VerityDevice, }, - constants::EFI_DEFAULT_BIN_RELATIVE_PATH, error::TridentResultExt, status::{AbVolumeSelection, HostStatus, ServicingState}, BlockDeviceId, @@ -306,7 +305,7 @@ fn inner_initial_host_status( partition_paths, ..Default::default() }; - mshv::has_slot_mshv_boot_components(&esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH))?; + mshv::validate_installed_boot_files(esp_path)?; Ok(host_status) } diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index ac166b237d..10f4ea11fb 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -29,7 +29,7 @@ use trident_api::{ }; use uuid::Uuid; -use crate::{datastore::DataStore, subsystems::esp}; +use crate::{datastore::DataStore, engine::boot::mshv, subsystems::esp}; #[derive(Clone, Debug, serde::Deserialize)] struct PrismPartition { @@ -534,6 +534,9 @@ pub fn execute( "Failed to find ESP filesystem in Host Status, validation should have failed if this was the case", )))?; + mshv::validate_installed_boot_files(esp_path) + .structured(InvalidInputError::InvalidBootConfiguration) + .message("Invalid installed MSHV boot components")?; esp::bootstrap_azla_from_fallback(esp_path) .structured(InvalidInputError::InvalidBootConfiguration) .message("Failed to bootstrap AZLA from fallback")?; diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index aaa183c793..be443baf23 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -33,7 +33,8 @@ use trident_api::{ use crate::{ engine::{ boot::{ - self, mshv as boot_mshv, uki, ESP_EXTRACTION_DIRECTORY, ESP_EXTRACTION_DIRECTORY_MODE, + self, files as boot_files, mshv as boot_mshv, uki, ESP_EXTRACTION_DIRECTORY, + ESP_EXTRACTION_DIRECTORY_MODE, }, EngineContext, Subsystem, }, @@ -47,6 +48,8 @@ use crate::{ mod mshv; +const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; + #[derive(Default, Debug)] pub struct EspSubsystem; impl Subsystem for EspSubsystem { @@ -366,9 +369,6 @@ 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()); - // MSHV boot components require additional files beyond the ordinary boot-file list. - let slot_mshv = ctx.bootloader().is_some_and(Bootloader::uses_mshv); - let source_boot_dir = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); let boot_files = prepare_boot_files_for_staging(temp_mount_dir, ctx, mount_point)?; // Clear esp_dir_path if it exists @@ -388,16 +388,14 @@ fn copy_file_artifacts( } // Call helper func to copy boot files from temp_mount_dir to esp_dir_path - let grub_noprefix = if slot_mshv { - boot_mshv::copy_boot_files(&source_boot_dir, &esp_dir_path)?; - false - } else { - 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() - ))? - }; + let grub_noprefix = + 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 @@ -461,18 +459,41 @@ fn prepare_boot_files_for_staging( let source_boot_dir = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); // Compare source metadata with the retained slot before any ESP writes. mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; - let boot_files = if ctx.bootloader().is_some_and(Bootloader::uses_mshv) { - boot_mshv::validate_boot_files(&source_boot_dir)?; - Vec::new() + let mut boot_files = generate_boot_filepaths(temp_mount_dir, is_uki, ctx.bootloader()) + .context("Failed to generate boot filepaths")?; + if ctx.bootloader().is_some_and(Bootloader::uses_mshv) { + boot_mshv::validate_boot_components(&source_boot_dir)?; + for component in boot_files::filepaths(&source_boot_dir)? { + let relative = component.strip_prefix(&source_boot_dir)?; + let name = relative.to_str().context("Non-UTF-8 boot file path")?; + // These are selected and normalized by ordinary bootloader discovery. + 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; + } + boot_files.push(component); + } } else { - // Ordinary copying would omit required MSHV boot components. ensure!( !source_boot_dir.join("HvLoader.efi").try_exists()?, "An MSHV image must declare COSI bootloader type 'efitreeloader-mshv-systemd-boot'" ); - generate_boot_filepaths(temp_mount_dir, is_uki) - .context("Failed to generate boot filepaths")? - }; + } + for path in &boot_files { + ensure!( + fs::symlink_metadata(path)?.is_file(), + "Not a regular boot file: {}", + path.display() + ); + } if is_uki { // Reclaim target-slot space before copying, preserving the active slot. // A failed copy can leave the target without its previous UKI. @@ -623,12 +644,7 @@ fn copy_boot_files_for_uefi_fallback( source_esp_dir_path.display(), uefi_fallback_path.display() ); - // Fallback also runs without an image, so detect the selected slot's MSHV boot components. - let result = if boot_mshv::has_slot_mshv_boot_components(&source_esp_dir_path)? { - boot_mshv::replace_boot_files(&source_esp_dir_path, &uefi_fallback_path) - } else { - replace_boot_files(&source_esp_dir_path, &uefi_fallback_path) - }; + let result = replace_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(), @@ -637,121 +653,9 @@ fn copy_boot_files_for_uefi_fallback( Ok(()) } -/// Copies boot files from one folder to another. +/// Replaces the complete fallback boot tree, including nested files. 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 pre-existing entries 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(); - // Leave staged files and pending cleanup entries in place. - if !orig_file_name_string.ends_with(".new") && !orig_file_name_string.ends_with(".old") - { - 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 retired files and the known MSHV boot component directory. - 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") { - let result = if orig_path.file_type()?.is_dir() - && orig_file_name - .to_string_lossy() - .eq_ignore_ascii_case("Windows.old") - { - fs::remove_dir_all(orig_path.path()) - } else { - fs::remove_file(orig_path.path()) - }; - result.context(format!( - "Failed to remove pre-existing entry '{}'", - orig_path.path().display() - ))?; - trace!( - "Removed pre-existing entry '{}'", - orig_path.path().display() - ); - } - Ok::<(), Error>(()) - }) - .context("Failed to remove pre-existing files")?; - Ok(()) + boot_files::replace_boot_files(from_dir, to_dir) } /// Ensures `EFI/AZLA` exists on the ESP, seeding it from the `EFI/BOOT` fallback @@ -759,16 +663,12 @@ pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { /// 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. /// -/// Detects MSHV boot components in BOOT, preflights boot-file capacity, and publishes a -/// complete copy via a staged directory rename. Existing AZLA is never refreshed: -/// it is validated when BOOT contains MSHV, or left untouched for ordinary BOOT. +/// Preflights the complete BOOT tree and publishes a copy via a staged +/// directory rename. Existing AZLA is never refreshed; image-specific +/// completeness checks belong to initialization, not tree relocation. 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); - let slot_mshv = boot_mshv::has_slot_mshv_boot_components(&boot_esp_path)?; - if slot_mshv && azla_esp_path.exists() { - return boot_mshv::validate_boot_files(&azla_esp_path); - } trace!("Checking for AZLA volume ESP path at {:?}", &azla_esp_path); if !azla_esp_path.exists() { trace!( @@ -779,8 +679,7 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { // an atomic rename only once the copy has fully succeeded. Creating // AZLA directly before the copy completes could leave a partially // populated directory on failure. Ordinary-mode retries would skip - // that directory because it exists, while MSHV retries would reject - // its incomplete MSHV boot components rather than repair them. + // 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!( @@ -788,13 +687,9 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { azla_tmp_path.display() ))?; } - let copy_result = if slot_mshv { - // Check capacity after reclaiming stale staging contents. - boot_mshv::preflight_bootstrap(&boot_esp_path, esp_path)?; - boot_mshv::copy_boot_files(&boot_esp_path, &azla_tmp_path) - } else { - replace_boot_files(&boot_esp_path, &azla_tmp_path) - }; + // Check capacity after reclaiming stale staging contents. + boot_files::preflight_bootstrap(&boot_esp_path, esp_path)?; + let copy_result = boot_files::copy_boot_files(&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(), @@ -828,7 +723,11 @@ fn copy_boot_files( boot_file.display() ))?; - let destination_path = esp_dir.join(file_name); + 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() { @@ -848,7 +747,10 @@ fn copy_boot_files( ))?; // Rename grub-noprefix efi to grub efi - if file_name == GRUB_NOPREFIX_EFI { + if relative + .to_str() + .is_some_and(|name| name.eq_ignore_ascii_case(GRUB_NOPREFIX_EFI)) + { fs::rename( &destination_path, esp_dir @@ -869,9 +771,15 @@ 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. +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) @@ -912,14 +820,16 @@ fn generate_boot_filepaths(temp_mount_dir: &Path, is_uki: bool) -> Result Result (TempDir, TempDir, EngineContext) { let source = TempDir::new().unwrap(); @@ -1029,6 +1104,9 @@ mod tests { 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(); + } } let ukis = esp.path().join(uki::UKI_DIRECTORY); fs::create_dir_all(&ukis).unwrap(); @@ -1708,17 +1786,17 @@ mod tests { } #[test] - fn test_replace_boot_files_preserves_unrelated_directories() { + 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("unrelated")).unwrap(); - fs::write(destination.path().join("unrelated/keep"), b"unrelated data").unwrap(); - - assert!(replace_boot_files(source.path(), destination.path()).is_err()); + fs::create_dir_all(destination.path().join("retired")).unwrap(); + fs::write(destination.path().join("retired/old"), b"retired data").unwrap(); + replace_boot_files(source.path(), destination.path()).unwrap(); + assert!(!destination.path().join("retired").exists()); assert_eq!( - fs::read(destination.path().join("unrelated.old/keep")).unwrap(), - b"unrelated data" + fs::read(destination.path().join(BOOT_EFI)).unwrap(), + b"ordinary loader" ); } @@ -1841,7 +1919,7 @@ mod tests { } } - /// MSHV discovers secondary files and validates, but never refreshes, existing AZLA. + /// Bootstrap preserves all MSHV files but never refreshes an existing AZLA. #[test] fn test_bootstrap_azla_from_mshv_fallback() { let esp = TempDir::new().unwrap(); @@ -1883,8 +1961,9 @@ mod tests { bootstrap_azla_from_fallback(esp.path()).unwrap(); assert!(!azla.join(secondary).exists()); fs::remove_file(azla.join("lxhvloader.dll")).unwrap(); - assert!(bootstrap_azla_from_fallback(esp.path()).is_err()); + bootstrap_azla_from_fallback(esp.path()).unwrap(); assert!(!azla.join("lxhvloader.dll").exists()); + assert!(boot_mshv::validate_installed_boot_files(esp.path()).is_err()); } /// Failed preflight follows stale-copy cleanup and leaves BOOT untouched. @@ -1925,14 +2004,14 @@ mod tests { /// Incomplete marked fallback cannot publish AZLA. #[test] - fn test_bootstrap_azla_rejects_incomplete_mshv_fallback() { + fn test_initialization_rejects_incomplete_mshv_before_bootstrap() { 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"); fs::create_dir_all(&boot).unwrap(); fs::write(boot.join(BOOT_EFI), "shim").unwrap(); fs::write(boot.join("HvLoader.efi"), "loader").unwrap(); - assert!(bootstrap_azla_from_fallback(esp.path()).is_err()); + boot_mshv::validate_installed_boot_files(esp.path()).unwrap_err(); assert!(!azla.exists()); assert_eq!(fs::read_to_string(boot.join(BOOT_EFI)).unwrap(), "shim"); } @@ -2051,7 +2130,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(), @@ -2067,14 +2146,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 @@ -2085,7 +2164,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![ @@ -2102,7 +2181,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(), @@ -2118,7 +2197,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![ @@ -2135,7 +2214,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(), @@ -2169,13 +2248,13 @@ mod tests { .join(ETL_SECOND_STAGE_EFI_FILENAME); assert_eq!( - generate_boot_filepaths(source.path(), is_uki).unwrap(), + generate_boot_filepaths(source.path(), is_uki, None).unwrap(), expected_paths, "absent second stage: is_uki={is_uki}, grub={grub_filename}" ); fs::write(&second_stage, [0, 0xff, 1, 0x80]).unwrap(); - 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, "unrelated second-stage file: is_uki={is_uki}, grub={grub_filename}" @@ -2194,7 +2273,7 @@ mod tests { fs::remove_file(&second_stage).unwrap(); fs::create_dir(&second_stage).unwrap(); assert_eq!( - generate_boot_filepaths(source.path(), is_uki).unwrap(), + 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/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index 1dc8539705..ed70ec9385 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -42,12 +42,13 @@ 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/System32`. Shim, efitreeloader, -and systemd-boot are supporting bootloaders, not MSHV-specific components. +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/System32` directory may contain image-specific MSHV +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. @@ -67,9 +68,12 @@ EFI/ `-- kdstub.dll ``` -Trident copies the five top-level boot files and discovers direct files in -`Windows/System32`, preserving their relative paths. Subdirectories under -`System32` are ignored. For the first OS installation, the managed layout is: +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 preserves all additional +BOOT files and subdirectories, including nested `Windows` components, rather +than imposing an exhaustive filename list. UKI handling is selected separately. +For the first OS installation, the managed layout is: ```text EFI/ @@ -95,10 +99,10 @@ 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. -Trident detects MSHV boot components in BOOT and seeds the AZLA boot files -before persisting the discovered HostStatus. Incomplete MSHV boot components -fail discovery; legacy shared files outside BOOT do not establish slot-owned -mode. +Initialization validates detected MSHV loader files before seeding AZLA +and persisting the discovered HostStatus. Legacy shared files outside BOOT +do not establish slot-owned mode. Bootstrap copies the complete BOOT tree +without interpreting its bootloader; an existing AZLA is never refreshed. ## Updates, Fallback, and Rollback @@ -109,6 +113,18 @@ 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. +Fallback and bootstrap relocate complete installed boot trees without COSI +metadata or MSHV/efitreeloader filename selection. Files, nested directories +and empty directories are preserved. Destination-only entries inside the +owned boot directory are retired; 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. Both paths retain capacity preflight; staging does not. +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 | From 7cf17066b8dd3fc13a78a1b367ec08b5dc639eda Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 18:05:21 +0000 Subject: [PATCH 55/82] Document boot-tree copying and replacement invariants Explain ownership, validation boundaries, capacity estimates, retry recovery, and non-atomic publication phases. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/engine/boot/files.rs | 52 ++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/crates/trident/src/engine/boot/files.rs b/crates/trident/src/engine/boot/files.rs index 96bbdec440..01bfb09a4f 100644 --- a/crates/trident/src/engine/boot/files.rs +++ b/crates/trident/src/engine/boot/files.rs @@ -1,4 +1,8 @@ //! Copies complete installed boot trees without interpreting their bootloader. +//! +//! Image-specific completeness belongs to staging and initialization. Relocation +//! preserves unfamiliar files and directories while enforcing structural safety. +//! Replacement owns the destination's entire contents, not individual filenames. use std::{ fs, @@ -9,8 +13,11 @@ use std::{ use anyhow::{ensure, Context, Error}; use nix::sys::statvfs; +// Leave headroom for directory growth beyond the per-directory estimate. const SPACE_RESERVE: u64 = 1024 * 1024; +/// Validates the whole tree, including empty directories, and collects relative file paths. +/// `temporary` permits replacement suffixes in destinations left by interrupted work. fn scan( root: &Path, directory: &Path, @@ -46,6 +53,7 @@ fn scan( Ok(()) } +/// Returns sorted root-relative file paths; empty directories are validated but not listed. fn boot_files(root: &Path, temporary: bool) -> Result, Error> { let mut files = Vec::new(); scan(root, root, temporary, &mut files)?; @@ -54,6 +62,7 @@ fn boot_files(root: &Path, temporary: bool) -> Result, Error> { } /// 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() @@ -61,12 +70,14 @@ pub(crate) fn filepaths(root: &Path) -> Result, Error> { .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") }) } +/// Resolves existing ancestors so overlap checks also cover destinations not yet created. fn canonical_path(path: &Path) -> Result { match fs::canonicalize(path) { Ok(path) => Ok(path), @@ -78,6 +89,7 @@ fn canonical_path(path: &Path) -> Result { } } +/// Prevents recursive copying into the source or retiring entries that contain the source. fn ensure_disjoint(from: &Path, to: &Path) -> Result<(), Error> { let from = canonical_path(from)?; let to = canonical_path(to)?; @@ -88,6 +100,8 @@ fn ensure_disjoint(from: &Path, to: &Path) -> Result<(), Error> { Ok(()) } +/// Copies an already-validated entry, creating even empty directories. +/// Existing destination-only entries are not retired, and failure can leave a partial copy. fn copy_entry(from: &Path, to: &Path) -> Result<(), Error> { if fs::symlink_metadata(from)?.is_dir() { fs::create_dir_all(to)?; @@ -101,6 +115,7 @@ fn copy_entry(from: &Path, to: &Path) -> Result<(), Error> { Ok(()) } +/// Removes an owned entry; missing entries are expected during retry cleanup. fn remove_entry(path: &Path) -> Result<(), Error> { match fs::symlink_metadata(path) { Ok(metadata) if metadata.is_dir() => fs::remove_dir_all(path)?, @@ -111,8 +126,9 @@ fn remove_entry(path: &Path) -> Result<(), Error> { Ok(()) } -/// Copies every file and directory after validating both trees. -/// The caller supplies an empty destination when an exact copy is required. +/// Copies a validated tree without retiring destination-only entries. +/// 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(crate) fn copy_boot_files(from: &Path, to: &Path) -> Result<(), Error> { boot_files(from, false)?; if to.try_exists()? { @@ -145,6 +161,8 @@ fn allocation(path: &Path, cluster: u64) -> Result { Ok(total) } +/// Checks the estimated copy budget without reclaiming current entries or backups. +/// `reclaimed` counts only matching `.new` entries that retries will discard. fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<(), Error> { ensure!(available.saturating_add(reclaimed) >= required.saturating_add(SPACE_RESERVE), "Insufficient ESP capacity: need {required} bytes plus {SPACE_RESERVE} bytes reserve, have {available} bytes free and {reclaimed} bytes reclaimable"); @@ -152,6 +170,7 @@ fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<(), Erro } /// Checks room for a complete new boot tree without reclaiming ESP contents. +/// `esp` identifies the destination filesystem; stale bootstrap staging is removed by the caller. pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> { boot_files(from, false)?; let stats = statvfs::statvfs(esp)?; @@ -164,11 +183,15 @@ pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> ) } -/// Stages complete top-level entries as `.new`, backs up the old entries, -/// then publishes and retires backups. Directory entries include their full -/// subtrees. Publication across entries is not atomic; retries discard partial -/// staging and recover a selected `.old` entry when its current entry is absent. +/// Replaces an owned directory's complete contents, including nested and empty +/// directories. Destination-only entries are retired after the new tree is staged. +/// +/// 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(crate) fn replace_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)?; @@ -178,6 +201,10 @@ pub(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { .map(|entry| entry.map(|entry| entry.file_name())) .collect::, _>>()?; entries.sort(); + + // Budget the new tree alongside current entries and backups. Only matching + // abandoned `.new` entries are credited; other temporary entries stay in place + // until publication succeeds. let stats = statvfs::statvfs(to.parent().context("Missing fallback parent")?)?; let cluster = stats.fragment_size(); ensure!(cluster > 0, "Invalid ESP allocation unit"); @@ -190,10 +217,14 @@ pub(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { reclaimed, allocation(from, cluster)?, )?; + + // 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()? { remove_entry(&previous)?; @@ -201,10 +232,14 @@ pub(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { 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())); remove_entry(&staged)?; copy_entry(&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")?; @@ -214,12 +249,17 @@ pub(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { 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 From cb2cf4ce4c87f45cec9c212953df4e8a1642473e Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 18:20:09 +0000 Subject: [PATCH 56/82] Remove redundant ESP boot-file replacement wrapper Call the shared boot-tree replacement directly from fallback handling and existing tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/subsystems/esp.rs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index be443baf23..413ba429cc 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -644,7 +644,7 @@ fn copy_boot_files_for_uefi_fallback( source_esp_dir_path.display(), uefi_fallback_path.display() ); - let result = replace_boot_files(&source_esp_dir_path, &uefi_fallback_path); + let result = boot_files::replace_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(), @@ -653,11 +653,6 @@ fn copy_boot_files_for_uefi_fallback( Ok(()) } -/// Replaces the complete fallback boot tree, including nested files. -pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { - boot_files::replace_boot_files(from_dir, to_dir) -} - /// 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 @@ -1739,7 +1734,7 @@ mod tests { } // Call the function to copy files - replace_boot_files(from_dir.path(), to_dir.path()).unwrap(); + boot_files::replace_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 { @@ -1775,7 +1770,7 @@ mod tests { fs::create_dir_all(&secondary).unwrap(); fs::write(secondary.join("image-specific.dll"), b"previous payload").unwrap(); - replace_boot_files(source.path(), destination.path()).unwrap(); + boot_files::replace_boot_files(source.path(), destination.path()).unwrap(); assert_eq!( fs::read(destination.path().join(BOOT_EFI)).unwrap(), @@ -1792,7 +1787,7 @@ mod tests { 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(); - replace_boot_files(source.path(), destination.path()).unwrap(); + boot_files::replace_boot_files(source.path(), destination.path()).unwrap(); assert!(!destination.path().join("retired").exists()); assert_eq!( fs::read(destination.path().join(BOOT_EFI)).unwrap(), From e3e01315072674d00d71cf71fe181c2bfede858f Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 18:38:47 +0000 Subject: [PATCH 57/82] boot: rely on staged copies instead of capacity estimates Propagate copy failures before publishing fallback or bootstrap trees. Remove allocation prediction and reserve checks; retain validation and retry recovery. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/engine/boot/files.rs | 114 +----------------------- crates/trident/src/subsystems/esp.rs | 47 +++++----- docs/Explanation/MSHV.md | 5 +- 3 files changed, 29 insertions(+), 137 deletions(-) diff --git a/crates/trident/src/engine/boot/files.rs b/crates/trident/src/engine/boot/files.rs index 01bfb09a4f..67752382f5 100644 --- a/crates/trident/src/engine/boot/files.rs +++ b/crates/trident/src/engine/boot/files.rs @@ -3,6 +3,7 @@ //! Image-specific completeness belongs to staging and initialization. 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, @@ -11,10 +12,6 @@ use std::{ }; use anyhow::{ensure, Context, Error}; -use nix::sys::statvfs; - -// Leave headroom for directory growth beyond the per-directory estimate. -const SPACE_RESERVE: u64 = 1024 * 1024; /// Validates the whole tree, including empty directories, and collects relative file paths. /// `temporary` permits replacement suffixes in destinations left by interrupted work. @@ -138,53 +135,9 @@ pub(crate) fn copy_boot_files(from: &Path, to: &Path) -> Result<(), Error> { copy_entry(from, to) } -/// Estimates cluster-rounded file bytes plus one cluster per directory. -/// Missing paths contribute zero; links and special files are rejected. -fn allocation(path: &Path, cluster: u64) -> Result { - let metadata = match fs::symlink_metadata(path) { - Ok(metadata) => metadata, - Err(error) if error.kind() == ErrorKind::NotFound => return Ok(0), - Err(error) => return Err(error.into()), - }; - if metadata.is_file() { - return Ok(metadata.len().div_ceil(cluster) * cluster); - } - ensure!( - metadata.is_dir(), - "Not a regular file or directory: {}", - path.display() - ); - let mut total = cluster; - for entry in fs::read_dir(path)? { - total += allocation(&entry?.path(), cluster)?; - } - Ok(total) -} - -/// Checks the estimated copy budget without reclaiming current entries or backups. -/// `reclaimed` counts only matching `.new` entries that retries will discard. -fn check_space(available: u64, reclaimed: u64, required: u64) -> Result<(), Error> { - ensure!(available.saturating_add(reclaimed) >= required.saturating_add(SPACE_RESERVE), - "Insufficient ESP capacity: need {required} bytes plus {SPACE_RESERVE} bytes reserve, have {available} bytes free and {reclaimed} bytes reclaimable"); - Ok(()) -} - -/// Checks room for a complete new boot tree without reclaiming ESP contents. -/// `esp` identifies the destination filesystem; stale bootstrap staging is removed by the caller. -pub(crate) fn preflight_bootstrap(from: &Path, esp: &Path) -> Result<(), Error> { - boot_files(from, false)?; - let stats = statvfs::statvfs(esp)?; - let cluster = stats.fragment_size(); - ensure!(cluster > 0, "Invalid ESP allocation unit"); - check_space( - stats.blocks_available() * cluster, - 0, - allocation(from, cluster)?, - ) -} - /// Replaces an owned directory's complete contents, 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 @@ -202,22 +155,6 @@ pub(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { .collect::, _>>()?; entries.sort(); - // Budget the new tree alongside current entries and backups. Only matching - // abandoned `.new` entries are credited; other temporary entries stay in place - // until publication succeeds. - let stats = statvfs::statvfs(to.parent().context("Missing fallback parent")?)?; - let cluster = stats.fragment_size(); - ensure!(cluster > 0, "Invalid ESP allocation unit"); - let mut reclaimed = 0; - for name in &entries { - reclaimed += allocation(&to.join(format!("{}.new", name.to_string_lossy())), cluster)?; - } - check_space( - stats.blocks_available() * cluster, - reclaimed, - allocation(from, cluster)?, - )?; - // Rebuild all incoming staging while leaving current entries available. fs::create_dir_all(to)?; for name in &entries { @@ -277,7 +214,7 @@ pub(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { mod tests { use super::*; - use std::{fs::File, os::unix::fs as unix_fs}; + use std::os::unix::fs as unix_fs; use nix::{sys::stat::Mode, unistd}; use tempfile::TempDir; @@ -526,41 +463,6 @@ mod tests { filepaths(&fallback).unwrap(); } - #[test] - fn budgets_all_files_including_nested_subdirectories() { - 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); - create_boot_files(&source, b"new"); - create_boot_files(&fallback, b"retained"); - let secondary = source.join("Windows/System32"); - fs::create_dir_all(&secondary).unwrap(); - let large = secondary.join("image-specific.bin"); - let stats = statvfs::statvfs(&esp).unwrap(); - File::create(&large) - .unwrap() - .set_len(stats.blocks_available() * stats.fragment_size() + SPACE_RESERVE) - .unwrap(); - assert!(preflight_bootstrap(&source, &esp).is_err()); - assert!(replace_boot_files(&source, &fallback).is_err()); - assert_eq!( - fs::read(fallback.join("HvLoader.efi")).unwrap(), - b"retained" - ); - - fs::create_dir(secondary.join("ignored")).unwrap(); - fs::rename(&large, secondary.join("ignored/large.bin")).unwrap(); - assert!(preflight_bootstrap(&source, &esp).is_err()); - assert!(replace_boot_files(&source, &fallback).is_err()); - fs::remove_file(secondary.join("ignored/large.bin")).unwrap(); - preflight_bootstrap(&source, &esp).unwrap(); - replace_boot_files(&source, &fallback).unwrap(); - assert_eq!(fs::read(fallback.join("HvLoader.efi")).unwrap(), b"new"); - assert!(fallback.join("Windows/System32/ignored").is_dir()); - } - /// Temporary suffixes are reserved regardless of filename casing. #[test] fn accepts_additional_files_but_rejects_temporary_source_names() { @@ -637,16 +539,6 @@ mod tests { assert!(replace_boot_files(&source, &source).is_err()); } - /// Capacity includes cluster rounding, reclamation, and a reserve. - #[test] - fn capacity_accounts_for_clusters_and_preserves_a_reserve() { - let temp = TempDir::new().unwrap(); - fs::write(temp.path().join("file"), b"x").unwrap(); - assert_eq!(allocation(&temp.path().join("file"), 4096).unwrap(), 4096); - assert!(check_space(SPACE_RESERVE, 0, 1).is_err()); - assert!(check_space(SPACE_RESERVE, 4096, 4096).is_ok()); - } - /// 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() { diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 413ba429cc..c30a91e277 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -658,8 +658,8 @@ fn copy_boot_files_for_uefi_fallback( /// 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. /// -/// Preflights the complete BOOT tree and publishes a copy via a staged -/// directory rename. Existing AZLA is never refreshed; image-specific +/// Copies the complete BOOT tree and publishes it via a staged directory +/// rename only after copying succeeds. Existing AZLA is never refreshed; image-specific /// completeness checks belong to initialization, not tree relocation. pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { let azla_esp_path = esp_path.join(ESP_EFI_DIRECTORY).join("AZLA"); @@ -682,8 +682,6 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { azla_tmp_path.display() ))?; } - // Check capacity after reclaiming stale staging contents. - boot_files::preflight_bootstrap(&boot_esp_path, esp_path)?; let copy_result = boot_files::copy_boot_files(&boot_esp_path, &azla_tmp_path); copy_result.context(format!( "Failed to copy boot files from '{}' to temporary AZLA bootstrap path '{}'", @@ -888,12 +886,7 @@ fn generate_efi_bin_base_dir_path( mod tests { use super::*; - use std::{ - fs::{File, OpenOptions}, - io::Write, - }; - - use nix::sys::statvfs; + use std::{fs::File, io::Write}; use trident_api::{ config::{HostConfiguration, Os}, @@ -1961,9 +1954,9 @@ mod tests { assert!(boot_mshv::validate_installed_boot_files(esp.path()).is_err()); } - /// Failed preflight follows stale-copy cleanup and leaves BOOT untouched. + /// Failed source validation leaves AZLA unpublished and permits a clean retry. #[test] - fn test_bootstrap_azla_cleans_stale_mshv_copy_before_capacity_check() { + 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"); @@ -1978,23 +1971,27 @@ mod tests { } fs::create_dir_all(&temporary).unwrap(); fs::write(temporary.join("stale"), b"abandoned copy").unwrap(); - - // Force preflight failure with a sparse file, without filling the filesystem. - let stats = statvfs::statvfs(esp.path()).unwrap(); - let length = stats.blocks_available() * stats.fragment_size() + 1; - OpenOptions::new() - .write(true) - .open(boot.join(BOOT_EFI)) - .unwrap() - .set_len(length) - .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.to_string().contains("Insufficient ESP capacity")); + assert!(error + .root_cause() + .to_string() + .contains("Reserved boot file name")); assert!(!temporary.exists()); assert!(!azla.exists()); - assert_eq!(fs::metadata(boot.join(BOOT_EFI)).unwrap().len(), length); - assert_eq!(fs::read(boot.join("HvLoader.efi")).unwrap(), b"retained"); + for name in 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 FILES { + assert!(files_are_identical(&boot.join(name), &azla.join(name))); + } } /// Incomplete marked fallback cannot publish AZLA. diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index ed70ec9385..888e87deb8 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -122,7 +122,10 @@ 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. Both paths retain capacity preflight; staging does not. +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: From 3da29edd8a27c7d15562d8bcab54f541850d204f Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 19:24:02 +0000 Subject: [PATCH 58/82] boot: explain image staging path handling Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/subsystems/esp.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index c30a91e277..6cbf92cb4f 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -716,6 +716,8 @@ fn copy_boot_files( boot_file.display() ))?; + // 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) @@ -739,7 +741,7 @@ fn copy_boot_files( destination_path.display() ))?; - // Rename grub-noprefix efi to grub 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)) From c499dd06820498da46f126fba283895f86d06215 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 19:26:58 +0000 Subject: [PATCH 59/82] boot: name tree-copy helpers for bootstrap and fallback Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/engine/boot/files.rs | 48 ++++++++++++------------- crates/trident/src/subsystems/esp.rs | 12 +++---- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/crates/trident/src/engine/boot/files.rs b/crates/trident/src/engine/boot/files.rs index 67752382f5..1a6ba06adb 100644 --- a/crates/trident/src/engine/boot/files.rs +++ b/crates/trident/src/engine/boot/files.rs @@ -123,10 +123,10 @@ fn remove_entry(path: &Path) -> Result<(), Error> { Ok(()) } -/// Copies a validated tree without retiring destination-only entries. +/// 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(crate) fn copy_boot_files(from: &Path, to: &Path) -> Result<(), Error> { +pub(crate) fn copy_fallback_for_bootstrap(from: &Path, to: &Path) -> Result<(), Error> { boot_files(from, false)?; if to.try_exists()? { boot_files(to, true)?; @@ -135,7 +135,7 @@ pub(crate) fn copy_boot_files(from: &Path, to: &Path) -> Result<(), Error> { copy_entry(from, to) } -/// Replaces an owned directory's complete contents, including nested and empty +/// 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. /// @@ -143,7 +143,7 @@ pub(crate) fn copy_boot_files(from: &Path, to: &Path) -> Result<(), Error> { /// 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(crate) fn replace_boot_files(from: &Path, to: &Path) -> Result<(), Error> { +pub(crate) 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()? { @@ -272,7 +272,7 @@ mod tests { ..Default::default() }; ctx.spec.os.uefi_fallback = mode; - copy_boot_files(&source, &target).unwrap(); + copy_fallback_for_bootstrap(&source, &target).unwrap(); for _ in 0..2 { esp::set_uefi_fallback_contents(&ctx, ServicingState::CleanInstallStaged, &esp) .unwrap(); @@ -300,7 +300,7 @@ mod tests { for name in ["grub.cfg", "grubx64-noprefix.efi", "future-loader.efi"] { fs::write(source.join(name), name).unwrap(); } - copy_boot_files(&source, &target).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(), @@ -328,7 +328,7 @@ mod tests { "fifo" => unistd::mkfifo(&ordinary, Mode::S_IRUSR).unwrap(), _ => unreachable!(), } - replace_boot_files(&source, &fallback).unwrap_err(); + 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"); } @@ -343,7 +343,7 @@ mod tests { let target = temp.path().join("AZLB"); create_boot_files(&source, b"new"); create_boot_files(&active, b"retained"); - copy_boot_files(&source, &target).unwrap(); + copy_fallback_for_bootstrap(&source, &target).unwrap(); for name in FILES { assert_eq!(fs::read(target.join(name)).unwrap(), b"new"); assert_eq!(fs::read(active.join(name)).unwrap(), b"retained"); @@ -361,7 +361,7 @@ mod tests { fs::write(secondary.join("image-specific.bin"), b"\0\xffpayload").unwrap(); fs::write(secondary.join("drivers/ignored.dll"), b"ignored").unwrap(); - copy_boot_files(&source, &target).unwrap(); + copy_fallback_for_bootstrap(&source, &target).unwrap(); assert_eq!( fs::read(target.join("Windows/System32/image-specific.bin")).unwrap(), b"\0\xffpayload" @@ -374,11 +374,11 @@ mod tests { fs::remove_dir_all(source.join("Windows")).unwrap(); let without_secondary = temp.path().join("without-secondary"); - copy_boot_files(&source, &without_secondary).unwrap(); + 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_boot_files(&source, &empty_secondary).unwrap(); + 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"] { @@ -389,7 +389,7 @@ mod tests { } unix_fs::symlink(temp.path().join("outside"), secondary.join("linked.dll")).unwrap(); let rejected = temp.path().join("rejected"); - assert!(copy_boot_files(&source, &rejected).is_err()); + assert!(copy_fallback_for_bootstrap(&source, &rejected).is_err()); assert!(!rejected.exists()); } @@ -406,13 +406,13 @@ mod tests { 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_boot_files(&source, &target).unwrap(); - replace_boot_files(&source, &target).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_boot_files(&source, &source.join("child")).is_err()); + assert!(replace_fallback_boot_files(&source, &source.join("child")).is_err()); assert!(!source.join("child").exists()); } @@ -441,8 +441,8 @@ mod tests { fs::write(fallback.join(secondary).join(name), b"obsolete").unwrap(); } - replace_boot_files(&source, &fallback).unwrap(); - replace_boot_files(&source, &fallback).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" @@ -458,7 +458,7 @@ mod tests { } fs::remove_dir_all(source.join("Windows")).unwrap(); - replace_boot_files(&source, &fallback).unwrap(); + replace_fallback_boot_files(&source, &fallback).unwrap(); assert!(!fallback.join(secondary).join("current.dll").exists()); filepaths(&fallback).unwrap(); } @@ -491,7 +491,7 @@ mod tests { 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_boot_files(&source, &target).unwrap_err(); + copy_fallback_for_bootstrap(&source, &target).unwrap_err(); assert!(!target.exists()); } @@ -505,11 +505,11 @@ mod tests { create_boot_files(&source, b"new"); fs::create_dir(&outside).unwrap(); unix_fs::symlink(&outside, &target).unwrap(); - assert!(replace_boot_files(&source, &target).is_err()); + 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_boot_files(&source, &target).is_err()); + assert!(copy_fallback_for_bootstrap(&source, &target).is_err()); assert!(fs::read_dir(&outside).unwrap().next().is_none()); } @@ -528,15 +528,15 @@ mod tests { .unwrap(); fs::write(fallback.join("second.efi.new"), b"partial").unwrap(); fs::write(fallback.join("lxhvloader.dll.old"), b"stale").unwrap(); - replace_boot_files(&source, &fallback).unwrap(); - replace_boot_files(&source, &fallback).unwrap(); + replace_fallback_boot_files(&source, &fallback).unwrap(); + replace_fallback_boot_files(&source, &fallback).unwrap(); filepaths(&fallback).unwrap(); for name in 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_boot_files(&source, &source).is_err()); + assert!(replace_fallback_boot_files(&source, &source).is_err()); } /// Enabled fallback policies copy all slot boot files and preserve the retained slot. diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 6cbf92cb4f..13bac02efe 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -644,7 +644,7 @@ fn copy_boot_files_for_uefi_fallback( source_esp_dir_path.display(), uefi_fallback_path.display() ); - let result = boot_files::replace_boot_files(&source_esp_dir_path, &uefi_fallback_path); + let result = boot_files::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(), @@ -682,7 +682,7 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { azla_tmp_path.display() ))?; } - let copy_result = boot_files::copy_boot_files(&boot_esp_path, &azla_tmp_path); + let copy_result = boot_files::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(), @@ -1699,7 +1699,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(); @@ -1729,7 +1729,7 @@ mod tests { } // Call the function to copy files - boot_files::replace_boot_files(from_dir.path(), to_dir.path()).unwrap(); + boot_files::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 { @@ -1765,7 +1765,7 @@ mod tests { fs::create_dir_all(&secondary).unwrap(); fs::write(secondary.join("image-specific.dll"), b"previous payload").unwrap(); - boot_files::replace_boot_files(source.path(), destination.path()).unwrap(); + boot_files::replace_fallback_boot_files(source.path(), destination.path()).unwrap(); assert_eq!( fs::read(destination.path().join(BOOT_EFI)).unwrap(), @@ -1782,7 +1782,7 @@ mod tests { 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_files::replace_boot_files(source.path(), destination.path()).unwrap(); + boot_files::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(), From f22eb3d77d76dc0e9360b898ff8494cc27cbaaeb Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 19:30:38 +0000 Subject: [PATCH 60/82] boot: explain preparation before slot cleanup Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/subsystems/esp.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 13bac02efe..132553395b 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -369,6 +369,8 @@ 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()); + // Select and validate boot files by image capability before clearing the slot. + // Preparation also cleans target-slot UKIs after source validation succeeds. let boot_files = prepare_boot_files_for_staging(temp_mount_dir, ctx, mount_point)?; // Clear esp_dir_path if it exists From f60748c99817ab6b421e74f3767d69b42519fddf Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 19:34:23 +0000 Subject: [PATCH 61/82] boot: document staging selection and MSHV validation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/subsystems/esp.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 132553395b..656cdc751b 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -461,14 +461,24 @@ fn prepare_boot_files_for_staging( let source_boot_dir = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); // Compare source metadata with the retained slot before any ESP writes. mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; + // Select shim and the main loader (GRUB or efitreeloader), plus second.efi + // for efitreeloader and grub.cfg for non-UKI images. UKI payloads are staged + // separately; MSHV-specific components are added below. let mut boot_files = generate_boot_filepaths(temp_mount_dir, is_uki, ctx.bootloader()) .context("Failed to generate boot filepaths")?; if ctx.bootloader().is_some_and(Bootloader::uses_mshv) { + // Require HvLoader.efi and lxhvloader.dll as regular files, and validate + // the optional Windows tree's structure. Reject malformed components + // before any target-slot cleanup. boot_mshv::validate_boot_components(&source_boot_dir)?; + // Add all remaining BOOT files, including nested Windows components and + // future image-specific files; the copier preserves BOOT-relative paths. for component in boot_files::filepaths(&source_boot_dir)? { let relative = component.strip_prefix(&source_boot_dir)?; let name = relative.to_str().context("Non-UTF-8 boot file path")?; - // These are selected and normalized by ordinary bootloader discovery. + // 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, From 016dc4a409841a5098a1b59e396ce5bb0c47196a Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 19:48:36 +0000 Subject: [PATCH 62/82] boot: separate capability-specific file discovery Delegate efitreeloader second-stage and MSHV component discovery to dedicated helpers. Keep capability checks and ordinary loader selection in generate_boot_filepaths, with validation before target cleanup. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/subsystems/esp.rs | 133 ++++++++++++++++++--------- 1 file changed, 90 insertions(+), 43 deletions(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 656cdc751b..544fd94762 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -458,47 +458,13 @@ fn prepare_boot_files_for_staging( mount_point: &Path, ) -> Result, Error> { let is_uki = ctx.is_uki().unstructured("UKI setting unknown")?; - let source_boot_dir = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); // Compare source metadata with the retained slot before any ESP writes. mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; // Select shim and the main loader (GRUB or efitreeloader), plus second.efi // for efitreeloader and grub.cfg for non-UKI images. UKI payloads are staged - // separately; MSHV-specific components are added below. - let mut boot_files = generate_boot_filepaths(temp_mount_dir, is_uki, ctx.bootloader()) + // separately; declared MSHV components are included by discovery. + let boot_files = generate_boot_filepaths(temp_mount_dir, is_uki, ctx.bootloader()) .context("Failed to generate boot filepaths")?; - if ctx.bootloader().is_some_and(Bootloader::uses_mshv) { - // Require HvLoader.efi and lxhvloader.dll as regular files, and validate - // the optional Windows tree's structure. Reject malformed components - // before any target-slot cleanup. - boot_mshv::validate_boot_components(&source_boot_dir)?; - // Add all remaining BOOT files, including nested Windows components and - // future image-specific files; the copier preserves BOOT-relative paths. - for component in boot_files::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; - } - boot_files.push(component); - } - } else { - ensure!( - !source_boot_dir.join("HvLoader.efi").try_exists()?, - "An MSHV image must declare COSI bootloader type 'efitreeloader-mshv-systemd-boot'" - ); - } for path in &boot_files { ensure!( fs::symlink_metadata(path)?.is_file(), @@ -780,6 +746,7 @@ fn copy_boot_files( /// The is_uki parameter indicates whether the image being processed is a UKI (Unified Kernel Image), in which /// 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, @@ -827,6 +794,7 @@ fn generate_boot_filepaths( .join(EFI_DEFAULT_BIN_RELATIVE_PATH) .join(GRUB_EFI); + // Efitreeloader uses GRUB_EFI's filename, not the GRUB noprefix binary. let selected_grub_binary_path = if !uses_efitreeloader && grub_efi_noprefix_path.exists() && grub_efi_noprefix_path.is_file() @@ -858,21 +826,68 @@ fn generate_boot_filepaths( boot_efi_path.display() ); paths.push(boot_efi_path); + let source_boot_dir = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + // Efitreeloader's second stage is required independently of MSHV. if uses_efitreeloader { - let second = temp_mount_dir - .join(EFI_DEFAULT_BIN_RELATIVE_PATH) - .join(ETL_SECOND_STAGE_EFI_FILENAME); + paths.extend(generate_efitreeloader_boot_filepaths(&source_boot_dir)?); + } + + // Add MSHV components without changing ordinary loader/config selection. + if bootloader.is_some_and(Bootloader::uses_mshv) { + paths.extend(generate_mshv_boot_filepaths(&source_boot_dir)?); + } else { ensure!( - fs::symlink_metadata(&second)?.is_file(), - "Invalid efitreeloader second stage: {}", - second.display() + !source_boot_dir.join("HvLoader.efi").try_exists()?, + "An MSHV image must declare COSI bootloader type 'efitreeloader-mshv-systemd-boot'" ); - paths.push(second); } Ok(paths) } +/// Selects and validates efitreeloader's second stage, without requiring MSHV. +fn generate_efitreeloader_boot_filepaths(source_boot_dir: &Path) -> Result, Error> { + let second = source_boot_dir.join(ETL_SECOND_STAGE_EFI_FILENAME); + ensure!( + fs::symlink_metadata(&second)?.is_file(), + "Invalid efitreeloader second stage: {}", + second.display() + ); + Ok(vec![second]) +} + +/// Validates required MSHV loaders and selects additional BOOT files for staging. +/// Supporting loaders/configs remain the responsibility of ordinary discovery. +fn generate_mshv_boot_filepaths(source_boot_dir: &Path) -> 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_files::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) +} + /// Returns the path to the ESP directory where the boot files need to be copied to. /// /// Path will be in the form of `/boot/efi/EFI/`, where `` is the install ID as determined @@ -2231,6 +2246,38 @@ mod tests { ); } + #[test] + 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 = 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); + + let ordinary = Bootloader::new(BootloaderType::SystemdBoot, None); + assert!(generate_boot_filepaths(source.path(), is_uki, Some(&ordinary)).is_err()); + + 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_unrelated_second_stage() { for is_uki in [false, true] { From ad8f36f7820e3b6f65932970865f991d8919bdf7 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 19:53:03 +0000 Subject: [PATCH 63/82] boot: document pre-staging UKI cleanup selection Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/engine/boot/uki.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index 9440729025..4e492ec7d5 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -248,7 +248,16 @@ pub fn cleanup_ukis_before_staging( Ok(()) } -/// Lists cleanup candidates without mutation. +/// 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. pub(crate) fn find_ukis_to_remove_before_staging( ctx: &EngineContext, esp_uki_directory: &Path, From 3419d0e660bd2abf923a8c7ae6fd7e6e332309ef Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 19:59:47 +0000 Subject: [PATCH 64/82] boot: show example capability-specific filepaths Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/subsystems/esp.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 544fd94762..475ae62702 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -846,6 +846,11 @@ fn generate_boot_filepaths( } /// Selects and validates efitreeloader's second stage, without requiring MSHV. +/// +/// Example output for `source_boot_dir = /image/EFI/BOOT`: +/// ```text +/// ["/image/EFI/BOOT/second.efi"] +/// ``` fn generate_efitreeloader_boot_filepaths(source_boot_dir: &Path) -> Result, Error> { let second = source_boot_dir.join(ETL_SECOND_STAGE_EFI_FILENAME); ensure!( @@ -858,6 +863,15 @@ fn generate_efitreeloader_boot_filepaths(source_boot_dir: &Path) -> 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. From 654aa0d41a0ab97cf7c7d640dd2886d71e1ae7a5 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 20:14:44 +0000 Subject: [PATCH 65/82] boot: document staging preparation contract Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/subsystems/esp.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 475ae62702..fd003be10c 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -451,7 +451,23 @@ fn copy_file_artifacts( Ok(()) } -/// Validates source boot files and prepares target UKIs before boot-file copies. +/// Prepares file-based ESP staging, validating sources before target cleanup. +/// +/// `temp_mount_dir` is the mounted COSI ESP image. `mount_point` and +/// `ctx.esp_mount_path` locate the destination ESP. Returns source paths rooted +/// at `temp_mount_dir` for the staging copier: shim/main loader, capability-specific +/// efitreeloader/MSHV files, and GRUB config for non-UKI images. UKI payloads are +/// staged separately and are not included in the returned list. +/// +/// Checks MSHV layout compatibility for A/B updates, selects files by image +/// capability, and verifies that selected sources are regular files. Only after +/// validation succeeds does UKI-mode cleanup reclaim old UKIs and addons under +/// its ownership rules, preserving the active slot and other installations. +/// This function neither copies boot files nor clears the target boot directory. +/// +/// Validation failures leave the destination ESP unchanged. Cleanup can partially +/// succeed before returning an error; subsequent copy failures do not restore +/// deleted target-slot UKIs. fn prepare_boot_files_for_staging( temp_mount_dir: &Path, ctx: &EngineContext, From d39df6a351519f2b3eec0bbc96ac2dbc72809607 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 20:24:16 +0000 Subject: [PATCH 66/82] boot: clarify MSHV bootstrap validation scope Rename the initialization validator and document marker detection, component integrity checks and BOOT-driven validation of optional AZLA. Preserve existing behavior. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/engine/boot/mshv.rs | 27 ++++++++++++++++++++++---- crates/trident/src/init/acl/mod.rs | 2 +- crates/trident/src/init/offline/mod.rs | 2 +- crates/trident/src/subsystems/esp.rs | 4 ++-- 4 files changed, 27 insertions(+), 8 deletions(-) diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 43c901d46a..1a8b598ecb 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -11,7 +11,13 @@ use super::files; const MSHV_BOOT_FILES: &[&str] = &["HvLoader.efi", "lxhvloader.dll"]; const MSHV_BOOT_COMPONENTS_DIR: &str = "Windows"; -/// Detects MSHV boot components and validates their required loader files. +/// 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() @@ -30,8 +36,13 @@ pub(crate) fn has_slot_mshv_boot_components(boot_dir: &Path) -> Result Result<(), Error> { for name in MSHV_BOOT_FILES { let path = boot_dir.join(name); @@ -53,8 +64,16 @@ pub(crate) fn validate_boot_components(boot_dir: &Path) -> Result<(), Error> { Ok(()) } -/// Validates discovered installed MSHV components before initializing Host Status. -pub(crate) fn validate_installed_boot_files(esp: &Path) -> Result<(), Error> { +/// Validates MSHV components used to seed or adopt the initial AZLA slot. +/// +/// MSHV markers in EFI/BOOT trigger fallback validation and, if EFI/AZLA already +/// exists, validation of its required loaders and optional Windows tree. A missing +/// AZLA is left for the caller to bootstrap. Without BOOT markers, this check +/// returns without inspecting AZLA. +/// +/// This is read-only and limited to BOOT/AZLA, not AZLB or numbered installations. +/// It checks filesystem structure, not runtime hypervisor identity. +pub(crate) fn validate_mshv_bootstrap_components(esp: &Path) -> Result<(), Error> { if has_slot_mshv_boot_components(&esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH))? { let installed = esp.join(ESP_EFI_DIRECTORY).join("AZLA"); if installed.try_exists()? { diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index 2344fe62f2..df4d056ec9 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -305,7 +305,7 @@ fn inner_initial_host_status( partition_paths, ..Default::default() }; - mshv::validate_installed_boot_files(esp_path)?; + mshv::validate_mshv_bootstrap_components(esp_path)?; Ok(host_status) } diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index 10f4ea11fb..7cf2d27f96 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -534,7 +534,7 @@ pub fn execute( "Failed to find ESP filesystem in Host Status, validation should have failed if this was the case", )))?; - mshv::validate_installed_boot_files(esp_path) + mshv::validate_mshv_bootstrap_components(esp_path) .structured(InvalidInputError::InvalidBootConfiguration) .message("Invalid installed MSHV boot components")?; esp::bootstrap_azla_from_fallback(esp_path) diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index fd003be10c..5bbd25e185 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -2010,7 +2010,7 @@ mod tests { fs::remove_file(azla.join("lxhvloader.dll")).unwrap(); bootstrap_azla_from_fallback(esp.path()).unwrap(); assert!(!azla.join("lxhvloader.dll").exists()); - assert!(boot_mshv::validate_installed_boot_files(esp.path()).is_err()); + assert!(boot_mshv::validate_mshv_bootstrap_components(esp.path()).is_err()); } /// Failed source validation leaves AZLA unpublished and permits a clean retry. @@ -2062,7 +2062,7 @@ mod tests { fs::create_dir_all(&boot).unwrap(); fs::write(boot.join(BOOT_EFI), "shim").unwrap(); fs::write(boot.join("HvLoader.efi"), "loader").unwrap(); - boot_mshv::validate_installed_boot_files(esp.path()).unwrap_err(); + boot_mshv::validate_mshv_bootstrap_components(esp.path()).unwrap_err(); assert!(!azla.exists()); assert_eq!(fs::read_to_string(boot.join(BOOT_EFI)).unwrap(), "shim"); } From 9366de6f74e6417f7ee481afc38f13103c166730 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 20:30:46 +0000 Subject: [PATCH 67/82] boot: document runtime MSHV validation semantics Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/engine/mshv.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs index bdc9b65183..8aa5d2494f 100644 --- a/crates/trident/src/engine/mshv.rs +++ b/crates/trident/src/engine/mshv.rs @@ -10,7 +10,15 @@ use super::boot; const MSHV_DEVICE_PATH: &str = "/dev/mshv"; -/// Calls the identity hook only when the MSHV device is present. +/// Runs the expected-slot identity hook when /dev/mshv reports as present. +/// +/// `expected_volume` selects the A/B slot for `install_index`; None selects the +/// EFI/BOOT fallback. A missing or uninspectable device path skips the check +/// successfully. When invoked, an identity-hook error propagates unchanged. +/// +/// The identity hook is currently an assume-success stub. Ok means the check was +/// skipped or the stub accepted it, not that the running hypervisor matches the +/// expected OS slot. This does not inspect installed ESP files. pub(crate) fn validate_active_hypervisor( install_index: usize, expected_volume: Option, @@ -20,6 +28,11 @@ pub(crate) fn validate_active_hypervisor( }) } +/// Applies a best-effort path-presence gate to an identity check. +/// +/// Path existence does not establish device type or hypervisor identity. +/// Missing/uninspectable paths return success without invoking `check`; +/// otherwise the callback runs once and its failure is propagated. fn validate_if_mshv_present( device: &Path, check: impl FnOnce() -> Result<(), TridentError>, @@ -31,6 +44,11 @@ fn validate_if_mshv_present( Ok(()) } +/// Assume-success placeholder for verifying the running hypervisor's identity. +/// +/// Formats the expected slot/fallback directory for a warning, but does not read +/// ESP components or query the running hypervisor. Always returns Ok until an +/// actual identity comparison is implemented. fn validate_hypervisor_identity( install_index: usize, expected_volume: Option, From 631c89d31626ccea188fe96915e087b40e762dfb Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 20:47:38 +0000 Subject: [PATCH 68/82] boot: remove MSHV-specific initialization validation Use the same bootstrap structural checks for every boot type. Remove the initialization-only validator, dependent ACL plumbing and policy-specific tests; retain staging and retained-slot transition validation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- crates/trident/src/engine/boot/files.rs | 2 +- crates/trident/src/engine/boot/mshv.rs | 21 ---- crates/trident/src/init/acl/mod.rs | 148 ++++++------------------ crates/trident/src/init/offline/mod.rs | 7 +- crates/trident/src/subsystems/esp.rs | 19 +-- docs/Explanation/MSHV.md | 12 +- 6 files changed, 45 insertions(+), 164 deletions(-) diff --git a/crates/trident/src/engine/boot/files.rs b/crates/trident/src/engine/boot/files.rs index 1a6ba06adb..6570875d1d 100644 --- a/crates/trident/src/engine/boot/files.rs +++ b/crates/trident/src/engine/boot/files.rs @@ -1,6 +1,6 @@ //! Copies complete installed boot trees without interpreting their bootloader. //! -//! Image-specific completeness belongs to staging and initialization. Relocation +//! 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. diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 1a8b598ecb..4a688a01d8 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -4,8 +4,6 @@ use std::{fs, io::ErrorKind, path::Path}; use anyhow::{ensure, Context, Error}; -use trident_api::constants::{EFI_DEFAULT_BIN_RELATIVE_PATH, ESP_EFI_DIRECTORY}; - use super::files; const MSHV_BOOT_FILES: &[&str] = &["HvLoader.efi", "lxhvloader.dll"]; @@ -64,25 +62,6 @@ pub(crate) fn validate_boot_components(boot_dir: &Path) -> Result<(), Error> { Ok(()) } -/// Validates MSHV components used to seed or adopt the initial AZLA slot. -/// -/// MSHV markers in EFI/BOOT trigger fallback validation and, if EFI/AZLA already -/// exists, validation of its required loaders and optional Windows tree. A missing -/// AZLA is left for the caller to bootstrap. Without BOOT markers, this check -/// returns without inspecting AZLA. -/// -/// This is read-only and limited to BOOT/AZLA, not AZLB or numbered installations. -/// It checks filesystem structure, not runtime hypervisor identity. -pub(crate) fn validate_mshv_bootstrap_components(esp: &Path) -> Result<(), Error> { - if has_slot_mshv_boot_components(&esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH))? { - let installed = esp.join(ESP_EFI_DIRECTORY).join("AZLA"); - if installed.try_exists()? { - validate_boot_components(&installed)?; - } - } - Ok(()) -} - #[cfg(test)] pub(crate) const FILES: &[&str] = &[ "bootx64.efi", diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index df4d056ec9..deb9e1c45a 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -8,7 +8,6 @@ use log::{trace, warn}; use uuid::Uuid; use osutils::{ - container, lsblk::{self, BlockDevice}, osrelease::OsRelease, sfdisk::SfDisk, @@ -20,13 +19,10 @@ use trident_api::{ MountOptions, MountPoint, Partition, PartitionSize, PartitionTableType, PartitionType, Storage, VerityDevice, }, - error::TridentResultExt, status::{AbVolumeSelection, HostStatus, ServicingState}, BlockDeviceId, }; -use crate::engine::boot::mshv; - const ACL_ESP_MOUNT_POINT: &str = "/boot"; /// Returns whether the host is running the ACL image. @@ -61,7 +57,6 @@ impl<'a> ExpectedPartition<'a> { /// the expectations of the ACL image layout, and returns a HostStatus /// representing the current state of the host. This will be used to /// initialize the Trident datastore if it has not been created yet. -/// Validates any detected MSHV boot components without modifying the ESP. pub fn initial_host_status() -> Result { let blk_devices = lsblk::list().context("Failed to run lsblk")?; let root_blk_device = blk_devices @@ -79,20 +74,16 @@ pub fn initial_host_status() -> Result { root_blk_device.device_path().display() ))?; - let esp_path = container::get_host_relative_path(PathBuf::from(ACL_ESP_MOUNT_POINT)) - .unstructured("Failed to resolve ACL ESP path")?; - inner_initial_host_status(&disk_information, &root_blk_device, &esp_path) + inner_initial_host_status(&disk_information, &root_blk_device) } /// Internal function that does much of the work of creating the /// initial ACL HostStatus, separated from the code that gets the /// Host's current disk information. This allows for easier testing /// of the HostStatus creation logic. -/// Rejects incomplete MSHV boot components without modifying the ESP. fn inner_initial_host_status( disk_information: &SfDisk, root_blk_device: &BlockDevice, - esp_path: &Path, ) -> Result { let disk_name = "disk-0".to_string(); // Construct the HostStatus disk UUID struct @@ -233,7 +224,7 @@ fn inner_initial_host_status( }); } - let host_status = HostStatus { + Ok(HostStatus { spec: HostConfiguration { storage: Storage { disks: vec![Disk { @@ -304,18 +295,14 @@ fn inner_initial_host_status( disk_uuids, partition_paths, ..Default::default() - }; - mshv::validate_mshv_bootstrap_components(esp_path)?; - Ok(host_status) + }) } #[cfg(test)] mod tests { use super::*; - use std::{fs, str::FromStr}; - - use tempfile::TempDir; + use std::str::FromStr; use osutils::{ lsblk::{BlockDevice, BlockDeviceType, PartitionTableType}, @@ -323,8 +310,6 @@ mod tests { }; use sysdefs::{osuuid::OsUuid, partition_types::DiscoverablePartitionType}; - use crate::engine::boot::mshv::FILES; - enum TestPartitions { Correct, MissingOne, @@ -479,57 +464,6 @@ mod tests { } } - /// Creates complete BOOT files with MSHV boot components for discovery tests. - fn create_mshv_boot_files(esp_path: &Path) { - for name in FILES { - let path = esp_path.join("EFI/BOOT").join(name); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, b"payload").unwrap(); - } - } - - /// MSHV discovery needs no configuration flag and leaves AZLA untouched. - #[test] - fn initial_host_status_accepts_slot_mshv_without_opt_in() { - let esp = TempDir::new().unwrap(); - let disk = create_sfdisk("EFI-SYSTEM", TestPartitions::Correct); - let device = create_blk_device(); - let ordinary = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); - - fs::create_dir_all(esp.path().join("EFI/BOOT")).unwrap(); - fs::write(esp.path().join("EFI/BOOT/bootx64.efi"), b"shim").unwrap(); - fs::write( - esp.path().join("EFI/HvLoader.efi"), - b"legacy shared payload", - ) - .unwrap(); - let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); - assert_eq!(status.spec, ordinary.spec); - - create_mshv_boot_files(esp.path()); - let status = inner_initial_host_status(&disk, &device, esp.path()).unwrap(); - assert_eq!(status.spec, ordinary.spec); - assert!(!esp.path().join("EFI/AZLA").exists()); - } - - /// Incomplete MSHV boot components fail discovery without creating AZLA. - #[test] - fn initial_host_status_rejects_incomplete_slot_mshv_boot_components() { - let esp = TempDir::new().unwrap(); - create_mshv_boot_files(esp.path()); - fs::remove_file(esp.path().join("EFI/BOOT/HvLoader.efi")).unwrap(); - let error = inner_initial_host_status( - &create_sfdisk("EFI-SYSTEM", TestPartitions::Correct), - &create_blk_device(), - esp.path(), - ) - .unwrap_err(); - assert!(error - .to_string() - .contains("Missing MSHV boot component: HvLoader.efi")); - assert!(!esp.path().join("EFI/AZLA").exists()); - } - fn create_blk_device() -> BlockDevice { BlockDevice { name: "/dev/sda".into(), @@ -541,14 +475,13 @@ mod tests { } } - /// Ordinary ACL discovery needs no MSHV boot components. + /// Derives ACL Host Status from partition metadata without inspecting boot files. #[test] fn test_inner_initial_host_status_success() { let sfdisk = create_sfdisk("efi-system", TestPartitions::Correct); let blkdevice = create_blk_device(); // Run - let init_host_status = - inner_initial_host_status(&sfdisk, &blkdevice, TempDir::new().unwrap().path()).unwrap(); + let init_host_status = inner_initial_host_status(&sfdisk, &blkdevice).unwrap(); init_host_status.spec.validate().unwrap(); @@ -590,8 +523,7 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::Correct); let blkdevice = create_blk_device(); - let init_host_status = - inner_initial_host_status(&sfdisk, &blkdevice, TempDir::new().unwrap().path()).unwrap(); + let init_host_status = inner_initial_host_status(&sfdisk, &blkdevice).unwrap(); init_host_status.spec.validate().unwrap(); let volume_pairs = &init_host_status @@ -612,8 +544,7 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::WithHashSigPair); let blkdevice = create_blk_device(); - let init_host_status = - inner_initial_host_status(&sfdisk, &blkdevice, TempDir::new().unwrap().path()).unwrap(); + let init_host_status = inner_initial_host_status(&sfdisk, &blkdevice).unwrap(); init_host_status.spec.validate().unwrap(); let partitions = &init_host_status.spec.storage.disks[0].partitions; @@ -648,8 +579,7 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::WithHashSigPartial); let blkdevice = create_blk_device(); - let init_host_status = - inner_initial_host_status(&sfdisk, &blkdevice, TempDir::new().unwrap().path()).unwrap(); + let init_host_status = inner_initial_host_status(&sfdisk, &blkdevice).unwrap(); init_host_status.spec.validate().unwrap(); let volume_pairs = &init_host_status @@ -663,40 +593,34 @@ mod tests { assert!(volume_pairs.iter().all(|p| p.id != "usr-hash-sig")); } - /// Unexpected ESP labels fail before MSHV boot component discovery. + /// Unexpected ESP labels fail Host Status derivation. #[test] fn test_inner_initial_host_status_unexpected_part_name() { let wrong_label = "wrong-label"; let unexpected_label = create_sfdisk(wrong_label, TestPartitions::Correct); let blkdevice = create_blk_device(); // Run - assert!(inner_initial_host_status( - &unexpected_label, - &blkdevice, - TempDir::new().unwrap().path() - ) - .unwrap_err() - .root_cause() - .to_string() - .contains(&format!( - "Unexpected partition label '{}' found on root disk", - wrong_label - ))); + assert!(inner_initial_host_status(&unexpected_label, &blkdevice) + .unwrap_err() + .root_cause() + .to_string() + .contains(&format!( + "Unexpected partition label '{}' found on root disk", + wrong_label + ))); } - /// Missing required partitions must be rejected before ESP discovery. + /// Missing required partitions must be rejected during Host Status derivation. #[test] fn test_inner_initial_host_status_missing_part() { let sfdisk = create_sfdisk("efi-system", TestPartitions::MissingOne); let blkdevice = create_blk_device(); // Run - assert!( - inner_initial_host_status(&sfdisk, &blkdevice, TempDir::new().unwrap().path()) - .unwrap_err() - .root_cause() - .to_string() - .contains("Missing partition labels found on root disk") - ); + assert!(inner_initial_host_status(&sfdisk, &blkdevice) + .unwrap_err() + .root_cause() + .to_string() + .contains("Missing partition labels found on root disk")); } /// Unrecognized partitions must not be silently adopted. @@ -705,13 +629,11 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::ExtraOne); let blkdevice = create_blk_device(); // Run - assert!( - inner_initial_host_status(&sfdisk, &blkdevice, TempDir::new().unwrap().path()) - .unwrap_err() - .root_cause() - .to_string() - .contains("Unexpected partition label 'extra-one' found on root disk") - ); + assert!(inner_initial_host_status(&sfdisk, &blkdevice) + .unwrap_err() + .root_cause() + .to_string() + .contains("Unexpected partition label 'extra-one' found on root disk")); } /// Duplicate labels cannot produce an ambiguous HostStatus. @@ -720,12 +642,10 @@ mod tests { let sfdisk = create_sfdisk("efi-system", TestPartitions::Duplicate); let blkdevice = create_blk_device(); // Run - assert!( - inner_initial_host_status(&sfdisk, &blkdevice, TempDir::new().unwrap().path()) - .unwrap_err() - .root_cause() - .to_string() - .contains("Multiple identical partition labels found on root disk: 'usr-a'") - ); + assert!(inner_initial_host_status(&sfdisk, &blkdevice) + .unwrap_err() + .root_cause() + .to_string() + .contains("Multiple identical partition labels found on root disk: 'usr-a'")); } } diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index 7cf2d27f96..bb4d94d763 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -29,7 +29,7 @@ use trident_api::{ }; use uuid::Uuid; -use crate::{datastore::DataStore, engine::boot::mshv, subsystems::esp}; +use crate::{datastore::DataStore, subsystems::esp}; #[derive(Clone, Debug, serde::Deserialize)] struct PrismPartition { @@ -457,7 +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 from the installed fallback, validating any detected MSHV boot components. +/// Seeds a missing AZLA by copying the installed fallback boot tree. pub fn execute( hs_path: Option<&Path>, lazy_partitions: &[String], @@ -534,9 +534,6 @@ pub fn execute( "Failed to find ESP filesystem in Host Status, validation should have failed if this was the case", )))?; - mshv::validate_mshv_bootstrap_components(esp_path) - .structured(InvalidInputError::InvalidBootConfiguration) - .message("Invalid installed MSHV boot components")?; esp::bootstrap_azla_from_fallback(esp_path) .structured(InvalidInputError::InvalidBootConfiguration) .message("Failed to bootstrap AZLA from fallback")?; diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 5bbd25e185..2894322d7e 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -653,8 +653,8 @@ fn copy_boot_files_for_uefi_fallback( /// 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; image-specific -/// completeness checks belong to initialization, not tree relocation. +/// 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); @@ -2010,7 +2010,6 @@ mod tests { fs::remove_file(azla.join("lxhvloader.dll")).unwrap(); bootstrap_azla_from_fallback(esp.path()).unwrap(); assert!(!azla.join("lxhvloader.dll").exists()); - assert!(boot_mshv::validate_mshv_bootstrap_components(esp.path()).is_err()); } /// Failed source validation leaves AZLA unpublished and permits a clean retry. @@ -2053,20 +2052,6 @@ mod tests { } } - /// Incomplete marked fallback cannot publish AZLA. - #[test] - fn test_initialization_rejects_incomplete_mshv_before_bootstrap() { - 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"); - fs::create_dir_all(&boot).unwrap(); - fs::write(boot.join(BOOT_EFI), "shim").unwrap(); - fs::write(boot.join("HvLoader.efi"), "loader").unwrap(); - boot_mshv::validate_mshv_bootstrap_components(esp.path()).unwrap_err(); - assert!(!azla.exists()); - assert_eq!(fs::read_to_string(boot.join(BOOT_EFI)).unwrap(), "shim"); - } - /// Validates that copy_boot_files() correctly copies boot files from temp_mount_dir to esp_dir #[test] fn test_copy_boot_files_without_noprefix() { diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index 888e87deb8..ebb19b4d70 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -99,10 +99,10 @@ 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 validates detected MSHV loader files before seeding AZLA -and persisting the discovered HostStatus. Legacy shared files outside BOOT -do not establish slot-owned mode. Bootstrap copies the complete BOOT tree -without interpreting its bootloader; an existing AZLA is never refreshed. +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 never refreshed. Legacy shared files outside +BOOT do not establish slot-owned mode. ## Updates, Fallback, and Rollback @@ -147,8 +147,8 @@ 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 validates detected MSHV -boot components and seeds AZLA when needed. +not use this file-copy path. Offline initialization seeds AZLA when needed, +without MSHV-specific completeness checks. ### Changing the Boot Layout From fbbe51a26920bf4c2ef48818252a9a7ddef348f8 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 20:59:02 +0000 Subject: [PATCH 69/82] boot: rename file helpers to boot_tree Update module references and remove added ACL test comments. No behavior changes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- .../src/engine/boot/{files.rs => boot_tree.rs} | 0 crates/trident/src/engine/boot/mod.rs | 2 +- crates/trident/src/engine/boot/mshv.rs | 4 ++-- crates/trident/src/init/acl/mod.rs | 5 ----- crates/trident/src/subsystems/esp.rs | 14 +++++++------- 5 files changed, 10 insertions(+), 15 deletions(-) rename crates/trident/src/engine/boot/{files.rs => boot_tree.rs} (100%) diff --git a/crates/trident/src/engine/boot/files.rs b/crates/trident/src/engine/boot/boot_tree.rs similarity index 100% rename from crates/trident/src/engine/boot/files.rs rename to crates/trident/src/engine/boot/boot_tree.rs diff --git a/crates/trident/src/engine/boot/mod.rs b/crates/trident/src/engine/boot/mod.rs index d02e4107b8..be03f09626 100644 --- a/crates/trident/src/engine/boot/mod.rs +++ b/crates/trident/src/engine/boot/mod.rs @@ -11,7 +11,7 @@ use crate::engine::Subsystem; use super::EngineContext; -pub(crate) mod files; +pub(crate) mod boot_tree; pub(super) mod grub; pub(crate) mod mshv; pub mod uki; diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 4a688a01d8..93220eec2d 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -4,7 +4,7 @@ use std::{fs, io::ErrorKind, path::Path}; use anyhow::{ensure, Context, Error}; -use super::files; +use super::boot_tree; const MSHV_BOOT_FILES: &[&str] = &["HvLoader.efi", "lxhvloader.dll"]; const MSHV_BOOT_COMPONENTS_DIR: &str = "Windows"; @@ -54,7 +54,7 @@ pub(crate) fn validate_boot_components(boot_dir: &Path) -> Result<(), Error> { let windows = boot_dir.join(MSHV_BOOT_COMPONENTS_DIR); match fs::symlink_metadata(&windows) { Ok(_) => { - files::filepaths(&windows)?; + boot_tree::filepaths(&windows)?; } Err(error) if error.kind() == ErrorKind::NotFound => {} Err(error) => return Err(error).context("Failed to inspect MSHV boot component directory"), diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index deb9e1c45a..8d5370f4f7 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -475,7 +475,6 @@ mod tests { } } - /// Derives ACL Host Status from partition metadata without inspecting boot files. #[test] fn test_inner_initial_host_status_success() { let sfdisk = create_sfdisk("efi-system", TestPartitions::Correct); @@ -593,7 +592,6 @@ mod tests { assert!(volume_pairs.iter().all(|p| p.id != "usr-hash-sig")); } - /// Unexpected ESP labels fail Host Status derivation. #[test] fn test_inner_initial_host_status_unexpected_part_name() { let wrong_label = "wrong-label"; @@ -610,7 +608,6 @@ mod tests { ))); } - /// Missing required partitions must be rejected during Host Status derivation. #[test] fn test_inner_initial_host_status_missing_part() { let sfdisk = create_sfdisk("efi-system", TestPartitions::MissingOne); @@ -623,7 +620,6 @@ mod tests { .contains("Missing partition labels found on root disk")); } - /// Unrecognized partitions must not be silently adopted. #[test] fn test_inner_initial_host_status_extra_part() { let sfdisk = create_sfdisk("efi-system", TestPartitions::ExtraOne); @@ -636,7 +632,6 @@ mod tests { .contains("Unexpected partition label 'extra-one' found on root disk")); } - /// Duplicate labels cannot produce an ambiguous HostStatus. #[test] fn test_inner_initial_host_status_duplicate_part() { let sfdisk = create_sfdisk("efi-system", TestPartitions::Duplicate); diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 2894322d7e..79ec506ee6 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -33,7 +33,7 @@ use trident_api::{ use crate::{ engine::{ boot::{ - self, files as boot_files, mshv as boot_mshv, uki, ESP_EXTRACTION_DIRECTORY, + self, boot_tree, mshv as boot_mshv, uki, ESP_EXTRACTION_DIRECTORY, ESP_EXTRACTION_DIRECTORY_MODE, }, EngineContext, Subsystem, @@ -638,7 +638,7 @@ fn copy_boot_files_for_uefi_fallback( source_esp_dir_path.display(), uefi_fallback_path.display() ); - let result = boot_files::replace_fallback_boot_files(&source_esp_dir_path, &uefi_fallback_path); + 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(), @@ -676,7 +676,7 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { azla_tmp_path.display() ))?; } - let copy_result = boot_files::copy_fallback_for_bootstrap(&boot_esp_path, &azla_tmp_path); + 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(), @@ -895,7 +895,7 @@ fn generate_mshv_boot_filepaths(source_boot_dir: &Path) -> Result, 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_files::filepaths(source_boot_dir)? { + 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. @@ -1786,7 +1786,7 @@ mod tests { } // Call the function to copy files - boot_files::replace_fallback_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 { @@ -1822,7 +1822,7 @@ mod tests { fs::create_dir_all(&secondary).unwrap(); fs::write(secondary.join("image-specific.dll"), b"previous payload").unwrap(); - boot_files::replace_fallback_boot_files(source.path(), destination.path()).unwrap(); + boot_tree::replace_fallback_boot_files(source.path(), destination.path()).unwrap(); assert_eq!( fs::read(destination.path().join(BOOT_EFI)).unwrap(), @@ -1839,7 +1839,7 @@ mod tests { 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_files::replace_fallback_boot_files(source.path(), destination.path()).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(), From da1499ec4cdfa9df4c9329d8b9a18825eb282022 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 21:03:58 +0000 Subject: [PATCH 70/82] docs: clarify MSHV validation and failure boundaries Distinguish bootstrap from fallback replacement, document target-UKI cleanup and describe the best-effort assume-success identity hook precisely. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- docs/Explanation/MSHV.md | 48 +++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index ebb19b4d70..6d1e7d1b7e 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -70,9 +70,11 @@ EFI/ 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 preserves all additional -BOOT files and subdirectories, including nested `Windows` components, rather -than imposing an exhaustive filename list. UKI handling is selected separately. +`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 @@ -101,8 +103,8 @@ 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 never refreshed. Legacy shared files outside -BOOT do not establish slot-owned mode. +completeness. An existing AZLA is neither inspected nor refreshed. +Legacy shared files outside BOOT do not establish slot-owned mode. ## Updates, Fallback, and Rollback @@ -111,12 +113,14 @@ 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. +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. Destination-only entries inside the -owned boot directory are retired; other slots and ESP directories are untouched. +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 @@ -134,11 +138,12 @@ Links, special files and source names ending in `.new` or `.old` are rejected. | --- | --- | --- | | `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` | Trident does not populate BOOT. | No fallback copy is performed. | +| `disabled` | BOOT is left unchanged. | No fallback copy is performed. | Rollback selects the retained OS slot and its corresponding MSHV boot components. -A separate hypervisor-validation failure state supports automatic recovery -without classifying an identity failure as a user health-check failure. +If a trial A/B hypervisor-identity check fails, Trident records `CommitFailed` +and requests a reboot to recover the retained OS, rather than treating it as +a user health-check failure. ## Current Limitations @@ -153,15 +158,18 @@ without MSHV-specific completeness checks. ### Changing the Boot Layout A/B staging 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. +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 currently assumes success**, meaning that the -running hypervisor matches the MSHV boot components in the active OS slot's -`EFI/AZLA` or `EFI/AZLB` directory. 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. +**Hypervisor identity validation currently assumes success.** A best-effort +check for `/dev/mshv` gates a placeholder that logs the expected slot or +fallback directory and returns success. A missing or uninspectable device +path skips the placeholder successfully. No ESP files are inspected. + +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. From 4cfbf083f02945d1b6a09a81ba46dc509ffe9e64 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 21:07:04 +0000 Subject: [PATCH 71/82] docs: scope MSHV explanation to its bootloader type Identify the COSI type and Rust enum up front, and scope the boot-chain comparison to that implementation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- docs/Explanation/MSHV.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index 6d1e7d1b7e..c1b1c79068 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -1,15 +1,20 @@ # 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. Other MSHV bootloader chains may +have different requirements. + 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 MSHV Boot Differs +## How This Boot Chain Differs -In an ordinary UKI-based image, shim starts systemd-boot, which loads the -selected Unified Kernel Image (UKI). An MSHV image adds +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: From 77bf521bf20278715eae3feeb2af571959d2d6f2 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Tue, 17 Nov 2026 21:08:49 +0000 Subject: [PATCH 72/82] docs: remove MSHV boot-chain qualifier Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 94d111c9-5b81-4784-9189-d5145b379318 --- docs/Explanation/MSHV.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index c1b1c79068..c94569cc7b 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -2,8 +2,7 @@ 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. Other MSHV bootloader chains may -have different requirements. +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 From d5559382f65a975b8825eafeb709a1d091bb82e9 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 17:29:45 +0000 Subject: [PATCH 73/82] Document pre-refresh fallback health-check coverage Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9785dfd5-6919-4af4-a4ec-1c9a74f3918a --- tests/e2e_tests/helpers/uefi_fallback_validation_script.txt | 3 +++ 1 file changed, 3 insertions(+) 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")" From 2889c5a84214b08c38268a86052215316b178d9d Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 18:02:49 +0000 Subject: [PATCH 74/82] Simplify MSHV servicing after review Validate layout transitions before staging and inline single-use helpers. Remove the placeholder hypervisor check and unused failure-state plumbing. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 88854ec6-204f-40de-bbfe-03a7ab8052b0 --- crates/sysdefs/src/acl.rs | 5 +- crates/trident-client/src/preview.rs | 1 - crates/trident-client/src/protocol.rs | 1 - crates/trident-client/src/tests.rs | 4 - crates/trident/src/engine/boot/boot_tree.rs | 15 +- .../src/engine/manual_rollback/utils.rs | 26 +-- crates/trident/src/engine/mod.rs | 1 - crates/trident/src/engine/mshv.rs | 113 ------------ crates/trident/src/engine/rollback.rs | 143 ++------------- crates/trident/src/init/acl/mod.rs | 5 +- crates/trident/src/lib.rs | 24 +-- .../src/server/tridentserver/datastore.rs | 5 - crates/trident/src/subsystems/esp.rs | 166 +++--------------- crates/trident/src/subsystems/esp/mshv.rs | 74 +++++--- crates/trident_api/src/error.rs | 6 - crates/trident_api/src/status.rs | 22 --- docs/Explanation/MSHV.md | 11 +- proto/trident/v1preview/status_service.proto | 2 - 18 files changed, 113 insertions(+), 511 deletions(-) delete mode 100644 crates/trident/src/engine/mshv.rs 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/trident-client/src/preview.rs b/crates/trident-client/src/preview.rs index 04946a60d7..dddb12829a 100644 --- a/crates/trident-client/src/preview.rs +++ b/crates/trident-client/src/preview.rs @@ -49,7 +49,6 @@ pub enum ServicingState { ManualRollbackAbFinalized, Provisioned, AbUpdateHealthCheckFailed, - CommitFailed, Unknown(i32), } diff --git a/crates/trident-client/src/protocol.rs b/crates/trident-client/src/protocol.rs index a3a3bc3003..e6ffe25bd2 100644 --- a/crates/trident-client/src/protocol.rs +++ b/crates/trident-client/src/protocol.rs @@ -308,7 +308,6 @@ pub(crate) fn decode_servicing_state(state: i32) -> ServicingState { Ok(ProtoServicingState::UpdateAbHealthCheckFailed) => { ServicingState::AbUpdateHealthCheckFailed } - Ok(ProtoServicingState::CommitFailed) => ServicingState::CommitFailed, Err(_) => ServicingState::Unknown(state), } } diff --git a/crates/trident-client/src/tests.rs b/crates/trident-client/src/tests.rs index cad3ee0149..07d4036073 100644 --- a/crates/trident-client/src/tests.rs +++ b/crates/trident-client/src/tests.rs @@ -1490,10 +1490,6 @@ async fn preview_status_validation_and_rollback_use_domain_types() { #[tokio::test] async fn preview_status_enums_preserve_known_unspecified_and_unknown_values() { let servicing_states = [ - ( - ProtoServicingState::CommitFailed as i32, - ServicingState::CommitFailed, - ), ( ProtoServicingState::Provisioned as i32, ServicingState::Provisioned, diff --git a/crates/trident/src/engine/boot/boot_tree.rs b/crates/trident/src/engine/boot/boot_tree.rs index 6570875d1d..4f3847b3a7 100644 --- a/crates/trident/src/engine/boot/boot_tree.rs +++ b/crates/trident/src/engine/boot/boot_tree.rs @@ -15,17 +15,13 @@ use anyhow::{ensure, Context, Error}; /// Validates the whole tree, including empty directories, and collects relative file paths. /// `temporary` permits replacement suffixes in destinations left by interrupted work. -fn scan( - root: &Path, - directory: &Path, - temporary: bool, - files: &mut Vec, -) -> Result<(), Error> { +fn scan(root: &Path, directory: &Path, temporary: bool) -> Result, Error> { ensure!( fs::symlink_metadata(directory)?.is_dir(), "Invalid boot directory: {}", directory.display() ); + let mut files = Vec::new(); for entry in fs::read_dir(directory)? { let entry = entry?; let path = entry.path(); @@ -37,7 +33,7 @@ fn scan( ); let kind = entry.file_type()?; if kind.is_dir() { - scan(root, &path, temporary, files)?; + files.extend(scan(root, &path, temporary)?); } else { ensure!( kind.is_file(), @@ -47,13 +43,12 @@ fn scan( files.push(path.strip_prefix(root)?.to_path_buf()); } } - Ok(()) + Ok(files) } /// Returns sorted root-relative file paths; empty directories are validated but not listed. fn boot_files(root: &Path, temporary: bool) -> Result, Error> { - let mut files = Vec::new(); - scan(root, root, temporary, &mut files)?; + let mut files = scan(root, root, temporary)?; files.sort(); Ok(files) } diff --git a/crates/trident/src/engine/manual_rollback/utils.rs b/crates/trident/src/engine/manual_rollback/utils.rs index 962d6f7d53..0ed7ee721c 100644 --- a/crates/trident/src/engine/manual_rollback/utils.rs +++ b/crates/trident/src/engine/manual_rollback/utils.rs @@ -352,7 +352,7 @@ impl ManualRollbackContext { current_operation.kind = OperationKind::RuntimeManualRollback; current_operation.operation_host_status = Some(current_hs.clone()); } - ServicingState::AbUpdateHealthCheckFailed | ServicingState::CommitFailed => { + ServicingState::AbUpdateHealthCheckFailed => { // Do not offer the rejected candidate as a rollback target. current_operation.kind = OperationKind::AbUpdateAutoRollback; trace!("Detected AbUpdateAutoRollback operation, ending parsing here."); @@ -1027,30 +1027,6 @@ mod tests { rollback_context_testing(&host_status_list, "Validate A/B update health check failed"); } - /// Hypervisor recovery bounds history like health-check recovery. - #[test] - fn test_ab_update_hypervisor_check_failed() { - let host_status_list = vec![ - inter(None, CI_FINAL, MIN), - inter(None, CI_FINAL, MIN), - prov(VOL_A, false, vec![], MIN), - inter(VOL_A, AB_STAGE, MIN), - inter(VOL_A, AB_FINAL, MIN), - inter(VOL_A, ServicingState::CommitFailed, MIN), - prov_e( - VOL_A, - false, - vec![], - MIN, - Some("hypervisor failure".to_string()), - ), - ]; - rollback_context_testing( - &host_status_list, - "Validate hypervisor auto-rollback history", - ); - } - #[test] fn test_ab_update_encryption() { let host_status_list = vec![ diff --git a/crates/trident/src/engine/mod.rs b/crates/trident/src/engine/mod.rs index 7d035a6724..a1bca74146 100644 --- a/crates/trident/src/engine/mod.rs +++ b/crates/trident/src/engine/mod.rs @@ -40,7 +40,6 @@ mod clean_install; mod context; mod kexec; pub mod manual_rollback; -pub(crate) mod mshv; mod newroot; pub mod provisioning_network; pub mod rollback; diff --git a/crates/trident/src/engine/mshv.rs b/crates/trident/src/engine/mshv.rs deleted file mode 100644 index 8aa5d2494f..0000000000 --- a/crates/trident/src/engine/mshv.rs +++ /dev/null @@ -1,113 +0,0 @@ -use std::path::Path; - -use log::warn; - -use trident_api::{ - constants::EFI_DEFAULT_BIN_DIRECTORY, error::TridentError, status::AbVolumeSelection, -}; - -use super::boot; - -const MSHV_DEVICE_PATH: &str = "/dev/mshv"; - -/// Runs the expected-slot identity hook when /dev/mshv reports as present. -/// -/// `expected_volume` selects the A/B slot for `install_index`; None selects the -/// EFI/BOOT fallback. A missing or uninspectable device path skips the check -/// successfully. When invoked, an identity-hook error propagates unchanged. -/// -/// The identity hook is currently an assume-success stub. Ok means the check was -/// skipped or the stub accepted it, not that the running hypervisor matches the -/// expected OS slot. This does not inspect installed ESP files. -pub(crate) fn validate_active_hypervisor( - install_index: usize, - expected_volume: Option, -) -> Result<(), TridentError> { - validate_if_mshv_present(Path::new(MSHV_DEVICE_PATH), || { - validate_hypervisor_identity(install_index, expected_volume) - }) -} - -/// Applies a best-effort path-presence gate to an identity check. -/// -/// Path existence does not establish device type or hypervisor identity. -/// Missing/uninspectable paths return success without invoking `check`; -/// otherwise the callback runs once and its failure is propagated. -fn validate_if_mshv_present( - device: &Path, - check: impl FnOnce() -> Result<(), TridentError>, -) -> Result<(), TridentError> { - // Presence is a best-effort gate, not evidence of the expected hypervisor identity. - if device.exists() { - check()?; - } - Ok(()) -} - -/// Assume-success placeholder for verifying the running hypervisor's identity. -/// -/// Formats the expected slot/fallback directory for a warning, but does not read -/// ESP components or query the running hypervisor. Always returns Ok until an -/// actual identity comparison is implemented. -fn validate_hypervisor_identity( - install_index: usize, - expected_volume: Option, -) -> Result<(), TridentError> { - let expected_directory = expected_volume - .map(|volume| boot::make_esp_dir_name(install_index, volume)) - .unwrap_or_else(|| EFI_DEFAULT_BIN_DIRECTORY.into()); - // TODO: Identify the running hypervisor and compare it with the expected OS's MSHV boot components. - warn!( - "MSHV hypervisor identity validation is not implemented; assuming success for {:?}", - expected_directory - ); - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - use std::fs; - - use tempfile::TempDir; - - use trident_api::error::{ErrorKind, ServicingError}; - - #[test] - fn missing_mshv_device_skips_identity_validation() { - let temp = TempDir::new().unwrap(); - validate_if_mshv_present(&temp.path().join("mshv"), || { - panic!("Identity validation must not run without the MSHV device") - }) - .unwrap(); - } - - #[test] - fn present_mshv_device_runs_identity_validation_and_propagates_failure() { - let temp = TempDir::new().unwrap(); - let device = temp.path().join("mshv"); - fs::write(&device, []).unwrap(); - let mut checked = false; - validate_if_mshv_present(&device, || { - checked = true; - Ok(()) - }) - .unwrap(); - assert!(checked); - - let error = validate_if_mshv_present(&device, || { - Err(TridentError::new( - ServicingError::ValidateAbActiveHypervisor { - expected_slot: "AZLB".into(), - observed_slot: Some("AZLA".into()), - }, - )) - }) - .unwrap_err(); - assert!(matches!( - error.kind(), - ErrorKind::Servicing(ServicingError::ValidateAbActiveHypervisor { .. }) - )); - } -} diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 1000eef68c..dac9192c5a 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -19,9 +19,8 @@ use trident_api::{ use crate::{ engine::{ - boot, bootentries, + bootentries, context::{EngineContext, EngineContextParams}, - mshv, storage::{encryption, verity}, }, health, @@ -35,19 +34,14 @@ pub enum BootValidationResult { ValidBootProvisioned, /// Target OS booted successfully, and the health checks failed ValidBootHealthCheckFailed(TridentError), - /// The trial OS booted, but its hypervisor failed validation and requires rollback. - InvalidHypervisor(TridentError), } /// Validates that the firmware correctly booted from the expected target OS /// image rather than rolling back, and reconciles the Host Status accordingly. /// -/// Checks the boot device and calls the identity hook when `/dev/mshv` is present. -/// The hook currently assumes success rather than verifying the running hypervisor. -/// /// 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 or hypervisor validation failures can request +/// 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)] @@ -60,10 +54,10 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result datastore.host_status().ab_active_volume, - // For AbUpdateHealthCheckFailed or CommitFailed, use + // 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 | ServicingState::CommitFailed => { + ServicingState::AbUpdateHealthCheckFailed => { match datastore.host_status().ab_active_volume { Some(AbVolumeSelection::VolumeB) => Some(AbVolumeSelection::VolumeA), Some(AbVolumeSelection::VolumeA) => Some(AbVolumeSelection::VolumeB), @@ -79,9 +73,9 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result ServicingType::AbUpdate, + ServicingState::AbUpdateFinalized | ServicingState::AbUpdateHealthCheckFailed => { + ServicingType::AbUpdate + } ServicingState::CleanInstallFinalized => ServicingType::CleanInstall, ServicingState::ManualRollbackAbFinalized => ServicingType::ManualRollbackAb, _ => ServicingType::NoActiveServicing, @@ -90,7 +84,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Result Result { - // For an A/B update whose health or hypervisor validation failed, + (false, ServicingState::AbUpdateHealthCheckFailed) => { + // 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"); @@ -198,26 +176,6 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result { - // Restore the retained OS's status, but still report the rejected update's failure. - info!("Rollback to servicing OS succeeded, setting host status from {current_servicing_state:?} to Provisioned"); - datastore.with_host_status(|host_status| { - host_status.spec = host_status.spec_old.clone(); - host_status.spec_old = Default::default(); - host_status.servicing_state = ServicingState::Provisioned; - })?; - - return Err(TridentError::new( - ServicingError::ValidateAbActiveHypervisor { - expected_slot: ctx - .get_ab_update_volume() - .map(|volume| boot::make_esp_dir_name(ctx.install_index, volume)) - .unwrap_or_default(), - observed_slot: None, - }, - )) - .message("Rollback to the retained OS succeeded after hypervisor validation failed"); - } (false, ServicingState::AbUpdateFinalized) => { // AbUpdateFinalize, when booting from incorrect device (the servicing OS), mark host status // state as Provisioned @@ -260,24 +218,6 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Result { - if state == ServicingState::AbUpdateFinalized { - let serialized = serde_yaml::to_value(&error).structured(InternalError::SerializeError)?; - datastore.with_host_status(|status| { - status.servicing_state = ServicingState::CommitFailed; - status.last_error = Some(serialized); - })?; - Ok(BootValidationResult::InvalidHypervisor(error)) - } else { - Err(error) - } -} - /// Completes the commit for AbUpdateFinalized and CleanInstallFinalized states when /// the host has booted from the expected boot device. This includes running health /// checks, updating boot order, updating the encryption pcrlock policy if needed, and @@ -863,7 +803,6 @@ mod tests { use const_format::formatcp; use maplit::btreemap; - use tempfile::TempDir; use osutils::{osrelease::OsRelease, testutils::repart::TEST_DISK_DEVICE_PATH}; use trident_api::{ @@ -876,66 +815,6 @@ mod tests { status::AbVolumeSelection, }; - /// The recovery state and original error survive reopening the datastore. - #[test] - fn hypervisor_failure_is_persisted_before_requesting_rollback() { - let temp = TempDir::new().unwrap(); - let path = temp.path().join("datastore.sqlite"); - let mut datastore = DataStore::open_or_create(&path).unwrap(); - let error = TridentError::new(ServicingError::ValidateAbActiveHypervisor { - expected_slot: "AZLB".into(), - observed_slot: Some("AZLA".into()), - }); - let expected_error = serde_yaml::to_value(&error).unwrap(); - let result = - record_hypervisor_failure(&mut datastore, ServicingState::AbUpdateFinalized, error) - .unwrap(); - assert!(matches!(result, BootValidationResult::InvalidHypervisor(_))); - assert_eq!( - datastore.host_status().servicing_state, - ServicingState::CommitFailed - ); - assert_eq!( - datastore.host_status().last_error.as_ref(), - Some(&expected_error) - ); - drop(datastore); - let datastore = DataStore::open(&path).unwrap(); - assert_eq!( - datastore.host_status().servicing_state, - ServicingState::CommitFailed - ); - assert_eq!( - datastore.host_status().last_error.as_ref(), - Some(&expected_error) - ); - } - - /// A recovery identity failure must not request another rollback. - #[test] - fn recovery_identity_failure_does_not_request_another_rollback() { - let temp = TempDir::new().unwrap(); - let mut datastore = - DataStore::open_or_create(&temp.path().join("datastore.sqlite")).unwrap(); - datastore - .with_host_status(|status| { - status.servicing_state = ServicingState::CommitFailed; - }) - .unwrap(); - let error = TridentError::new(ServicingError::ValidateAbActiveHypervisor { - expected_slot: "AZLA".into(), - observed_slot: None, - }); - assert!( - record_hypervisor_failure(&mut datastore, ServicingState::CommitFailed, error,) - .is_err() - ); - assert_eq!( - datastore.host_status().servicing_state, - ServicingState::CommitFailed - ); - } - #[test] fn test_get_expected_device_path() { let mut ctx = EngineContext { diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index 8d5370f4f7..ac7e830a92 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -12,6 +12,7 @@ use osutils::{ osrelease::OsRelease, sfdisk::SfDisk, }; +use sysdefs::acl::ACL_ESP_MOUNT_POINT; use trident_api::{ config::{ @@ -23,13 +24,11 @@ use trident_api::{ BlockDeviceId, }; -const ACL_ESP_MOUNT_POINT: &str = "/boot"; - /// 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())) + Ok(os_release.get_distro().is_acl()) } /// An expected partition on the ACL root disk, identified by label, along diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index 9341764f2c..da489ddc69 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -305,10 +305,8 @@ impl Trident { where F: FnOnce(&mut DataStore) -> Result, { - // AbUpdateHealthCheckFailed and CommitFailed are - // special cases where the last error must be preserved across failed - // recovery attempts. This keeps the original health/hypervisor failure - // visible instead of replacing it with a secondary recovery error. + // Preserve the original health-check failure across failed recovery attempts + // instead of replacing it with a secondary recovery error. debug!( "Execute and record error with servicing state: {:?} and last error: {:?}", datastore.host_status().servicing_state, @@ -316,7 +314,7 @@ impl Trident { ); let last_error_to_preserve = if matches!( datastore.host_status().servicing_state, - ServicingState::AbUpdateHealthCheckFailed | ServicingState::CommitFailed + ServicingState::AbUpdateHealthCheckFailed ) { datastore.host_status().last_error.clone() } else { @@ -614,7 +612,6 @@ impl Trident { }) } - /// Adopts untracked ACL hosts as needed, then stages/finalizes the update. pub fn update( &mut self, datastore: &mut DataStore, @@ -820,16 +817,14 @@ impl Trident { &mut self, datastore: &mut DataStore, ) -> Result<(ExitKind, ServicingType), TridentError> { - // If the host's servicing state is *Finalized, AbUpdateHealthCheckFailed, - // or CommitFailed, re-evaluate the current state of - // the host to validate either the target boot or the recovery boot. + // 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, ServicingState::CleanInstallFinalized | ServicingState::AbUpdateFinalized | ServicingState::AbUpdateHealthCheckFailed - | ServicingState::CommitFailed | ServicingState::ManualRollbackAbFinalized ) { info!( @@ -840,9 +835,9 @@ impl Trident { } let servicing_type = match servicing_state { - ServicingState::AbUpdateFinalized - | ServicingState::AbUpdateHealthCheckFailed - | ServicingState::CommitFailed => ServicingType::AbUpdate, + ServicingState::AbUpdateFinalized | ServicingState::AbUpdateHealthCheckFailed => { + ServicingType::AbUpdate + } ServicingState::CleanInstallFinalized => ServicingType::CleanInstall, ServicingState::ManualRollbackAbFinalized => ServicingType::ManualRollbackAb, _ => ServicingType::NoActiveServicing, @@ -864,8 +859,7 @@ impl Trident { } Ok((ExitKind::Done, servicing_type)) } - Ok(BootValidationResult::InvalidHypervisor(e)) - | Ok(BootValidationResult::ValidBootHealthCheckFailed(e)) => { + Ok(BootValidationResult::ValidBootHealthCheckFailed(e)) => { // The caller must reboot to complete automatic recovery. debug!("Boot validation requires rollback: {e:?}"); Ok((ExitKind::NeedsReboot, servicing_type)) diff --git a/crates/trident/src/server/tridentserver/datastore.rs b/crates/trident/src/server/tridentserver/datastore.rs index c2e0c8b877..defeae4770 100644 --- a/crates/trident/src/server/tridentserver/datastore.rs +++ b/crates/trident/src/server/tridentserver/datastore.rs @@ -50,7 +50,6 @@ mod preview { ServicingState::AbUpdateHealthCheckFailed => { ProtoServicingState::UpdateAbHealthCheckFailed } - ServicingState::CommitFailed => ProtoServicingState::CommitFailed, } } @@ -113,10 +112,6 @@ mod preview { ServicingState::AbUpdateHealthCheckFailed, ProtoServicingState::UpdateAbHealthCheckFailed, ), - ( - ServicingState::CommitFailed, - ProtoServicingState::CommitFailed, - ), ]; // Track which ServicingState variants have been tested for coverage. diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 79ec506ee6..3ef53f4981 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -369,9 +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()); - // Select and validate boot files by image capability before clearing the slot. - // Preparation also cleans target-slot UKIs after source validation succeeds. - let boot_files = prepare_boot_files_for_staging(temp_mount_dir, ctx, mount_point)?; + // 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() { @@ -451,51 +455,6 @@ fn copy_file_artifacts( Ok(()) } -/// Prepares file-based ESP staging, validating sources before target cleanup. -/// -/// `temp_mount_dir` is the mounted COSI ESP image. `mount_point` and -/// `ctx.esp_mount_path` locate the destination ESP. Returns source paths rooted -/// at `temp_mount_dir` for the staging copier: shim/main loader, capability-specific -/// efitreeloader/MSHV files, and GRUB config for non-UKI images. UKI payloads are -/// staged separately and are not included in the returned list. -/// -/// Checks MSHV layout compatibility for A/B updates, selects files by image -/// capability, and verifies that selected sources are regular files. Only after -/// validation succeeds does UKI-mode cleanup reclaim old UKIs and addons under -/// its ownership rules, preserving the active slot and other installations. -/// This function neither copies boot files nor clears the target boot directory. -/// -/// Validation failures leave the destination ESP unchanged. Cleanup can partially -/// succeed before returning an error; subsequent copy failures do not restore -/// deleted target-slot UKIs. -fn prepare_boot_files_for_staging( - temp_mount_dir: &Path, - ctx: &EngineContext, - mount_point: &Path, -) -> Result, Error> { - let is_uki = ctx.is_uki().unstructured("UKI setting unknown")?; - // Compare source metadata with the retained slot before any ESP writes. - mshv::validate_transition(ctx, &path::join_relative(mount_point, &ctx.esp_mount_path))?; - // Select shim and the main loader (GRUB or efitreeloader), plus second.efi - // for efitreeloader and grub.cfg for non-UKI images. UKI payloads are staged - // separately; declared MSHV components are included by discovery. - let boot_files = generate_boot_filepaths(temp_mount_dir, is_uki, ctx.bootloader()) - .context("Failed to generate boot filepaths")?; - for path in &boot_files { - ensure!( - fs::symlink_metadata(path)?.is_file(), - "Not a regular boot file: {}", - path.display() - ); - } - if is_uki { - // Reclaim target-slot space before copying, preserving the active slot. - // A failed copy can leave the target without its previous UKI. - uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; - } - Ok(boot_files) -} - /// Determines the source directory to copy UEFI fallback boot files from. /// This varies based on the servicing state and UEFI fallback mode. /// @@ -845,7 +804,13 @@ fn generate_boot_filepaths( let source_boot_dir = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); // Efitreeloader's second stage is required independently of MSHV. if uses_efitreeloader { - paths.extend(generate_efitreeloader_boot_filepaths(&source_boot_dir)?); + let second = source_boot_dir.join(ETL_SECOND_STAGE_EFI_FILENAME); + ensure!( + fs::symlink_metadata(&second)?.is_file(), + "Invalid efitreeloader second stage: {}", + second.display() + ); + paths.push(second); } // Add MSHV components without changing ordinary loader/config selection. @@ -858,25 +823,16 @@ fn generate_boot_filepaths( ); } + for path in &paths { + ensure!( + fs::symlink_metadata(path)?.is_file(), + "Not a regular boot file: {}", + path.display() + ); + } Ok(paths) } -/// Selects and validates efitreeloader's second stage, without requiring MSHV. -/// -/// Example output for `source_boot_dir = /image/EFI/BOOT`: -/// ```text -/// ["/image/EFI/BOOT/second.efi"] -/// ``` -fn generate_efitreeloader_boot_filepaths(source_boot_dir: &Path) -> Result, Error> { - let second = source_boot_dir.join(ETL_SECOND_STAGE_EFI_FILENAME); - ensure!( - fs::symlink_metadata(&second)?.is_file(), - "Invalid efitreeloader second stage: {}", - second.display() - ); - Ok(vec![second]) -} - /// Validates required MSHV loaders and selects additional BOOT files for staging. /// Supporting loaders/configs remain the responsibility of ordinary discovery. /// @@ -993,7 +949,7 @@ mod tests { b"unrelated GRUB binary", ) .unwrap(); - let files = prepare_boot_files_for_staging(source.path(), &ctx, esp.path()).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))); @@ -1034,20 +990,15 @@ mod tests { #[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 (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(); - prepare_boot_files_for_staging(source.path(), &ctx, esp.path()).unwrap_err(); - assert!(esp - .path() - .join(uki::UKI_DIRECTORY) - .join("vmlinuz-100-azlb1.efi") - .is_file()); + generate_boot_filepaths(source.path(), true, ctx.bootloader()).unwrap_err(); } - let (source, esp, ctx) = boot_file_staging_fixture(false, true); + let (source, _esp, ctx) = boot_file_staging_fixture(false, true); fs::create_dir( source .path() @@ -1055,7 +1006,7 @@ mod tests { .join(ETL_SECOND_STAGE_EFI_FILENAME), ) .unwrap(); - let paths = prepare_boot_files_for_staging(source.path(), &ctx, esp.path()).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))); @@ -1155,74 +1106,9 @@ mod tests { fs::write(root.join(GRUB2_CONFIG_FILENAME), b"configuration").unwrap(); } } - let ukis = esp.path().join(uki::UKI_DIRECTORY); - fs::create_dir_all(&ukis).unwrap(); - for name in ["vmlinuz-100-azla1.efi", "vmlinuz-100-azlb1.efi"] { - fs::write(ukis.join(name), b"kernel").unwrap(); - let addons = ukis.join(format!("{name}.extra.d")); - fs::create_dir(&addons).unwrap(); - fs::write(addons.join("payload.addon.efi"), b"addon").unwrap(); - } (source, esp, ctx) } - #[test] - fn test_prepare_boot_files_for_staging_skips_cleanup_for_non_uki_images() { - // MSHV and UKI are independent predicates, despite current deployment restrictions. - for is_mshv in [false, true] { - let (source, esp, ctx) = boot_file_staging_fixture(is_mshv, false); - prepare_boot_files_for_staging(source.path(), &ctx, esp.path()).unwrap(); - let ukis = esp.path().join(uki::UKI_DIRECTORY); - for name in ["vmlinuz-100-azla1.efi", "vmlinuz-100-azlb1.efi"] { - assert_eq!(fs::read(ukis.join(name)).unwrap(), b"kernel"); - assert_eq!( - fs::read(ukis.join(format!("{name}.extra.d/payload.addon.efi"))).unwrap(), - b"addon" - ); - } - } - } - - #[test] - fn test_prepare_boot_files_for_staging_cleans_target_ukis_for_uki_images() { - for is_mshv in [false, true] { - let (source, esp, ctx) = boot_file_staging_fixture(is_mshv, true); - prepare_boot_files_for_staging(source.path(), &ctx, esp.path()).unwrap(); - let ukis = esp.path().join(uki::UKI_DIRECTORY); - assert!(!ukis.join("vmlinuz-100-azlb1.efi").exists()); - assert!(!ukis.join("vmlinuz-100-azlb1.efi.extra.d").exists()); - assert_eq!( - fs::read(ukis.join("vmlinuz-100-azla1.efi")).unwrap(), - b"kernel" - ); - assert_eq!( - fs::read(ukis.join("vmlinuz-100-azla1.efi.extra.d/payload.addon.efi")).unwrap(), - b"addon" - ); - } - } - - #[test] - fn test_prepare_boot_files_for_staging_validates_source_before_cleanup() { - let (source, esp, ctx) = boot_file_staging_fixture(true, true); - fs::remove_file( - source - .path() - .join(EFI_DEFAULT_BIN_RELATIVE_PATH) - .join("lxhvloader.dll"), - ) - .unwrap(); - assert!(prepare_boot_files_for_staging(source.path(), &ctx, esp.path()).is_err()); - let ukis = esp.path().join(uki::UKI_DIRECTORY); - for name in ["vmlinuz-100-azla1.efi", "vmlinuz-100-azlb1.efi"] { - assert_eq!(fs::read(ukis.join(name)).unwrap(), b"kernel"); - assert_eq!( - fs::read(ukis.join(format!("{name}.extra.d/payload.addon.efi"))).unwrap(), - b"addon" - ); - } - } - #[test] fn test_generate_efi_bin_base_dir_path_clean_install() { // Clean install EngineContext diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index b91019ea12..0d728d713f 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -4,10 +4,11 @@ use std::path::Path; use anyhow::{anyhow, ensure, Context, Error}; +use osutils::container; use sysdefs::arch::SystemArchitecture; use trident_api::{ constants::ESP_EFI_DIRECTORY, - error::{InvalidInputError, TridentError}, + error::{InvalidInputError, ReportError, TridentError}, status::ServicingType, }; @@ -19,33 +20,43 @@ use crate::{ osimage::bootloader::Bootloader, }; -/// Enforces support restrictions for file-based deployment of MSHV images. +/// Enforces file-based MSHV support and retained-slot compatibility before staging. pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { - if ctx.is_stream_image || !ctx.bootloader().is_some_and(Bootloader::uses_mshv) { + if ctx.is_stream_image { return Ok(()); } - // The required bootloader files currently support only x86-64. - if !SystemArchitecture::current().is_x64() || !ctx.image_distro().is_acl() || !ctx.is_uki()? { - return Err(unsupported( - "Slot-owned MSHV requires an x86-64 ACL UKI image", - )); + 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(unsupported( + "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(unsupported( + "Slot-owned MSHV TPM/PCR-bound encryption is not validated", + )); + } } - if ctx - .spec - .storage - .encryption - .as_ref() - .is_some_and(|encryption| !encryption.pcrs.is_empty()) - { - return Err(unsupported( - "Slot-owned MSHV TPM/PCR-bound encryption is not validated", - )); + 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(()) } /// Rejects A/B updates that change the retained slot's MSHV layout. -pub(super) fn validate_transition(ctx: &EngineContext, esp_path: &Path) -> Result<(), Error> { +fn validate_transition(ctx: &EngineContext, esp_path: &Path) -> Result<(), Error> { if ctx.servicing_type != ServicingType::AbUpdate { return Ok(()); } @@ -84,8 +95,9 @@ mod tests { use trident_api::{config::Encryption, status::AbVolumeSelection}; use crate::{ - engine::boot::mshv::FILES, + engine::{boot::mshv::FILES, Subsystem}, osimage::{bootloader::BootloaderType, mock::MockOsImage}, + subsystems::esp::EspSubsystem, }; /// Only file-based deployment of metadata-declared MSHV images receives these restrictions. @@ -143,8 +155,19 @@ mod tests { 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 @@ -153,10 +176,17 @@ mod tests { }; ctx.bootloader = Some(Bootloader::new(bootloader_type, None)); assert_eq!( - validate_transition(&ctx, esp.path()).is_ok(), + 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(); } } } diff --git a/crates/trident_api/src/error.rs b/crates/trident_api/src/error.rs index 2c239aa510..e4fda52de0 100644 --- a/crates/trident_api/src/error.rs +++ b/crates/trident_api/src/error.rs @@ -712,12 +712,6 @@ pub enum ServicingError { hs_active_volume: String, }, - #[error("Running hypervisor does not match expected slot '{expected_slot}' (observed: {observed_slot:?})")] - ValidateAbActiveHypervisor { - expected_slot: String, - observed_slot: Option, - }, - #[error("Trident rebuild-raid validation failed")] ValidateRebuildRaid, diff --git a/crates/trident_api/src/status.rs b/crates/trident_api/src/status.rs index 6dbc216679..407714de0e 100644 --- a/crates/trident_api/src/status.rs +++ b/crates/trident_api/src/status.rs @@ -133,8 +133,6 @@ pub enum ServicingState { Provisioned, /// A/B update has been completed, the host booted into the target OS but the health checks failed. AbUpdateHealthCheckFailed, - /// Commit failed and rollback to the retained OS is required. - CommitFailed, } /// A/B volume selection. Determines which set of volumes are currently @@ -319,26 +317,6 @@ pub fn decode_host_status(mut yaml: Value) -> Result("ab-update-hypervisor-check-failed").is_err() - ); - - let health: ServicingState = serde_yaml::from_str("ab-update-health-check-failed").unwrap(); - assert_eq!(health, ServicingState::AbUpdateHealthCheckFailed); - assert_eq!( - serde_yaml::to_string(&health).unwrap().trim(), - "ab-update-health-check-failed" - ); - } - #[test] fn load_old_format() { let old_yaml = include_str!("test/preview12_host_status.yaml"); diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md index c94569cc7b..a6740f3113 100644 --- a/docs/Explanation/MSHV.md +++ b/docs/Explanation/MSHV.md @@ -145,9 +145,6 @@ Links, special files and source names ending in `.new` or `.old` are rejected. | `disabled` | BOOT is left unchanged. | No fallback copy is performed. | Rollback selects the retained OS slot and its corresponding MSHV boot components. -If a trial A/B hypervisor-identity check fails, Trident records `CommitFailed` -and requests a reboot to recover the retained OS, rather than treating it as -a user health-check failure. ## Current Limitations @@ -161,17 +158,15 @@ without MSHV-specific completeness checks. ### Changing the Boot Layout -A/B staging compares the source COSI's bootloader type with the retained +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 currently assumes success.** A best-effort -check for `/dev/mshv` gates a placeholder that logs the expected slot or -fallback directory and returns success. A missing or uninspectable device -path skips the placeholder successfully. No ESP files are inspected. +**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 diff --git a/proto/trident/v1preview/status_service.proto b/proto/trident/v1preview/status_service.proto index 9ca249c131..5cd2a97d28 100644 --- a/proto/trident/v1preview/status_service.proto +++ b/proto/trident/v1preview/status_service.proto @@ -77,8 +77,6 @@ enum ServicingState { // A/B update has been completed, the host booted into the target OS but the // health checks failed. UPDATE_AB_HEALTH_CHECK_FAILED = 11; - // Commit failed; rollback to the retained OS is required. - COMMIT_FAILED = 12; } message GetServicingStateResponse { From fe25cd0b68244c33949b84e388fc8caefc9e401b Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 18:20:58 +0000 Subject: [PATCH 75/82] Address ESP ownership and staging review feedback Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 88854ec6-204f-40de-bbfe-03a7ab8052b0 --- crates/trident/src/engine/boot/mod.rs | 1 - crates/trident/src/engine/boot/mshv.rs | 2 +- crates/trident/src/engine/boot/uki.rs | 2 +- crates/trident/src/subsystems/esp.rs | 41 ++++++++++++++----- .../boot => subsystems/esp}/boot_tree.rs | 0 5 files changed, 33 insertions(+), 13 deletions(-) rename crates/trident/src/{engine/boot => subsystems/esp}/boot_tree.rs (100%) diff --git a/crates/trident/src/engine/boot/mod.rs b/crates/trident/src/engine/boot/mod.rs index be03f09626..745e2a7539 100644 --- a/crates/trident/src/engine/boot/mod.rs +++ b/crates/trident/src/engine/boot/mod.rs @@ -11,7 +11,6 @@ use crate::engine::Subsystem; use super::EngineContext; -pub(crate) mod boot_tree; pub(super) mod grub; pub(crate) mod mshv; pub mod uki; diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 93220eec2d..91fd135335 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -4,7 +4,7 @@ use std::{fs, io::ErrorKind, path::Path}; use anyhow::{ensure, Context, Error}; -use super::boot_tree; +use crate::subsystems::esp::boot_tree; const MSHV_BOOT_FILES: &[&str] = &["HvLoader.efi", "lxhvloader.dll"]; const MSHV_BOOT_COMPONENTS_DIR: &str = "Windows"; diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index 4e492ec7d5..8cdd222c51 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -258,7 +258,7 @@ pub fn cleanup_ukis_before_staging( /// 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. -pub(crate) fn find_ukis_to_remove_before_staging( +fn find_ukis_to_remove_before_staging( ctx: &EngineContext, esp_uki_directory: &Path, ) -> Result, Error> { diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 3ef53f4981..41347a73e3 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -33,8 +33,7 @@ use trident_api::{ use crate::{ engine::{ boot::{ - self, boot_tree, mshv as boot_mshv, uki, ESP_EXTRACTION_DIRECTORY, - ESP_EXTRACTION_DIRECTORY_MODE, + self, mshv as boot_mshv, uki, ESP_EXTRACTION_DIRECTORY, ESP_EXTRACTION_DIRECTORY_MODE, }, EngineContext, Subsystem, }, @@ -46,6 +45,7 @@ use crate::{ osimage::bootloader::Bootloader, }; +pub(crate) mod boot_tree; mod mshv; const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; @@ -816,11 +816,6 @@ fn generate_boot_filepaths( // Add MSHV components without changing ordinary loader/config selection. if bootloader.is_some_and(Bootloader::uses_mshv) { paths.extend(generate_mshv_boot_filepaths(&source_boot_dir)?); - } else { - ensure!( - !source_boot_dir.join("HvLoader.efi").try_exists()?, - "An MSHV image must declare COSI bootloader type 'efitreeloader-mshv-systemd-boot'" - ); } for path in &paths { @@ -2171,14 +2166,40 @@ mod tests { paths.sort(); assert_eq!(paths, expected); - let ordinary = Bootloader::new(BootloaderType::SystemdBoot, None); - assert!(generate_boot_filepaths(source.path(), is_uki, Some(&ordinary)).is_err()); - 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] { diff --git a/crates/trident/src/engine/boot/boot_tree.rs b/crates/trident/src/subsystems/esp/boot_tree.rs similarity index 100% rename from crates/trident/src/engine/boot/boot_tree.rs rename to crates/trident/src/subsystems/esp/boot_tree.rs From a624a709e62928b270fc8a1fb33bf816008c86a0 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 18:27:55 +0000 Subject: [PATCH 76/82] Use walkdir for boot-tree traversal Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 88854ec6-204f-40de-bbfe-03a7ab8052b0 --- Cargo.lock | 1 + Cargo.toml | 1 + crates/trident/Cargo.toml | 1 + .../trident/src/subsystems/esp/boot_tree.rs | 93 +++++++++++++------ 4 files changed, 66 insertions(+), 30 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 828302110b..80216b87b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4022,6 +4022,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/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/subsystems/esp/boot_tree.rs b/crates/trident/src/subsystems/esp/boot_tree.rs index 4f3847b3a7..e59cf2bb5f 100644 --- a/crates/trident/src/subsystems/esp/boot_tree.rs +++ b/crates/trident/src/subsystems/esp/boot_tree.rs @@ -12,43 +12,40 @@ use std::{ }; use anyhow::{ensure, Context, Error}; +use walkdir::WalkDir; -/// Validates the whole tree, including empty directories, and collects relative file paths. +/// Returns sorted root-relative file paths, validating empty directories without listing them. /// `temporary` permits replacement suffixes in destinations left by interrupted work. -fn scan(root: &Path, directory: &Path, temporary: bool) -> Result, Error> { - ensure!( - fs::symlink_metadata(directory)?.is_dir(), - "Invalid boot directory: {}", - directory.display() - ); +fn boot_files(root: &Path, temporary: bool) -> Result, Error> { let mut files = Vec::new(); - for entry in fs::read_dir(directory)? { + for entry in WalkDir::new(root) + .follow_links(false) + .follow_root_links(false) + { let entry = entry?; - let path = entry.path(); - let name = entry.file_name(); - let name = name.to_str().context("Non-UTF-8 boot file name")?; + 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}" ); - let kind = entry.file_type()?; - if kind.is_dir() { - files.extend(scan(root, &path, temporary)?); + if kind.is_file() { + files.push(entry.path().strip_prefix(root)?.to_path_buf()); } else { ensure!( - kind.is_file(), + kind.is_dir(), "Not a regular boot file: {}", - path.display() + entry.path().display() ); - files.push(path.strip_prefix(root)?.to_path_buf()); } } - Ok(files) -} - -/// Returns sorted root-relative file paths; empty directories are validated but not listed. -fn boot_files(root: &Path, temporary: bool) -> Result, Error> { - let mut files = scan(root, root, temporary)?; files.sort(); Ok(files) } @@ -95,14 +92,26 @@ fn ensure_disjoint(from: &Path, to: &Path) -> Result<(), Error> { /// Copies an already-validated entry, creating even empty directories. /// Existing destination-only entries are not retired, and failure can leave a partial copy. fn copy_entry(from: &Path, to: &Path) -> Result<(), Error> { - if fs::symlink_metadata(from)?.is_dir() { - fs::create_dir_all(to)?; - for entry in fs::read_dir(from)? { - let entry = entry?; - copy_entry(&entry.path(), &to.join(entry.file_name()))?; + 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)?; + } else { + ensure!( + entry.file_type().is_file(), + "Not a regular boot file: {}", + entry.path().display() + ); + fs::copy(entry.path(), destination)?; } - } else { - fs::copy(from, to)?; } Ok(()) } @@ -491,6 +500,30 @@ mod tests { } /// 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(); From 9ff608def196ee92b5f77243b586171f05be63b8 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 18:33:14 +0000 Subject: [PATCH 77/82] Move reusable boot-tree filesystem mechanics into osutils Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 88854ec6-204f-40de-bbfe-03a7ab8052b0 --- Cargo.lock | 1 + crates/osutils/Cargo.toml | 1 + crates/osutils/src/files.rs | 155 +++++++++++++++++- .../trident/src/subsystems/esp/boot_tree.rs | 80 ++------- 4 files changed, 165 insertions(+), 72 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 80216b87b8..beeabf6267 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2304,6 +2304,7 @@ dependencies = [ "thiserror 1.0.69", "trident_api", "uuid", + "walkdir", "which", "xattr", ] 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..ed6fefaab0 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,76 @@ where }) } +/// Resolves existing ancestors, retaining the suffix of paths not yet created. +fn canonical_path(path: &Path) -> Result { + match fs::canonicalize(path) { + Ok(path) => Ok(path), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(canonical_path( + 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 = canonical_path(&path::absolute(from)?)?; + let to = canonical_path(&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. The destination tree +/// must be link-free. Extra destination entries are retained; errors can leave a +/// partial copy, so callers needing preflight validation must perform it separately. +pub fn copy_regular_entry(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)?; + } else { + ensure!( + entry.file_type().is_file(), + "Not a regular file: {}", + entry.path().display() + ); + fs::copy(entry.path(), destination)?; + } + } + Ok(()) +} + +/// Removes a file, link or directory tree without following a root link. +/// Missing entries are ignored. +pub fn remove_entry_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 +403,88 @@ 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_regular_entry_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_regular_entry(&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_regular_entry(source.join("nested/payload.new"), &file).unwrap(); + assert_eq!(fs::read(&file).unwrap(), b"payload"); + copy_regular_entry(&source, source.join("child")).unwrap_err(); + assert!(!source.join("child").exists()); + } + + #[test] + fn test_copy_regular_entry_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_regular_entry(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_entry_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_entry_if_exists(&link).unwrap(); + remove_entry_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_entry_if_exists(&entry).unwrap(); + fs::write(&entry, b"file").unwrap(); + remove_entry_if_exists(&entry).unwrap(); + assert!(!entry.exists()); + } + #[test] fn test_create_file() { let dir = tempdir().unwrap(); diff --git a/crates/trident/src/subsystems/esp/boot_tree.rs b/crates/trident/src/subsystems/esp/boot_tree.rs index e59cf2bb5f..f314609b17 100644 --- a/crates/trident/src/subsystems/esp/boot_tree.rs +++ b/crates/trident/src/subsystems/esp/boot_tree.rs @@ -7,13 +7,14 @@ use std::{ fs, - io::ErrorKind, 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> { @@ -66,67 +67,6 @@ fn is_temporary(name: &str) -> bool { }) } -/// Resolves existing ancestors so overlap checks also cover destinations not yet created. -fn canonical_path(path: &Path) -> Result { - match fs::canonicalize(path) { - Ok(path) => Ok(path), - Err(error) if error.kind() == ErrorKind::NotFound => Ok(canonical_path( - path.parent().context("Missing boot directory parent")?, - )? - .join(path.file_name().context("Missing boot directory name")?)), - Err(error) => Err(error.into()), - } -} - -/// Prevents recursive copying into the source or retiring entries that contain the source. -fn ensure_disjoint(from: &Path, to: &Path) -> Result<(), Error> { - let from = canonical_path(from)?; - let to = canonical_path(to)?; - ensure!( - !from.starts_with(&to) && !to.starts_with(&from), - "Source and destination boot trees overlap" - ); - Ok(()) -} - -/// Copies an already-validated entry, creating even empty directories. -/// Existing destination-only entries are not retired, and failure can leave a partial copy. -fn copy_entry(from: &Path, to: &Path) -> Result<(), Error> { - 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)?; - } else { - ensure!( - entry.file_type().is_file(), - "Not a regular boot file: {}", - entry.path().display() - ); - fs::copy(entry.path(), destination)?; - } - } - Ok(()) -} - -/// Removes an owned entry; missing entries are expected during retry cleanup. -fn remove_entry(path: &Path) -> Result<(), Error> { - 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(()) -} - /// 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. @@ -135,8 +75,8 @@ pub(crate) fn copy_fallback_for_bootstrap(from: &Path, to: &Path) -> Result<(), if to.try_exists()? { boot_files(to, true)?; } - ensure_disjoint(from, to)?; - copy_entry(from, to) + files::ensure_disjoint_paths(from, to)?; + files::copy_regular_entry(from, to) } /// Replaces the UEFI fallback's complete boot tree, including nested and empty @@ -153,7 +93,7 @@ pub(crate) fn replace_fallback_boot_files(from: &Path, to: &Path) -> Result<(), if to.try_exists()? { boot_files(to, true)?; } - ensure_disjoint(from, to)?; + files::ensure_disjoint_paths(from, to)?; let mut entries = fs::read_dir(from)? .map(|entry| entry.map(|entry| entry.file_name())) .collect::, _>>()?; @@ -168,15 +108,15 @@ pub(crate) fn replace_fallback_boot_files(from: &Path, to: &Path) -> Result<(), // before risking another copy; otherwise the current entry wins. if previous.try_exists()? { if destination.try_exists()? { - remove_entry(&previous)?; + files::remove_entry_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())); - remove_entry(&staged)?; - copy_entry(&from.join(name), &staged)?; + files::remove_entry_if_exists(&staged)?; + files::copy_regular_entry(from.join(name), &staged)?; } // Snapshot before renaming so directory iteration cannot skip changed entries. @@ -186,7 +126,7 @@ pub(crate) fn replace_fallback_boot_files(from: &Path, to: &Path) -> Result<(), let name = name.to_str().context("Non-UTF-8 boot file name")?; if !is_temporary(name) { let previous = to.join(format!("{name}.old")); - remove_entry(&previous)?; + files::remove_entry_if_exists(&previous)?; fs::rename(entry.path(), previous)?; } } @@ -208,7 +148,7 @@ pub(crate) fn replace_fallback_boot_files(from: &Path, to: &Path) -> Result<(), .to_str() .context("Non-UTF-8 boot file name")?, ) { - remove_entry(&entry.path())?; + files::remove_entry_if_exists(entry.path())?; } } Ok(()) From 5cf1fe35c048c4a72340eaeb41f7cd01ee3dcaf9 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 18:54:00 +0000 Subject: [PATCH 78/82] Clarify filesystem helper names and remove comment-only changes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 88854ec6-204f-40de-bbfe-03a7ab8052b0 --- crates/osutils/src/files.rs | 26 +++++++++---------- crates/trident-client/src/protocol.rs | 1 - crates/trident-client/src/tests.rs | 1 - .../src/engine/manual_rollback/utils.rs | 3 --- .../trident/src/subsystems/esp/boot_tree.rs | 12 ++++----- 5 files changed, 19 insertions(+), 24 deletions(-) diff --git a/crates/osutils/src/files.rs b/crates/osutils/src/files.rs index ed6fefaab0..73f5916553 100644 --- a/crates/osutils/src/files.rs +++ b/crates/osutils/src/files.rs @@ -228,7 +228,7 @@ pub fn ensure_disjoint_paths(from: impl AsRef, to: impl AsRef) -> Re /// Rejects overlapping paths, source links and special files. The destination tree /// must be link-free. Extra destination entries are retained; errors can leave a /// partial copy, so callers needing preflight validation must perform it separately. -pub fn copy_regular_entry(from: impl AsRef, to: impl AsRef) -> Result<(), Error> { +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)?; @@ -258,7 +258,7 @@ pub fn copy_regular_entry(from: impl AsRef, to: impl AsRef) -> Resul /// Removes a file, link or directory tree without following a root link. /// Missing entries are ignored. -pub fn remove_entry_if_exists(path: impl AsRef) -> Result<(), Error> { +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)?, @@ -409,7 +409,7 @@ mod tests { use tempfile::tempdir; #[test] - fn test_copy_regular_entry_preserves_empty_directories_and_root_files() { + 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"); @@ -417,7 +417,7 @@ mod tests { 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_regular_entry(&source, &destination).unwrap(); + copy_recursively(&source, &destination).unwrap(); assert!(destination.join("nested/empty").is_dir()); assert_eq!( fs::read(destination.join("nested/payload.new")).unwrap(), @@ -425,14 +425,14 @@ mod tests { ); assert_eq!(fs::read(destination.join("retained")).unwrap(), b"retained"); let file = temp.path().join("file"); - copy_regular_entry(source.join("nested/payload.new"), &file).unwrap(); + copy_recursively(source.join("nested/payload.new"), &file).unwrap(); assert_eq!(fs::read(&file).unwrap(), b"payload"); - copy_regular_entry(&source, source.join("child")).unwrap_err(); + copy_recursively(&source, source.join("child")).unwrap_err(); assert!(!source.join("child").exists()); } #[test] - fn test_copy_regular_entry_rejects_source_links_and_special_files() { + 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(); @@ -445,7 +445,7 @@ mod tests { unistd::mkfifo(&fifo, Mode::S_IRUSR).unwrap(); for source in [&file_link, &directory_link, &fifo] { let destination = temp.path().join("destination"); - copy_regular_entry(source, &destination).unwrap_err(); + copy_recursively(source, &destination).unwrap_err(); assert!(!destination.exists()); } assert_eq!(fs::read(outside.join("payload")).unwrap(), b"outside"); @@ -465,23 +465,23 @@ mod tests { } #[test] - fn test_remove_entry_if_exists_preserves_link_targets() { + 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_entry_if_exists(&link).unwrap(); - remove_entry_if_exists(&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_entry_if_exists(&entry).unwrap(); + remove_recursively_if_exists(&entry).unwrap(); fs::write(&entry, b"file").unwrap(); - remove_entry_if_exists(&entry).unwrap(); + remove_recursively_if_exists(&entry).unwrap(); assert!(!entry.exists()); } diff --git a/crates/trident-client/src/protocol.rs b/crates/trident-client/src/protocol.rs index e6ffe25bd2..9d7654f809 100644 --- a/crates/trident-client/src/protocol.rs +++ b/crates/trident-client/src/protocol.rs @@ -286,7 +286,6 @@ fn decode_location(location: ProtoFileLocation) -> SourceLocation { } } -/// Decodes preview states, preserving unknown wire values. #[cfg(feature = "preview")] pub(crate) fn decode_servicing_state(state: i32) -> ServicingState { match ProtoServicingState::try_from(state) { diff --git a/crates/trident-client/src/tests.rs b/crates/trident-client/src/tests.rs index 07d4036073..c5ae868c23 100644 --- a/crates/trident-client/src/tests.rs +++ b/crates/trident-client/src/tests.rs @@ -1485,7 +1485,6 @@ async fn preview_status_validation_and_rollback_use_domain_types() { assert_eq!(captured.validation_yaml.len(), 2); } -/// Preview decoding preserves known, unspecified, and unknown states. #[cfg(feature = "preview")] #[tokio::test] async fn preview_status_enums_preserve_known_unspecified_and_unknown_values() { diff --git a/crates/trident/src/engine/manual_rollback/utils.rs b/crates/trident/src/engine/manual_rollback/utils.rs index 0ed7ee721c..04df1db6b1 100644 --- a/crates/trident/src/engine/manual_rollback/utils.rs +++ b/crates/trident/src/engine/manual_rollback/utils.rs @@ -247,8 +247,6 @@ impl ManualRollbackContext { /// * an operation that cannot be rolled back is found /// * a HostStatus entry is None /// - /// Health/hypervisor automatic rollback ends parsing, excluding the rejected candidate. - /// /// Once the Operations have been parsed, the ManualRollback operations (both /// A/B and runtime) and the operations that they undo (both A/B and runtime /// updates) are pruned from the list of Operations. @@ -353,7 +351,6 @@ impl ManualRollbackContext { current_operation.operation_host_status = Some(current_hs.clone()); } ServicingState::AbUpdateHealthCheckFailed => { - // Do not offer the rejected candidate as a rollback target. current_operation.kind = OperationKind::AbUpdateAutoRollback; trace!("Detected AbUpdateAutoRollback operation, ending parsing here."); break; diff --git a/crates/trident/src/subsystems/esp/boot_tree.rs b/crates/trident/src/subsystems/esp/boot_tree.rs index f314609b17..154a513e39 100644 --- a/crates/trident/src/subsystems/esp/boot_tree.rs +++ b/crates/trident/src/subsystems/esp/boot_tree.rs @@ -76,7 +76,7 @@ pub(crate) fn copy_fallback_for_bootstrap(from: &Path, to: &Path) -> Result<(), boot_files(to, true)?; } files::ensure_disjoint_paths(from, to)?; - files::copy_regular_entry(from, to) + files::copy_recursively(from, to) } /// Replaces the UEFI fallback's complete boot tree, including nested and empty @@ -108,15 +108,15 @@ pub(crate) fn replace_fallback_boot_files(from: &Path, to: &Path) -> Result<(), // before risking another copy; otherwise the current entry wins. if previous.try_exists()? { if destination.try_exists()? { - files::remove_entry_if_exists(&previous)?; + 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_entry_if_exists(&staged)?; - files::copy_regular_entry(from.join(name), &staged)?; + files::remove_recursively_if_exists(&staged)?; + files::copy_recursively(from.join(name), &staged)?; } // Snapshot before renaming so directory iteration cannot skip changed entries. @@ -126,7 +126,7 @@ pub(crate) fn replace_fallback_boot_files(from: &Path, to: &Path) -> Result<(), 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_entry_if_exists(&previous)?; + files::remove_recursively_if_exists(&previous)?; fs::rename(entry.path(), previous)?; } } @@ -148,7 +148,7 @@ pub(crate) fn replace_fallback_boot_files(from: &Path, to: &Path) -> Result<(), .to_str() .context("Non-UTF-8 boot file name")?, ) { - files::remove_entry_if_exists(entry.path())?; + files::remove_recursively_if_exists(entry.path())?; } } Ok(()) From d3bc06a874b03438fc53cabef4b6b29c02b1dc08 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 18:56:22 +0000 Subject: [PATCH 79/82] Clarify MSHV validation function contracts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 88854ec6-204f-40de-bbfe-03a7ab8052b0 --- crates/trident/src/subsystems/esp/mshv.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 0d728d713f..23e7f396ad 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -1,4 +1,4 @@ -//! Slot-owned MSHV validation and efitreeloader (ETL) ESP definitions. +//! Validates file-based MSHV support and retained-slot compatibility. use std::path::Path; @@ -20,7 +20,12 @@ use crate::{ osimage::bootloader::Bootloader, }; -/// Enforces file-based MSHV support and retained-slot compatibility before staging. +/// Checks file-based MSHV support and A/B layout compatibility before staging. +/// +/// 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(()); @@ -55,7 +60,12 @@ pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE Ok(()) } -/// Rejects A/B updates that change the retained slot's MSHV layout. +/// 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(()); @@ -74,7 +84,6 @@ fn validate_transition(ctx: &EngineContext, esp_path: &Path) -> Result<(), Error Ok(()) } -/// Reports unsupported MSHV boot configurations. fn unsupported(reason: &str) -> TridentError { TridentError::with_source( InvalidInputError::InvalidBootConfiguration, From f1de5746eb4a9417756ff92ab8f777a08778d09a Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 19:54:02 +0000 Subject: [PATCH 80/82] Clarify missing-path canonicalization helper Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 88854ec6-204f-40de-bbfe-03a7ab8052b0 --- crates/osutils/src/files.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/osutils/src/files.rs b/crates/osutils/src/files.rs index 73f5916553..3e78c7a372 100644 --- a/crates/osutils/src/files.rs +++ b/crates/osutils/src/files.rs @@ -199,11 +199,14 @@ where }) } -/// Resolves existing ancestors, retaining the suffix of paths not yet created. -fn canonical_path(path: &Path) -> Result { +/// 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(canonical_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")?)), @@ -214,8 +217,8 @@ fn canonical_path(path: &Path) -> Result { /// 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 = canonical_path(&path::absolute(from)?)?; - let to = canonical_path(&path::absolute(to)?)?; + 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" From 2dc65fe878240008d0ef95bb90349a65aa0deca0 Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 20:34:05 +0000 Subject: [PATCH 81/82] Address MSHV servicing review suggestions Clarify unchecked copy preconditions and add path-aware errors. Move ACL detection into osrelease, name the MSHV test fixture, and remove leftover error-preservation churn. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 51df658f-200d-426f-aa83-68c76a76e4a3 --- crates/osutils/src/files.rs | 41 ++++++++++++++++--- crates/osutils/src/osrelease.rs | 7 ++++ crates/trident/src/engine/boot/mshv.rs | 2 +- crates/trident/src/init/acl/mod.rs | 9 ---- crates/trident/src/lib.rs | 20 +++++---- crates/trident/src/subsystems/esp.rs | 23 +++++++---- .../trident/src/subsystems/esp/boot_tree.rs | 23 ++++++----- crates/trident/src/subsystems/esp/mshv.rs | 4 +- 8 files changed, 85 insertions(+), 44 deletions(-) diff --git a/crates/osutils/src/files.rs b/crates/osutils/src/files.rs index 3e78c7a372..14a0246b2e 100644 --- a/crates/osutils/src/files.rs +++ b/crates/osutils/src/files.rs @@ -228,9 +228,12 @@ pub fn ensure_disjoint_paths(from: impl AsRef, to: impl AsRef) -> Re /// Copies a regular file or directory tree, preserving empty directories. /// -/// Rejects overlapping paths, source links and special files. The destination tree -/// must be link-free. Extra destination entries are retained; errors can leave a -/// partial copy, so callers needing preflight validation must perform it separately. +/// 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(); @@ -246,14 +249,25 @@ pub fn copy_recursively(from: impl AsRef, to: impl AsRef) -> Result< to.join(entry.path().strip_prefix(from)?) }; if entry.file_type().is_dir() { - fs::create_dir_all(destination)?; + 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)?; + fs::copy(entry.path(), &destination).with_context(|| { + format!( + "Failed to copy '{}' to '{}'", + entry.path().display(), + destination.display() + ) + })?; } } Ok(()) @@ -434,6 +448,23 @@ mod tests { 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(); diff --git a/crates/osutils/src/osrelease.rs b/crates/osutils/src/osrelease.rs index bcac756dc8..acfabf1b9d 100644 --- a/crates/osutils/src/osrelease.rs +++ b/crates/osutils/src/osrelease.rs @@ -31,6 +31,13 @@ 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 { + let os_release = OsRelease::read().context("Failed to read OS release information")?; + + Ok(os_release.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/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs index 91fd135335..bc51cc0bb9 100644 --- a/crates/trident/src/engine/boot/mshv.rs +++ b/crates/trident/src/engine/boot/mshv.rs @@ -63,7 +63,7 @@ pub(crate) fn validate_boot_components(boot_dir: &Path) -> Result<(), Error> { } #[cfg(test)] -pub(crate) const FILES: &[&str] = &[ +pub(crate) const MSHV_SLOT_BOOT_FILES: &[&str] = &[ "bootx64.efi", "grubx64.efi", "second.efi", diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index ac7e830a92..f08476955c 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -9,11 +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, @@ -24,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.get_distro().is_acl()) -} - /// 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. diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index da489ddc69..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, @@ -305,17 +309,17 @@ impl Trident { where F: FnOnce(&mut DataStore) -> Result, { - // Preserve the original health-check failure across failed recovery attempts - // instead of replacing it with a secondary recovery error. + // AbUpdateHealthCheckFailed is a special case where we would like + // to preserve the last error across any recovery. This aids in + // surfacing the original error. debug!( "Execute and record error with servicing state: {:?} and last error: {:?}", datastore.host_status().servicing_state, datastore.host_status().last_error ); - let last_error_to_preserve = if matches!( - datastore.host_status().servicing_state, - ServicingState::AbUpdateHealthCheckFailed - ) { + let last_error_to_preserve = if datastore.host_status().servicing_state + == ServicingState::AbUpdateHealthCheckFailed + { datastore.host_status().last_error.clone() } else { None @@ -634,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() diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index 41347a73e3..2a44e3e648 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -906,7 +906,9 @@ mod tests { use crate::{ engine::{ - boot::{get_update_esp_dir_name, make_esp_dir_name_candidates, mshv::FILES}, + boot::{ + get_update_esp_dir_name, make_esp_dir_name_candidates, mshv::MSHV_SLOT_BOOT_FILES, + }, install_index, }, osimage::bootloader::BootloaderType, @@ -1083,7 +1085,7 @@ mod tests { ..Default::default() }; let names = if is_mshv { - FILES + MSHV_SLOT_BOOT_FILES } else { &[BOOT_EFI, GRUB_EFI, GRUB2_CONFIG_FILENAME] }; @@ -1696,7 +1698,7 @@ mod tests { let source = TempDir::new().unwrap(); let destination = TempDir::new().unwrap(); fs::write(source.path().join(BOOT_EFI), b"ordinary loader").unwrap(); - for name in FILES { + 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"); @@ -1857,7 +1859,7 @@ mod tests { .path() .join(ESP_EFI_DIRECTORY) .join("AZLA.bootstrap-tmp"); - for name in FILES { + 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(); @@ -1869,7 +1871,7 @@ mod tests { fs::write(temporary.join("stale"), "incomplete").unwrap(); bootstrap_azla_from_fallback(esp.path()).unwrap(); - for name in FILES { + for name in MSHV_SLOT_BOOT_FILES { assert!(files_are_identical(&boot.join(name), &azla.join(name))); } assert!(files_are_identical( @@ -1903,7 +1905,7 @@ mod tests { .path() .join(ESP_EFI_DIRECTORY) .join("AZLA.bootstrap-tmp"); - for name in FILES { + 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(); @@ -1920,7 +1922,7 @@ mod tests { .contains("Reserved boot file name")); assert!(!temporary.exists()); assert!(!azla.exists()); - for name in FILES { + for name in MSHV_SLOT_BOOT_FILES { assert_eq!(fs::read(boot.join(name)).unwrap(), b"retained"); } @@ -1928,7 +1930,7 @@ mod tests { bootstrap_azla_from_fallback(esp.path()).unwrap(); assert!(!temporary.exists()); assert!(!azla.join("stale").exists()); - for name in FILES { + for name in MSHV_SLOT_BOOT_FILES { assert!(files_are_identical(&boot.join(name), &azla.join(name))); } } @@ -2155,7 +2157,10 @@ mod tests { } fs::write(boot.join(GRUB_NOPREFIX_EFI), b"unrelated GRUB").unwrap(); fs::write(boot.join(GRUB2_CONFIG_FILENAME), b"configuration").unwrap(); - let mut expected = FILES.iter().map(|name| boot.join(name)).collect::>(); + 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)); diff --git a/crates/trident/src/subsystems/esp/boot_tree.rs b/crates/trident/src/subsystems/esp/boot_tree.rs index 154a513e39..3d3a54ee20 100644 --- a/crates/trident/src/subsystems/esp/boot_tree.rs +++ b/crates/trident/src/subsystems/esp/boot_tree.rs @@ -170,13 +170,13 @@ mod tests { }; use crate::{ - engine::{boot::mshv::FILES, EngineContext}, + 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 FILES { + 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(); @@ -222,13 +222,16 @@ mod tests { .unwrap(); } filepaths(&fallback).unwrap(); - for name in FILES { + 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 !FILES.iter().any(|name| entry.file_name() == *name) { + if !MSHV_SLOT_BOOT_FILES + .iter() + .any(|name| entry.file_name() == *name) + { assert!(!fallback.join(entry.file_name()).exists()); } } @@ -288,7 +291,7 @@ mod tests { create_boot_files(&source, b"new"); create_boot_files(&active, b"retained"); copy_fallback_for_bootstrap(&source, &target).unwrap(); - for name in FILES { + 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"); } @@ -411,7 +414,7 @@ mod tests { #[test] fn accepts_additional_files_but_rejects_temporary_source_names() { let temp = TempDir::new().unwrap(); - for name in FILES { + 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(); @@ -499,7 +502,7 @@ mod tests { replace_fallback_boot_files(&source, &fallback).unwrap(); replace_fallback_boot_files(&source, &fallback).unwrap(); filepaths(&fallback).unwrap(); - for name in FILES { + 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()); @@ -543,7 +546,7 @@ mod tests { ctx.spec.os.uefi_fallback = mode; esp::set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateStaged, temp.path()) .unwrap(); - for name in FILES.iter().copied().chain([secondary]) { + for name in MSHV_SLOT_BOOT_FILES.iter().copied().chain([secondary]) { let expected = if mode == UefiFallbackMode::Optimistic { b"candidate".as_slice() } else { @@ -553,7 +556,7 @@ mod tests { } esp::set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateFinalized, temp.path()) .unwrap(); - for name in FILES.iter().copied().chain([secondary]) { + for name in MSHV_SLOT_BOOT_FILES.iter().copied().chain([secondary]) { let expected = if mode == UefiFallbackMode::Disabled { b"retained".as_slice() } else { @@ -570,7 +573,7 @@ mod tests { temp.path(), ) .unwrap(); - for name in FILES.iter().copied().chain([secondary]) { + 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 23e7f396ad..072a24346f 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -104,7 +104,7 @@ mod tests { use trident_api::{config::Encryption, status::AbVolumeSelection}; use crate::{ - engine::{boot::mshv::FILES, Subsystem}, + engine::{boot::mshv::MSHV_SLOT_BOOT_FILES, Subsystem}, osimage::{bootloader::BootloaderType, mock::MockOsImage}, subsystems::esp::EspSubsystem, }; @@ -154,7 +154,7 @@ mod tests { for retained_mshv in [false, true] { let esp = TempDir::new().unwrap(); if retained_mshv { - for name in FILES { + 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(); From 7aec517ac2d259345fa5e0391775df4aed23cc3a Mon Sep 17 00:00:00 2001 From: Brian Fjeldstad Date: Wed, 18 Nov 2026 20:45:47 +0000 Subject: [PATCH 82/82] Apply ESP visibility and error-reporting feedback Limit tree replacement helpers to ESP, construct validation errors at their failure sites, and reuse os-release read context. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 51df658f-200d-426f-aa83-68c76a76e4a3 --- crates/osutils/src/osrelease.rs | 4 +--- crates/trident/src/subsystems/esp/boot_tree.rs | 4 ++-- crates/trident/src/subsystems/esp/mshv.rs | 17 ++++++----------- 3 files changed, 9 insertions(+), 16 deletions(-) diff --git a/crates/osutils/src/osrelease.rs b/crates/osutils/src/osrelease.rs index acfabf1b9d..96019cf689 100644 --- a/crates/osutils/src/osrelease.rs +++ b/crates/osutils/src/osrelease.rs @@ -33,9 +33,7 @@ pub fn is_azl3() -> Result { /// 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.get_distro().is_acl()) + Ok(OsRelease::read()?.get_distro().is_acl()) } /// Splits one os-release-style `KEY=VALUE` line into its key and diff --git a/crates/trident/src/subsystems/esp/boot_tree.rs b/crates/trident/src/subsystems/esp/boot_tree.rs index 3d3a54ee20..41d4308e24 100644 --- a/crates/trident/src/subsystems/esp/boot_tree.rs +++ b/crates/trident/src/subsystems/esp/boot_tree.rs @@ -70,7 +70,7 @@ fn is_temporary(name: &str) -> bool { /// 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(crate) fn copy_fallback_for_bootstrap(from: &Path, to: &Path) -> Result<(), Error> { +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)?; @@ -87,7 +87,7 @@ pub(crate) fn copy_fallback_for_bootstrap(from: &Path, to: &Path) -> Result<(), /// 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(crate) fn replace_fallback_boot_files(from: &Path, to: &Path) -> Result<(), Error> { +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()? { diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index 072a24346f..d4e12b0072 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -36,8 +36,9 @@ pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE || !ctx.image_distro().is_acl() || !ctx.is_uki()? { - return Err(unsupported( - "Slot-owned MSHV requires an x86-64 ACL UKI image", + return Err(TridentError::with_source( + InvalidInputError::InvalidBootConfiguration, + anyhow!("Slot-owned MSHV requires an x86-64 ACL UKI image"), )); } if ctx @@ -47,8 +48,9 @@ pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentE .as_ref() .is_some_and(|encryption| !encryption.pcrs.is_empty()) { - return Err(unsupported( - "Slot-owned MSHV TPM/PCR-bound encryption is not validated", + return Err(TridentError::with_source( + InvalidInputError::InvalidBootConfiguration, + anyhow!("Slot-owned MSHV TPM/PCR-bound encryption is not validated"), )); } } @@ -84,13 +86,6 @@ fn validate_transition(ctx: &EngineContext, esp_path: &Path) -> Result<(), Error Ok(()) } -fn unsupported(reason: &str) -> TridentError { - TridentError::with_source( - InvalidInputError::InvalidBootConfiguration, - anyhow!("{reason}"), - ) -} - #[cfg(test)] mod tests { use super::*;