crates/cloud-media-bootproof/tests/image_writer_boot.rs
//! **Cloud media, BOOTED back** — the proof the whole lane exists for.
//!
//! A medium writer that produces plausible bytes and an unbootable disk is
//! worse than none: the bytes pass every structural check, the customer
//! discovers it. So this test does not assert on structure at all. It:
//!
//! 1. builds a real UEFI payload from source (`nornir-build-thing/tests/fixtures/korp-efistub`,
//! which prints `KORP-APPLIANCE BOOT-OK` to COM1 and halts);
//! 2. lays a **real GPT with a real FAT EFI System Partition** on a blank raw
//! disk — through `korp_installer::{gpt, esp}`, the constellation's one GPT
//! writer and one ESP assembler, in pure Rust (no `sgdisk`, no `mkfs.vfat`);
//! 3. converts that one installed disk into ALL FOUR cloud media with
//! [`nornir_build_thing::image_writer::write_all_media`]; and
//! 4. **boots each product back under QEMU + OVMF** and asserts the marker
//! reaches the serial capture — `format=vpc` for the VHD, `format=raw` for
//! the AWS raw, the GCE tarball unpacked to `disk.raw` first (exactly what
//! GCE does with it), `format=qcow2` for the qcow2.
//!
//! # What is and is not a subprocess here
//!
//! Every WRITER is pure Rust with no `Command::new` — no `qemu-img`, no
//! `tar(1)`, no `gzip(1)`. This test then runs exactly two sanctioned externals
//! that are not build tools for the medium:
//!
//! * `cargo … --target x86_64-unknown-uefi` — the Rust COMPILER, building the
//! `no_std` payload from source rather than vendoring a blob; and
//! * `qemu-system-x86_64` — the hypervisor, which is the only thing that can
//! answer "does it boot".
//!
//! `qemu-img` is a build tool and appears nowhere.
//!
//! # Heavy / `#[ignore]`
//!
//! Self-gates on `qemu-system-x86_64`, an OVMF CODE+VARS pair and a buildable
//! `x86_64-unknown-uefi` target; SKIPs with a loud note (never a faked green)
//! when any is absent.
//!
//! ```bash
//! cargo test -p cloud-media-bootproof --test image_writer_boot -- --ignored --nocapture
//! ```
use std::io::{Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use korp_installer::esp::{build_esp_image, EspFile, FALLBACK_BOOT_PATH};
use korp_installer::gpt;
use korp_installer::kvmproof::{boot_disk_until, create_blank_disk, locate_ovmf, which};
use nornir_build_thing::image_writer::{self, CloudMedium, MIB};
/// The marker the `korp-efistub` fixture prints to COM1 on success. Shared with
/// `nornir-build-thing/tests/iso_boot.rs` — the SAME payload, so an ISO boot and a cloud-medium
/// boot are proven by the same sentence and cannot drift apart.
const BOOT_MARKER: &str = "KORP-APPLIANCE BOOT-OK";
/// The disk the media are made from: 128 MiB, GPT, 48 MiB ESP (enough for
/// `build_esp_image` to choose FAT32, which is what a real ESP is).
const DISK_BYTES: u64 = 128 * MIB;
const ESP_MIB: u64 = 48;
/// Deterministic GUID seed, so a failing run's table can be compared to a
/// passing one byte for byte.
const GPT_SEED: u64 = 0x5731_4d45_4449_554d; // "W1MEDIUM"
#[test]
#[ignore = "heavy: lays a GPT+ESP disk, converts it to all four cloud media, and BOOTS each one back under QEMU+OVMF"]
fn every_cloud_medium_boots_back_under_qemu() {
// ── self-gate: skip loudly (never fake green) when the host cannot boot ──
let Some(qemu) = which("qemu-system-x86_64") else {
eprintln!("SKIP image_writer_boot: no qemu-system-x86_64 on PATH");
return;
};
let Some((ovmf_code, ovmf_vars)) = locate_ovmf() else {
eprintln!("SKIP image_writer_boot: no OVMF CODE+VARS pair (install edk2/ovmf)");
return;
};
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
let Some(efi_app) = build_efi_stub(root) else {
eprintln!(
"SKIP image_writer_boot: could not build the x86_64-unknown-uefi payload \
(run `rustup target add x86_64-unknown-uefi`)"
);
return;
};
// ── 1. the INSTALLED disk: GPT + a FAT ESP carrying the fallback boot path ──
let installed = root.join("installed.raw");
let esp_bytes = lay_installed_disk(&installed, &efi_app);
eprintln!(
"installed disk: {DISK_BYTES} B, {ESP_MIB} MiB ESP ({} B image), payload {} B",
esp_bytes,
std::fs::metadata(&efi_app).unwrap().len()
);
// The disk really looks like an installed one before anything converts it —
// otherwise a later "the GPT survived" assertion proves nothing.
let probe = image_writer::probe_disk(&installed).expect("probe the installed disk");
assert!(probe.mbr_signature, "the installed disk carries a protective MBR");
assert!(probe.gpt_header, "the installed disk carries a GPT header");
// ── 2. one install, four media ──
let media_dir = root.join("media");
let products =
image_writer::write_all_media(&installed, &media_dir, "korp-cloud").expect("write all media");
assert_eq!(products.len(), 4);
// ── the CONTAINER must declare the right disk size, which a boot does NOT
// prove ────────────────────────────────────────────────────────────────
//
// MEASURED 2026-09-05, and the reason this block exists: a red probe that
// halved the VHD footer's `current_size` to 64 MiB **still booted**. QEMU
// exposed a 64 MiB disk, OVMF found the primary GPT and the ESP inside the
// first 48 MiB, and the guest reached BOOT-OK exactly as before — only the
// BACKUP GPT (which lives in the last sector) fell off the end, and UEFI
// never looks at it. So "it booted" is a real proof of attachability and of
// the payload chain, and it is BLIND to the size fields. The container is
// therefore read back here as well, by the reader that validates it.
for p in &products {
let declared = match p.medium {
CloudMedium::Vhd => {
image_writer::read_vhd_footer(&p.path).expect("the VHD footer validates").current_size
}
CloudMedium::Qcow2 => {
image_writer::Qcow2Reader::open(&p.path).expect("the qcow2 opens").header().size
}
CloudMedium::Raw => std::fs::metadata(&p.path).unwrap().len(),
CloudMedium::GceTarGz => p.virtual_size, // asserted at unpack time below
};
assert_eq!(
declared,
DISK_BYTES,
"{} declares a {declared} B disk; the installed disk is {DISK_BYTES} B",
p.medium.as_str()
);
}
for p in &products {
eprintln!(
" {:>7} → {:>12} B on disk, {} B virtual, id {}",
p.medium.as_str(),
p.file_size,
p.virtual_size,
&p.content_hex()[..16]
);
}
// ── 3. boot each product back ──
let mut booted: Vec<(&'static str, bool, usize)> = Vec::new();
for p in &products {
let name = p.medium.as_str();
let workdir = root.join(format!("boot-{}", p.medium.file_extension()));
std::fs::create_dir_all(&workdir).expect("boot workdir");
// The GCE tarball is not a disk. Unpack it to `disk.raw` — what GCE
// does — and attach THAT. Every other medium attaches as itself.
let (attach, medium_for_argv) = if p.medium == CloudMedium::GceTarGz {
let unpacked = workdir.join("disk.raw");
let n = image_writer::unpack_gce_tar_gz(&p.path, &unpacked)
.expect("unpack the GCE tarball to disk.raw");
assert_eq!(n, p.virtual_size, "the unpacked disk is the whole image");
(unpacked, CloudMedium::Raw)
} else {
(p.path.clone(), p.medium)
};
// The argv comes from the medium, not from a filename sniff — the
// rendered string is itself applied output and is printed with the run.
let args = medium_for_argv
.qemu_drive_arg(&attach)
.expect("an attachable medium renders a -drive");
assert!(
args[1].contains(&format!("format={}", p.medium.qemu_format()))
|| p.medium == CloudMedium::GceTarGz,
"the drive argv names this medium's own format: {args:?}"
);
eprintln!("booting {name}: {}", args.join(" "));
let serial = boot_disk_until(
&qemu,
&ovmf_code,
&ovmf_vars,
&args,
&workdir,
BOOT_MARKER,
Duration::from_secs(90),
);
let ok = serial.contains(BOOT_MARKER);
if !ok {
eprintln!("─── {name} serial ───\n{serial}\n─────────────────────");
}
booted.push((name, ok, serial.len()));
}
let failed: Vec<&str> = booted.iter().filter(|(_, ok, _)| !ok).map(|(n, _, _)| *n).collect();
assert!(
failed.is_empty(),
"these media did not reach '{BOOT_MARKER}' under OVMF: {failed:?} (all: {booted:?})"
);
eprintln!("all four cloud media booted to '{BOOT_MARKER}': {booted:?}");
}
/// The VHD arm on its own, so a failure names the medium rather than the loop.
///
/// It is the one worth isolating: `format=vpc` is the only medium whose
/// container the firmware never sees through — QEMU has to strip the 512-byte
/// `conectix` footer and present the padded body as the disk. A footer whose
/// size fields are wrong makes QEMU expose a disk of the wrong length, and the
/// GPT's backup header (which lives in the LAST sector) then falls outside it.
/// Nothing structural catches that; a boot does.
#[test]
#[ignore = "heavy: boots the produced fixed-size VHD as -drive format=vpc under QEMU+OVMF"]
fn the_vhd_boots_as_format_vpc_with_its_backup_gpt_intact() {
let Some(qemu) = which("qemu-system-x86_64") else {
eprintln!("SKIP vhd boot: no qemu-system-x86_64 on PATH");
return;
};
let Some((code, vars)) = locate_ovmf() else {
eprintln!("SKIP vhd boot: no OVMF CODE+VARS pair");
return;
};
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
let Some(efi_app) = build_efi_stub(root) else {
eprintln!("SKIP vhd boot: no x86_64-unknown-uefi target");
return;
};
let installed = root.join("installed.raw");
lay_installed_disk(&installed, &efi_app);
let vhd = root.join("azure.vhd");
let p = image_writer::write_vhd(&installed, &vhd).expect("write the VHD");
// 128 MiB is already MiB-aligned, so QEMU must see exactly the source disk.
assert_eq!(p.virtual_size, DISK_BYTES);
assert_eq!(p.padded, 0);
let f = image_writer::read_vhd_footer(&vhd).expect("the footer validates");
assert_eq!(f.current_size, DISK_BYTES);
let workdir = root.join("boot-vhd");
std::fs::create_dir_all(&workdir).unwrap();
let args = CloudMedium::Vhd.qemu_drive_arg(&vhd).unwrap();
assert!(args[1].contains("format=vpc"), "QEMU's word for a VHD: {args:?}");
let serial =
boot_disk_until(&qemu, &code, &vars, &args, &workdir, BOOT_MARKER, Duration::from_secs(90));
eprintln!("─── vhd serial ───\n{serial}\n──────────────────");
assert!(
serial.contains(BOOT_MARKER),
"the fixed-size VHD booted under OVMF as format=vpc (serial {} bytes)",
serial.len()
);
}
// ── helpers ─────────────────────────────────────────────────────────────────
/// Lay a GPT + FAT ESP on a blank raw disk at `path` and place `efi_app` at the
/// firmware fallback boot path. Returns the ESP image size in bytes.
///
/// Everything here is `korp_installer`'s: `create_blank_disk` (pure `set_len`),
/// `gpt::write_gpt` (the hand-rolled table, protective MBR + primary + backup)
/// and `esp::build_esp_image` (fatfs). Nothing is re-rolled and nothing shells
/// out — this is the same code path the real installer lays on real metal, so
/// the media below are made from a disk shaped exactly like a real one.
fn lay_installed_disk(path: &Path, efi_app: &Path) -> u64 {
create_blank_disk(path, DISK_BYTES);
let mut disk =
std::fs::OpenOptions::new().read(true).write(true).open(path).expect("open the blank disk");
let layout =
gpt::write_gpt(&mut disk, DISK_BYTES, ESP_MIB, None, GPT_SEED).expect("lay the GPT");
let payload = std::fs::read(efi_app).expect("read the UEFI payload");
let esp = build_esp_image(layout.esp.len_bytes(), &[EspFile::new(FALLBACK_BOOT_PATH, payload)])
.expect("assemble the ESP");
disk.seek(SeekFrom::Start(layout.esp.offset_bytes())).expect("seek to P1");
disk.write_all(&esp).expect("stream the ESP onto P1");
disk.flush().expect("flush the disk");
esp.len() as u64
}
/// Build the `nornir-build-thing/tests/fixtures/korp-efistub` UEFI payload; `None` when the
/// `x86_64-unknown-uefi` target is unavailable. Returns the `bootx64.efi` path.
///
/// NB this is the same twenty lines `nornir-build-thing/tests/iso_boot.rs` carries. It belongs in
/// `tests/common/mod.rs` beside the other shared fixture builders — that file is
/// not this lane's to edit, and the follow-up is recorded rather than done
/// silently.
fn build_efi_stub(root: &Path) -> Option<PathBuf> {
let fixture =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../nornir-build-thing/tests/fixtures/korp-efistub/Cargo.toml");
let target_dir = root.join("efi-target");
let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
let status = Command::new(&cargo)
.args(["build", "--release", "--target", "x86_64-unknown-uefi", "--manifest-path"])
.arg(&fixture)
.arg("--target-dir")
.arg(&target_dir)
.status()
.ok()?;
if !status.success() {
return None;
}
let efi = target_dir.join("x86_64-unknown-uefi/release/bootx64.efi");
efi.is_file().then_some(efi)
}