//! Installation orchestration. //! //! The only place destructive authorization is required, and only after the //! plan has been shown and confirmed. Stages run in the proven order and stop //! on the first failure. use std::path::PathBuf; use phoebus_core::policy::{load_history, PackagePolicyEngine, PolicyContext}; use phoebus_core::validate::ValidationIssue; use phoebus_core::{ validate, Filesystem, HardwareReport, InstallConfig, InstallPlan, SecretString, }; use phoebus_executor::storage::StorageState; use phoebus_executor::{ boot, desktop, encryption, kernel, nix, portage, probe, services, snapshot, stage3, storage, users, Exec, Result, }; pub struct Installer { pub config: InstallConfig, pub hardware: HardwareReport, pub disks: Vec, pub exec: Exec, pub engine: PackagePolicyEngine, pub policy_ctx: PolicyContext, pub state: StorageState, } /// Receives stage transitions during [`Installer::install_observed`]. The GUI /// bridge uses this to show real backend stages; it is deliberately a narrow /// trait so no frontend can influence execution. pub trait InstallObserver { fn stage_started(&mut self, step: phoebus_core::InstallStep); /// `error` is `None` on success, otherwise a redactable message. fn stage_finished(&mut self, step: phoebus_core::InstallStep, error: Option<&str>); } /// Does nothing; the default for callers that do not report progress. pub struct NoopObserver; impl InstallObserver for NoopObserver { fn stage_started(&mut self, _step: phoebus_core::InstallStep) {} fn stage_finished(&mut self, _step: phoebus_core::InstallStep, _error: Option<&str>) {} } impl Installer { pub fn new(config: InstallConfig, exec: Exec) -> Self { let hardware = probe::probe_hardware(exec.runner.as_ref()); let disks = probe::probe_disks(exec.runner.as_ref()); // Prefer measured history installed on the target, then the installer's // ephemeral state directory. let persistent = exec.root.join("var/lib/phoebus/compile-times.tsv"); let volatile = exec.state_dir.join("compile-times.tsv"); let history = if persistent.exists() { load_history(&persistent) } else { load_history(&volatile) }; let engine = PackagePolicyEngine::new().with_history(history); let binhost_available = config.packages.binary_packages && !phoebus_core::system::resolved_binhost_uri(&config).is_empty(); let policy_ctx = PolicyContext { policy: config.packages.policy, binhost_available, memory_mib: hardware.memory_mib, cores: hardware.cpu.cores, }; Self { config, hardware, disks, exec, engine, policy_ctx, state: StorageState::default(), } } pub fn plan(&self) -> InstallPlan { InstallPlan::for_config(&self.config) } /// Replace the configuration after a frontend edit, recomputing the derived /// policy context so package decisions reflect the new selection. Hardware /// and disks are unchanged by a configuration edit. pub fn reconfigure(&mut self, config: InstallConfig) { let binhost_available = config.packages.binary_packages && !phoebus_core::system::resolved_binhost_uri(&config).is_empty(); self.policy_ctx = PolicyContext { policy: config.packages.policy, binhost_available, memory_mib: self.hardware.memory_mib, cores: self.hardware.cpu.cores, }; self.config = config; } pub fn render_plan(&self) -> String { self.plan().render_human(&self.config, Some(&self.hardware)) } pub fn destructive_preview(&self) -> String { let disk = &self.config.storage.disk; let layout = probe::probe_disk_layout(self.exec.runner.as_ref(), disk); self.plan().destructive_preview(&self.config, &layout) } pub fn disk_layout(&self) -> String { probe::probe_disk_layout(self.exec.runner.as_ref(), &self.config.storage.disk) } /// Bounded system facts for AI assistance: hardware, selected profile, /// signed-binhost availability and measured compile times. No personal /// data, credentials or file contents. pub fn system_facts(&self) -> phoebus_ai::provider::SystemFacts { let persistent = self.exec.root.join("var/lib/phoebus/compile-times.tsv"); let volatile = self.exec.state_dir.join("compile-times.tsv"); let history = if persistent.exists() { load_history(&persistent) } else { load_history(&volatile) }; let binhost_available = self.config.packages.binary_packages && !phoebus_core::system::resolved_binhost_uri(&self.config).is_empty(); let disk = self .disks .iter() .find(|d| d.path == self.config.storage.disk) .map(|d| phoebus_ai::provider::DiskSummary { path: d.path.clone(), size_gib: d.size_bytes / (1024 * 1024 * 1024), ssd: d .transport .as_deref() .map(|t| t.contains("nvme")) .unwrap_or(false), }); phoebus_ai::provider::SystemFacts::from_system( &self.config, &self.hardware, &history, binhost_available, disk, ) } /// Configuration plus target-disk validation. pub fn validate(&self) -> Vec { let mut issues = validate::validate_config(&self.config); let disk = &self.config.storage.disk; if !disk.is_empty() { match self.disks.iter().find(|d| &d.path == disk) { Some(d) => { if let Some(reason) = d.protection() { issues.push(ValidationIssue::new( "target_disk", format!("refusing target {disk}: {}", reason.describe()), )); } } None => issues.push(ValidationIssue::new( "target_disk", format!("target disk {disk} was not detected on this system"), )), } } issues } /// Run the staged installation. `auth` must have been produced only after /// the destructive preview and final confirmation. pub fn install( &mut self, auth: &phoebus_executor::DestructiveAuthorization, luks_passphrase: Option<&SecretString>, user_password: Option<&SecretString>, root_password: Option<&SecretString>, ) -> Result<()> { self.install_observed( auth, luks_passphrase, user_password, root_password, &mut NoopObserver, ) } /// As [`Installer::install`], reporting each stage to `observer`. This is /// the real executor loop, not a re-implementation: the observer only sees /// transitions the backend actually performs. pub fn install_observed( &mut self, auth: &phoebus_executor::DestructiveAuthorization, luks_passphrase: Option<&SecretString>, user_password: Option<&SecretString>, root_password: Option<&SecretString>, observer: &mut dyn InstallObserver, ) -> Result<()> { let steps = self.plan().steps.clone(); for step in steps { let name = step.name(); self.exec.logger.section(name); observer.stage_started(step); let result = self.run_step(step, auth, luks_passphrase, user_password, root_password); if let Err(e) = result { self.exec.logger.error(format!("stage failed: {name}: {e}")); observer.stage_finished(step, Some(&self.exec.redactor().redact(&e.to_string()))); if !self.exec.dry_run { let _ = self.exec.export_log(); let _ = self.exec.umount_chroot(); } return Err(e); } self.exec.logger.info(format!("stage complete: {name}")); observer.stage_finished(step, None); } Ok(()) } fn run_step( &mut self, step: phoebus_core::InstallStep, auth: &phoebus_executor::DestructiveAuthorization, luks_passphrase: Option<&SecretString>, user_password: Option<&SecretString>, root_password: Option<&SecretString>, ) -> Result<()> { use phoebus_core::InstallStep::*; match step { StoragePrepare => self.storage_prepare(auth, luks_passphrase), StageInstall => self.stage_install(), FstabGenerate => self.fstab_generate(), PortageConfigure => self.portage_configure(), PackagesBase => self.packages_base(), KernelInstall => self.kernel_install(), BootInstall => self.boot_install(), UsersConfigure => self.users_configure(user_password, root_password), ServicesConfigure => self.services_configure(), DesktopInstall => self.desktop_install(), Finalize => self.finalize(auth), } } /// Re-check the selected target disk immediately before the destructive /// stage. An approval binds to a verified plan, not to a device name: the /// device may have disappeared, been mounted, become the live medium, or /// been replaced under the same name since it was chosen. Refuse to /// partition unless the disk is present, unprotected and the same device. pub fn revalidate_target_disk(&self) -> Result<()> { let disk_path = &self.config.storage.disk; if disk_path.trim().is_empty() { return Err(phoebus_executor::ExecError::operation( "storage_prepare", "revalidate target disk", "no target disk is selected", )); } let fresh = probe::probe_disks(self.exec.runner.as_ref()); let observed = match fresh.iter().find(|d| &d.path == disk_path) { Some(d) => d, None => { return Err(phoebus_executor::ExecError::operation( "storage_prepare", "revalidate target disk", format!( "target disk {disk_path} disappeared since it was selected; \ refusing to partition" ), )) } }; if let Some(reason) = observed.protection() { return Err(phoebus_executor::ExecError::operation( "storage_prepare", "revalidate target disk", format!("refusing target {disk_path}: {}", reason.describe()), )); } // Device-name reuse: if the same path now describes a different device // (size or model changed), the earlier review no longer applies. if let Some(expected) = self.disks.iter().find(|d| &d.path == disk_path) { if expected.size_bytes != 0 && observed.size_bytes != 0 && expected.size_bytes != observed.size_bytes { return Err(phoebus_executor::ExecError::operation( "storage_prepare", "revalidate target disk", format!( "target disk {disk_path} changed size since it was selected \ ({} -> {} bytes); refusing to partition", expected.size_bytes, observed.size_bytes ), )); } if let (Some(before), Some(now)) = (&expected.model, &observed.model) { if before != now { return Err(phoebus_executor::ExecError::operation( "storage_prepare", "revalidate target disk", format!( "target disk {disk_path} changed identity since it was \ selected ({before} -> {now}); refusing to partition" ), )); } } } Ok(()) } fn storage_prepare( &mut self, auth: &phoebus_executor::DestructiveAuthorization, luks_passphrase: Option<&SecretString>, ) -> Result<()> { if self.exec.dry_run { self.exec.logger.info(format!( "[dry-run] would partition and format {}", self.config.storage.disk )); self.state.root_source = format!("/dev/mapper/{}", self.config.encryption.name); self.state.luks_uuid = Some("".into()); return Ok(()); } self.revalidate_target_disk()?; storage::prepare( &self.exec, &self.config, auth, luks_passphrase, &mut self.state, ) } fn stage_install(&self) -> Result<()> { if self.exec.dry_run { self.exec .logger .info("[dry-run] would fetch and extract the stage3"); return Ok(()); } stage3::fetch(&self.exec, &self.config, &self.exec.state_dir)?; let tarball = self.exec.state_dir.join("stage3-systemd.tar.xz"); stage3::extract(&self.exec, std::path::Path::new(&self.exec.root), &tarball) } fn fstab_generate(&mut self) -> Result<()> { if self.exec.dry_run { self.exec .logger .info("[dry-run] would write fstab and crypttab"); return Ok(()); } storage::write_fstab(&self.exec, &self.config, &mut self.state)?; storage::write_crypttab(&self.exec, &self.config, &self.state)?; let target = self.exec.target(); for dir in ["var/tmp", "tmp", "root", "home"] { target.ensure_dir(dir)?; } use std::os::unix::fs::PermissionsExt; for dir in ["var/tmp", "tmp"] { if let Ok(p) = target.resolve(dir) { let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o1777)); } } if let Ok(p) = target.resolve("root") { let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o700)); } Ok(()) } fn portage_configure(&self) -> Result<()> { if self.exec.dry_run { self.exec .logger .info("[dry-run] would write Portage config and sync"); return Ok(()); } portage::write_config(&self.exec, &self.config, &self.hardware)?; self.exec.copy_resolv_conf()?; self.exec.mount_chroot()?; let root = PathBuf::from(&self.exec.root); if let Err(e) = portage::init_machine_id(&self.exec, &root) { self.exec .logger .warn(format!("could not initialise machine-id: {e}")); } let result: Result<()> = (|| { portage::sync(&self.exec, &root)?; if let Err(e) = portage::verification_setup(&self.exec, &root) { self.exec .logger .warn(format!("getuto failed; binary verification may fail: {e}")); } // The Mango desktop needs the git-only GURU overlay, so install git // from the main tree first, then sync GURU. Signature verification // stays on and the keyword set stays scoped. if phoebus_core::system::uses_guru(&self.config) { let bootstrap: Vec = portage::guru_bootstrap_packages() .into_iter() .map(str::to_string) .collect(); portage::emerge( &self.exec, &root, &bootstrap, &self.engine, &self.policy_ctx, )?; portage::sync_guru(&self.exec, &root, &self.config)?; } Ok(()) })(); self.exec.umount_chroot()?; result?; portage::select_profile(&self.exec, &self.config) } fn packages_base(&self) -> Result<()> { if self.exec.dry_run { self.exec .logger .info("[dry-run] would install base packages"); return Ok(()); } self.exec.mount_chroot()?; let packages: Vec = portage::base_packages() .into_iter() .map(str::to_string) .collect(); let result = portage::emerge( &self.exec, std::path::Path::new(&self.exec.root), &packages, &self.engine, &self.policy_ctx, ); self.exec.umount_chroot()?; if result.is_ok() { self.harvest_compile_times(); } result } /// Record measured compile times from the target's emerge.log into the /// installed system so the data survives reboot. fn harvest_compile_times(&self) { let history = match self.exec.target().var("lib/phoebus/compile-times.tsv") { Ok(p) => p, Err(_) => self.exec.state_dir.join("compile-times.tsv"), }; if let Err(e) = portage::harvest_emerge_log(&self.exec, &history) { self.exec .logger .warn(format!("compile-time instrumentation failed: {e}")); } } fn kernel_install(&self) -> Result<()> { if self.exec.dry_run { self.exec .logger .info("[dry-run] would configure and install the kernel"); return Ok(()); } kernel::write_profile(&self.exec, &self.config)?; boot::write_install_conf(&self.exec)?; boot::write_dracut_conf(&self.exec, &self.config)?; let root_source = storage::root_source_ref(&self.exec, &self.config, &self.state); kernel::write_cmdline( &self.exec, &self.config, self.state.luks_uuid.as_deref(), &root_source, )?; self.exec.mount_chroot()?; let result = kernel::install( &self.exec, &self.config, &self.hardware, &self.engine, &self.policy_ctx, ); self.exec.umount_chroot()?; if result.is_ok() { self.harvest_compile_times(); } result } fn boot_install(&self) -> Result<()> { if self.exec.dry_run { self.exec .logger .info("[dry-run] would install systemd-boot"); return Ok(()); } self.exec.mount_chroot()?; if let Err(e) = boot::install_systemd_boot(&self.exec, &self.config) { self.exec.logger.warn(format!( "bootctl install failed; relying on EFI fallback: {e}" )); } if let Err(e) = boot::generate_entries(&self.exec) { self.exec .logger .warn(format!("kernel-install reported an issue: {e}")); } self.exec.umount_chroot()?; boot::write_loader_conf(&self.exec, &self.config)?; if let Err(e) = boot::write_recovery_entry(&self.exec, &self.config) { self.exec .logger .warn(format!("could not write recovery entry: {e}")); } if let Err(e) = boot::install_fallback(&self.exec, &self.config) { self.exec .logger .warn(format!("EFI fallback not installed: {e}")); } let _ = boot::random_seed(&self.exec, &self.config); boot::verify(&self.exec, &self.config) } fn users_configure( &self, user_password: Option<&SecretString>, root_password: Option<&SecretString>, ) -> Result<()> { if self.exec.dry_run { self.exec .logger .info("[dry-run] would create the user account"); return Ok(()); } self.exec.mount_chroot()?; let result: Result<()> = (|| { users::create(&self.exec, &self.config, user_password, root_password)?; users::configure_sudo(&self.exec)?; Ok(()) })(); self.exec.umount_chroot()?; result } fn services_configure(&self) -> Result<()> { if self.exec.dry_run { self.exec .logger .info("[dry-run] would configure locale/timezone/services"); return Ok(()); } self.exec.mount_chroot()?; let result: Result<()> = (|| { services::configure(&self.exec, &self.config)?; if self.config.packages.nix { nix::install(&self.exec, std::path::Path::new(&self.exec.root))?; } Ok(()) })(); self.exec.umount_chroot()?; result } fn desktop_install(&self) -> Result<()> { if self.config.desktop.profile == phoebus_core::DesktopProfile::None { self.exec.logger.info("no desktop profile selected"); return Ok(()); } if self.exec.dry_run { self.exec .logger .info("[dry-run] would install the desktop profile"); return Ok(()); } self.exec.mount_chroot()?; let result: Result<()> = (|| { desktop::install(&self.exec, &self.config, &self.engine, &self.policy_ctx)?; desktop::write_session_script(&self.exec, &self.config)?; desktop::configure_login(&self.exec, &self.config)?; desktop::configure_flatpak(&self.exec, &self.config)?; Ok(()) })(); self.exec.umount_chroot()?; if result.is_ok() { self.harvest_compile_times(); } result } fn finalize(&self, auth: &phoebus_executor::DestructiveAuthorization) -> Result<()> { if self.exec.dry_run { self.exec.logger.info("[dry-run] finalize"); return Ok(()); } let _ = self.exec.export_log(); // Rewrite the desktop entry point last so it cannot be shadowed by an // earlier stage; a no-op for non-desktop profiles. if let Err(e) = desktop::write_session_script(&self.exec, &self.config) { self.exec .logger .warn(format!("could not write session script: {e}")); } self.create_initial_recovery_point(auth); // Durability: Btrfs commits lazily (~30s) and the installer's writes // are not fsynced; flush before unmounting so a forced poweroff cannot // lose the final files (the session script and the exported log). let _ = self.exec.run(phoebus_executor::command::CommandSpec::new( "finalize", "flush target", "sync", )); let _ = self.exec.umount_chroot(); storage::unmount_all( &self.exec, &self.config, std::path::Path::new(&self.exec.root), )?; if self.config.is_encrypted() { if let Err(e) = encryption::luks_close(&self.exec, auth, &self.config) { self.exec .logger .warn(format!("could not close LUKS device: {e}")); } } self.exec.logger.info("installation finished"); Ok(()) } /// A controlled, reversible re-check used by tests and by callers that want /// to gate a destructive action on the current disk identity. pub fn current_disks(&self) -> Vec { probe::probe_disks(self.exec.runner.as_ref()) } /// Capture an initial known-good snapshot and point a boot entry at it, so /// recovery does not depend on the (possibly later broken) live root. fn create_initial_recovery_point(&self, auth: &phoebus_executor::DestructiveAuthorization) { if self.config.storage.filesystem != Filesystem::Btrfs || !self .config .storage .subvols .iter() .any(|s| s == "@snapshots") { return; } let root = std::path::PathBuf::from(&self.exec.root); let root_str = root.to_string_lossy().to_string(); let var_source = if self.config.storage.subvols.iter().any(|s| s == "@var") { Some(root.join("var").to_string_lossy().to_string()) } else { None }; match snapshot::create_set_and_record_at( &self.exec, auth, &root, &root_str, var_source.as_deref(), "initial known-good", ) { Ok(record) => { if let Err(e) = boot::write_snapshot_recovery_entry( &self.exec, &self.config, &record.snapshot_subvol, ) { self.exec .logger .warn(format!("could not write snapshot recovery entry: {e}")); } } Err(e) => self .exec .logger .warn(format!("could not create initial recovery snapshot: {e}")), } } } #[cfg(test)] mod tests { use super::*; use phoebus_core::{Disk, DiskKind, Redactor}; use phoebus_executor::command::{CommandOutput, RecordingRunner}; use phoebus_executor::Logger; fn lsblk_output(lines: &str) -> CommandOutput { CommandOutput { status: 0, success: true, stdout: lines.as_bytes().to_vec(), stderr: Vec::new(), duration: std::time::Duration::from_millis(1), } } fn installer(target: &str, lsblk: &str) -> Installer { let runner = RecordingRunner::new(); runner.set_response("lsblk", lsblk_output(lsblk)); let dir = tempfile::tempdir().unwrap().keep(); let logger = Logger::open(dir.join("install.log"), Redactor::new(), false); let mut config = InstallConfig::default(); config.storage.disk = target.to_string(); let exec = Exec::new(Box::new(runner), logger, false, dir.join("root"), dir); Installer::new(config, exec) } const VDA_OK: &str = "NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n"; const VDA_READONLY: &str = "NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"1\"\n"; const VDB_ONLY: &str = "NAME=\"vdb\" MODEL=\"OTHER\" SIZE=\"10737418240\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n"; #[test] fn revalidation_accepts_the_same_observed_disk() { let installer = installer("/dev/vda", VDA_OK); assert!(installer.revalidate_target_disk().is_ok()); } #[test] fn revalidation_refuses_a_disappeared_disk() { let installer = installer("/dev/vda", VDB_ONLY); let err = installer.revalidate_target_disk().unwrap_err().to_string(); assert!(err.contains("disappeared"), "{err}"); } #[test] fn revalidation_refuses_a_now_protected_disk() { let installer = installer("/dev/vda", VDA_READONLY); let err = installer.revalidate_target_disk().unwrap_err().to_string(); assert!(err.contains("read-only"), "{err}"); } #[test] fn revalidation_refuses_reused_device_name_with_a_new_size() { let mut installer = installer("/dev/vda", VDA_OK); // The reviewed device had a different size; the name now points at a // different disk. installer.disks = vec![Disk { path: "/dev/vda".into(), model: Some("QEMU HARDDISK".into()), size_bytes: 8 * 1024 * 1024 * 1024, transport: Some("virtio".into()), removable: false, read_only: false, mounted: false, is_block_device: true, kind: DiskKind::Physical, live_media: false, }]; let err = installer.revalidate_target_disk().unwrap_err().to_string(); assert!(err.contains("changed size"), "{err}"); } #[test] fn revalidation_refuses_reused_device_name_with_a_new_model() { let mut installer = installer("/dev/vda", VDA_OK); installer.disks = vec![Disk { path: "/dev/vda".into(), model: Some("A DIFFERENT DISK".into()), size_bytes: 32_212_254_720, transport: Some("virtio".into()), removable: false, read_only: false, mounted: false, is_block_device: true, kind: DiskKind::Physical, live_media: false, }]; let err = installer.revalidate_target_disk().unwrap_err().to_string(); assert!(err.contains("changed identity"), "{err}"); } }