//! 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, DesktopProfile, Filesystem, HardwareReport, InstallConfig, InstallPlan, SecretString, }; use phoebus_executor::storage::StorageState; use phoebus_executor::{ boot, boot_assessment, 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, /// Validated installer-time credentials held in memory only (never in /// `InstallConfig`). Written into the new user's `~/.config/phoebus/ai.key` /// at finalize when `ai.reuse_ai_connection` is true (default). pending_ai_key: Option, pending_opencode_password: Option, /// Measured per-stage durations for the running install (real elapsed /// seconds, recorded by `install_observed` for the metrics report). stage_seconds: Vec<(String, u64)>, install_began: Option, /// Peak observed target-filesystem use in MiB (best-effort per-stage /// `df` samples; 0 means unmeasured, never fabricated). peak_disk_mib: u64, } /// 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(), pending_ai_key: None, pending_opencode_password: None, stage_seconds: Vec::new(), install_began: None, peak_disk_mib: 0, } } /// Hold the validated installer-time credential in memory for finalization. /// The secret is registered with the redactor immediately and never enters /// `InstallConfig`, logs, prompts or transcripts. pub fn set_pending_ai_credentials( &mut self, api_key: Option, opencode_password: Option, ) { if let Some(k) = &api_key { self.exec.register_secret(k); } if let Some(p) = &opencode_password { self.exec.register_secret(p); } self.pending_ai_key = api_key; self.pending_opencode_password = opencode_password; } 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()), )); } // Improved space estimates: the workstation profile needs // substantially more download/build/storage than headless. // Fail here with the exact requirement instead of mid-emerge. let required = phoebus_core::system::required_disk_gib(self.config.desktop.profile); let have_gib = d.size_bytes / (1024 * 1024 * 1024); if have_gib < required { issues.push(ValidationIssue::new( "target_disk", format!( "target disk {disk} is {have_gib} GiB; the {:?} profile requires at least {required} GiB \ (download + build + installed system)", self.config.desktop.profile, ), )); } } 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(); self.install_began = Some(std::time::Instant::now()); self.stage_seconds.clear(); self.peak_disk_mib = 0; for step in steps { let name = step.name(); self.exec.logger.section(name); observer.stage_started(step); // Best-effort peak-disk sample of the mounted target (skipped on // dry-run or when the target is not yet mounted). self.sample_peak_disk(); let began = std::time::Instant::now(); let result = self.run_step(step, auth, luks_passphrase, user_password, root_password); self.stage_seconds .push((name.to_string(), began.elapsed().as_secs())); 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(), NvidiaDrivers => self.nvidia_drivers(), BootInstall => self.boot_install(), UsersConfigure => self.users_configure(user_password, root_password), ServicesConfigure => self.services_configure(), DesktopInstall => self.desktop_install(), Finalize => self.finalize(auth), } } /// Best-effort per-stage sample of target-filesystem use for the peak-disk /// figure. Never fails the install; when the target is not mounted (or on /// dry-run) the sample is skipped and the metric stays unmeasured. fn sample_peak_disk(&mut self) { if self.exec.dry_run { return; } let root = self.exec.root.clone(); if !std::path::Path::new(&root).is_dir() { return; } let root_str = root.to_string_lossy().to_string(); let spec = phoebus_executor::command::CommandSpec::new("metrics", "sample target use", "df") .args(["-BM", "--output=used", root_str.as_str()]); let Ok(out) = self.exec.run_capture(spec) else { return; }; // Output is a header line plus e.g. ` 12345M`. for line in String::from_utf8_lossy(&out.stdout).lines().skip(1) { let digits: String = line.chars().filter(|c| c.is_ascii_digit()).collect(); if let Ok(mib) = digits.parse::() { if mib > self.peak_disk_mib { self.peak_disk_mib = mib; } } } } /// Write the measured installation report into the target (before /// unmount) and log it. Times are real; sizes are best-effort host-side /// measurements of the target; anything unmeasurable is reported as /// "not measured", never estimated silently. fn write_install_metrics(&self) { use phoebus_core::fastinstall::InstallMetrics; let total = self .install_began .map(|t| t.elapsed().as_secs()) .unwrap_or(0); let root_str = self.exec.root.to_string_lossy().to_string(); let installed_mib = du_mib(&self.exec, &root_str); let distfiles = du_mib(&self.exec, &format!("{root_str}/var/cache/distfiles")); let binpkgs = du_mib(&self.exec, &format!("{root_str}/var/cache/binpkgs")); let download_mib = match (distfiles, binpkgs) { (0, 0) => 0, (d, b) => d + b, }; let metrics = InstallMetrics { total_seconds: total, download_mib, peak_disk_mib: self.peak_disk_mib, installed_mib, per_stage_seconds: self.stage_seconds.clone(), }; let report = metrics.report(); for line in report.lines() { self.exec.logger.info(line); } let _ = self .exec .target() .write("var/lib/phoebus/install-metrics.txt", report); } /// 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::require_tools(&self.exec)?; if self.config.is_encrypted() { self.exec.require_tools(&["cryptsetup"])?; if luks_passphrase.is_none() || luks_passphrase .map(|p| p.expose().is_empty()) .unwrap_or(true) { return Err(phoebus_executor::ExecError::operation( "storage_prepare", "validate secrets", "encryption is enabled but no LUKS passphrase was supplied", )); } } if let Err(e) = phoebus_executor::sys_runtime::find_trusted_sys_binary() { return Err(phoebus_executor::ExecError::operation( "storage_prepare", "check sys runtime", format!("required sys runtime is missing or unusable: {e}"), )); } 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(()); } // Fail fast when the stage3 verifier (gpg, hashes, download tools) is // missing: an unverifiable stage3 must never reach extraction. stage3::require_tools(&self.exec)?; 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)?; } // Brave (stable only) via another-brave-overlay at the reviewed // pin, scoped so unrelated packages cannot override Gentoo. A // missing/placeholder pin refuses before any network use. if self.config.desktop.profile.is_desktop() { portage::sync_brave(&self.exec, &root, &self.config)?; } // Demonstrate the default ccache path (installed in base); // best-effort and never fatal. let _ = portage::verify_ccache_hit(&self.exec, &root); Ok(()) })(); self.exec.umount_chroot()?; result?; portage::select_profile(&self.exec, &self.config)?; // Portage can leave `repos.conf` unreadable to normal users; normalise // it so read-only `sys` package queries work without elevation. portage::normalize_config_permissions(std::path::Path::new(&self.exec.root)); Ok(()) } 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, &self.hardware)?; 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 } /// Install the NVIDIA accelerated driver selected from the PCI device IDs. /// /// A no-op on machines with no supported NVIDIA GPU (nouveau fallback). The /// initramfs generated during `KernelInstall` predates the module build, so /// it is regenerated here to embed the modules and their firmware. A failure /// fails the install: it must never be reported as successful NVIDIA /// support. fn nvidia_drivers(&self) -> Result<()> { let plan = phoebus_core::nvidia::NvidiaPlan::for_hardware(&self.hardware); if !plan.supported { self.exec .logger .info(format!("NVIDIA: no driver installed; {}", plan.reason)); return Ok(()); } if self.exec.dry_run { self.exec.logger.info(format!( "[dry-run] would install {} ({}) and regenerate the initramfs", phoebus_core::nvidia::GENTOO_ATOM, plan.branch )); return Ok(()); } self.exec.mount_chroot()?; let result: Result<()> = (|| { let packages = vec![phoebus_core::nvidia::GENTOO_ATOM.to_string()]; portage::emerge( &self.exec, std::path::Path::new(&self.exec.root), &packages, &self.engine, &self.policy_ctx, )?; // The modules exist now: force them into the initramfs, prove they // were actually built for the selected kernel, then regenerate the // boot image. A driver that produced no modules fails the install. boot::write_nvidia_dracut_conf(&self.exec, &self.hardware)?; let installed = boot::verify_nvidia_modules(&self.exec.root)?; boot::generate_entries(&self.exec)?; self.record_nvidia(&plan, &installed)?; Ok(()) })(); self.exec.umount_chroot()?; if result.is_ok() { self.harvest_compile_times(); } result } /// Persist the resolved driver decision and the *actual* installed version /// in the target, so post-install inspection and recovery know exactly what /// was selected rather than only a "current" label. fn record_nvidia( &self, plan: &phoebus_core::nvidia::NvidiaPlan, installed: &boot::InstalledNvidia, ) -> Result<()> { let mut text = String::new(); text.push_str("# Resolved NVIDIA accelerated driver (generated by the installer).\n"); text.push_str(&format!( "version={}\n", if installed.version.is_empty() { "unknown" } else { &installed.version } )); text.push_str(&format!("kernel={}\n", installed.kernel)); text.push_str(&format!("branch={}\n", plan.branch)); text.push_str(&format!( "flavor={}\n", plan.flavor.map(|f| f.as_str()).unwrap_or("none") )); text.push_str(&format!( "generation={}\n", plan.generation.map(|g| g.as_str()).unwrap_or("none") )); text.push_str("package=x11-drivers/nvidia-drivers\n"); for module in &installed.modules { text.push_str(&format!("module={module}\n")); } for device in &plan.devices { text.push_str(&format!( "device={} {}\n", device.pci_id, device.generation.map(|g| g.as_str()).unwrap_or("unknown") )); } text.push_str(&format!("reason={}\n", plan.reason)); self.exec.target().write("etc/phoebus/nvidia", text)?; self.exec.logger.info(format!( "recorded the NVIDIA driver selection in /etc/phoebus/nvidia (version {}, kernel {}, modules: {})", if installed.version.is_empty() { "unknown" } else { &installed.version }, installed.kernel, installed.modules.join(", ") )); Ok(()) } 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}")); } boot_assessment::install_boot_health_check(&self.exec)?; 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)?; users::configure_polkit_admin(&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)?; // Fast defaults, target-only: system-wide Flatpaks from Flathub. // The review UI already showed the delivery set (see // `fastinstall::delivery_summary` in the plan); log it again here // so progress output names the chosen method and expected work. for line in phoebus_core::fastinstall::delivery_summary().lines() { self.exec.logger.info(line); } desktop::install_flatpak_apps(&self.exec, &self.config)?; desktop::provision_installed_welcome(&self.exec, &self.config)?; Ok(()) })(); self.exec.umount_chroot()?; if result.is_ok() { self.harvest_compile_times(); } result } fn finalize(&mut 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(); // 1. Install matching sys runtime into target before recovery snapshot. phoebus_executor::sys_runtime::install_sys_to_target(&self.exec)?; // 2. Persist non-secret assistant configuration so `sudo sys ask` keeps its settings. // When "Use this model connection after installation" is selected // (default), the validated installer credential is written into the // new user's ~/.config/phoebus/ai.key (0700/0600, user-owned, // symlink-safe) and only the credential *path* is stored in config. // OpenCode and local-model connections follow their actual // requirements: a live-VM-only endpoint is never called "connected" // after reboot. self.persist_ai_connection()?; if self.config.ai.enabled || !self.config.ai.provider.is_empty() || !self.config.ai.opencode_server.is_empty() { if let Ok(toml_str) = toml::to_string(&self.config.ai) { let _ = self .exec .target() .write("etc/phoebus/assistant.conf", toml_str); } } // 2b. Persist the non-secret installation configuration so the // installed `sys` loads the real settings (desktop, filesystem, // package policy, groups) instead of assuming defaults. There are no // secrets in `InstallConfig`; passphrases are handled separately. if let Ok(toml_str) = self.config.to_toml_string() { self.exec .target() .write("etc/phoebus/install.toml", toml_str)?; } // 3. Rewrite the desktop entry point last so it cannot be shadowed by an // earlier stage; a no-op for non-desktop profiles. desktop::write_session_script(&self.exec, &self.config)?; // 3b. Portage can re-chmod `/etc/portage/repos.conf` during a sync or // emerge; normalise it last so non-root read-only catalogue queries // (`sys search/list/info`) work on the installed system. portage::normalize_config_permissions(std::path::Path::new(&self.exec.root)); // 4. Verify target integrity before snapshotting and unmounting. self.verify_installed_system()?; // 4b. Record measured installation time and sizes. self.sample_peak_disk(); self.write_install_metrics(); // 5. Initial known-good recovery point snapshot and boot entry. self.create_initial_recovery_point(auth)?; // Only arm the changing BLS filename once the snapshot-based recovery // entry exists. Rewrite loader.conf with a stable wildcard default. let entries = boot::esp_path(&self.exec, &self.config).join("loader/entries"); if self.config.storage.filesystem == Filesystem::Btrfs { let recovery = entries.join("phoebus-recovery.conf"); let recovery_text = std::fs::read_to_string(&recovery) .map_err(|e| phoebus_executor::ExecError::io(recovery.clone(), e))?; if !recovery_text.contains("@snapshots/") { return Err(phoebus_executor::ExecError::operation( "finalize", "arm boot assessment", "snapshot-based recovery entry is missing", )); } boot_assessment::enable_boot_counting(&entries, boot_assessment::DEFAULT_BOOT_TRIES)?; boot::write_loader_conf(&self.exec, &self.config)?; } // 6. Durability flush before unmounting. self.exec.run(phoebus_executor::command::CommandSpec::new( "finalize", "flush target", "sync", ))?; // 7. Unmount chroot and filesystems. let umount_chroot_res = self.exec.umount_chroot(); let unmount_res = 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}")); } } umount_chroot_res?; unmount_res?; self.exec.logger.info("installation finished"); Ok(()) } /// Write the installer-time AI credential into the new user's /// `~/.config/phoebus/ai.key` when reuse is selected (default). /// /// Symlink-safe target writes, a 0700 parent directory, a 0600 file and /// correct ownership. Only the credential path enters `assistant.conf`; /// the key itself never enters config, logs, prompts or transcripts. /// Missing/invalid/unreadable/opted-out credentials fail closed with a /// setup action and the real error — never a false "Connected". fn persist_ai_connection(&mut self) -> Result<()> { if !self.config.ai.reuse_ai_connection { self.exec .logger .info("AI connection reuse declined; no credential written"); return Ok(()); } let backend = self.config.ai.backend; let username = self.config.user.username.clone(); if username.is_empty() { return Ok(()); } let home_base = self.config.user.home.trim_end_matches('/').to_string(); // Local models need no key; OpenCode server credentials follow the // OpenCode path. A live-VM-only endpoint is not "connected" after // reboot and is not persisted as one. if backend == phoebus_core::AiBackend::OpenCode { if let Some(pw) = self.pending_opencode_password.clone() { if pw.is_empty() { return Ok(()); } let dir_rel = format!("{}/{}/.config/phoebus", home_base, username) .trim_start_matches('/') .to_string(); let file_rel = format!("{dir_rel}/opencode.key"); self.write_user_secret(&dir_rel, &file_rel, &pw, &username)?; self.config.ai.opencode_credential_file = format!("/{file_rel}"); self.exec .logger .info("persisted OpenCode credential for the new user"); } return Ok(()); } // Direct provider: only keyed providers persist a key. A local model // (`provider == local` or empty with local semantics) needs none. let provider = self.config.ai.provider.to_ascii_lowercase(); if provider.is_empty() || provider == "local" || provider == "none" { return Ok(()); } let key = match self.pending_ai_key.clone() { Some(k) if !k.is_empty() => k, _ => { self.exec.logger.warn( "AI reuse selected but no installer credential is held; \ the installed assistant will show a setup action", ); return Ok(()); } }; let dir_rel = format!("{}/{}/.config/phoebus", home_base, username) .trim_start_matches('/') .to_string(); let file_rel = format!("{dir_rel}/ai.key"); self.write_user_secret(&dir_rel, &file_rel, &key, &username)?; self.config.ai.direct_credential_file = format!("/{file_rel}"); self.exec .logger .info("persisted AI credential for the new user (0600)"); Ok(()) } fn write_user_secret( &self, dir_rel: &str, file_rel: &str, secret: &SecretString, username: &str, ) -> Result<()> { #[allow(unused_imports)] use std::os::unix::fs::PermissionsExt; let target = self.exec.target(); // Symlink-safe: TargetRoot rejects symlink components on ensure/write. target.ensure_dir_mode(dir_rel, 0o700)?; let path = target.resolve(file_rel).map_err(|e| { phoebus_executor::ExecError::operation( "finalize", "resolve AI credential path", e.to_string(), ) })?; // Refuse to follow or overwrite a symlink. if path.is_symlink() { return Err(phoebus_executor::ExecError::operation( "finalize", "write AI credential", "refused to overwrite a symlink", )); } std::fs::write(&path, format!("{}\n", secret.expose())) .map_err(|e| phoebus_executor::ExecError::io(path.clone(), e))?; std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)) .map_err(|e| phoebus_executor::ExecError::io(path.clone(), e))?; // Correct ownership (best-effort in chroot; the file is already 0600). let root = std::path::Path::new(&self.exec.root); let arg = format!("{username}:{username}"); let rel_arg = format!("/{}", file_rel.trim_start_matches('/')); let _ = portage::chroot(&self.exec, root, "chown", &[&arg, &rel_arg]); let dir_arg = format!("/{dir_rel}"); let _ = portage::chroot(&self.exec, root, "chown", &[&arg, &dir_arg]); Ok(()) } /// Check that required installed components and configuration for the selected profile exist. pub fn verify_installed_system(&self) -> Result<()> { if self.exec.dry_run { self.exec.logger.info("[dry-run] verify_installed_system"); return Ok(()); } self.exec .logger .info("verifying installed target integrity"); let target = self.exec.target(); // 1. sys CLI binary must be present in target root and executable if !target.exists("usr/local/bin/sys") { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", "required runtime /usr/local/bin/sys is missing in target root", )); } // 2. Boot loader and kernel let has_loader = target.exists("boot/loader/loader.conf") || target.exists("efi/loader/loader.conf") || target.exists("boot/grub/grub.cfg"); if !has_loader { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", "boot loader configuration (systemd-boot/grub) missing in target", )); } let root_p = std::path::Path::new(&self.exec.root); if !target_has_kernel(root_p) { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", "no kernel image found in the target boot/efi tree", )); } // 3. Desktop profile artifacts if self.config.desktop.profile.is_desktop() { match self.config.desktop.profile { DesktopProfile::Mango => { if !target.exists("usr/local/bin/phoebus-session-mango") { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", "session script /usr/local/bin/phoebus-session-mango missing", )); } if !target.exists("etc/xdg/mango/config.conf") { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", "Mango configuration /etc/xdg/mango/config.conf missing", )); } } DesktopProfile::None => {} } if !target.exists("etc/greetd/config.toml") { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", "login configuration /etc/greetd/config.toml missing", )); } let passwd = target.read_to_string("etc/passwd").unwrap_or_default(); if !passwd.lines().any(|l| l.starts_with("greeter:")) { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", "greeter user account missing from target /etc/passwd", )); } // Workstation defaults: cursor theme, Nemo default, local CUPS, // Zsh skeleton. sshd must stay disabled (no enablement symlink). for rel in [ "etc/xdg/mango/cursor-env.sh", "etc/profile.d/phoebus-cursor.sh", "etc/xdg/mimeapps.list", "etc/cups/cupsd.conf", "etc/skel/.zshrc", "etc/zsh/zprofile", ] { if !target.exists(rel) { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", format!("workstation default {rel} missing"), )); } } if target.exists("etc/systemd/system/multi-user.target.wants/sshd.service") { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", "sshd is enabled; it must stay disabled by default", )); } // Fast defaults: the -bin atoms are installed, the Flatpak // manifest names every default app, no duplicate Portage copies // of Calibre/GIMP exist, and the installed welcome is present // (script + launcher + autostart). The live-only installer entry // must not be on the installed system. for rel in [ "usr/local/bin/phoebus-welcome", "usr/share/applications/phoebus-welcome.desktop", "usr/share/applications/phoebus-assistant.desktop", "etc/xdg/autostart/phoebus-welcome.desktop", "etc/xdg/quickshell/phoebus-welcome-installed/shell.qml", "var/lib/phoebus/flatpaks-installed", ] { if !target.exists(rel) { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", format!("fast-default artifact {rel} missing"), )); } } for (category, name) in [ ("www-client", "firefox-bin"), ("app-office", "libreoffice-bin"), ] { if !has_vdb_record(std::path::Path::new(&self.exec.root), category, name) { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", format!("{category}/{name} has no package-database record in the target"), )); } } for (category, name) in [("app-text", "calibre"), ("media-gfx", "gimp")] { if has_vdb_record(std::path::Path::new(&self.exec.root), category, name) { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", format!("duplicate Portage copy under var/db/pkg/{category}/{name}; Calibre/GIMP must be Flatpak-only"), )); } } if target.exists("usr/share/applications/phoebus-install.desktop") { return Err(phoebus_executor::ExecError::operation( "finalize", "verify target", "live-only installer entry must not be on the installed system", )); } } self.exec .logger .info("target integrity verification passed"); 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, ) -> Result<()> { if self.config.storage.filesystem != Filesystem::Btrfs || !self .config .storage .subvols .iter() .any(|s| s == "@snapshots") { return Ok(()); } 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 }; let record = snapshot::create_set_and_record_at( &self.exec, auth, &root, &root_str, var_source.as_deref(), "initial known-good", )?; boot::write_snapshot_recovery_entry(&self.exec, &self.config, &record.snapshot_subvol) } } /// Best-effort host-side `du -sm` of a target path. Returns 0 (unmeasured) /// when the path is missing or the tool fails; never fails the install. fn du_mib(exec: &Exec, path: &str) -> u64 { if exec.dry_run || !std::path::Path::new(path).exists() { return 0; } let spec = phoebus_executor::command::CommandSpec::new("metrics", "measure target size", "du") .args(["-sm", "--apparent-size", path]); let Ok(out) = exec.run_capture(spec) else { return 0; }; let text = String::from_utf8_lossy(&out.stdout); text.split_whitespace() .next() .and_then(|n| n.parse::().ok()) .unwrap_or(0) } /// Whether the target has an installed kernel image. /// /// With `layout=bls`, systemd's `kernel-install` places the kernel as /// `///linux` (not a top-level `vmlinuz`), so a /// shallow scan is not enough. A BLS entry that names a kernel is equally /// authoritative. Symlinks are not followed, so the scan cannot escape the /// target root. fn target_has_kernel(root: &std::path::Path) -> bool { for sub in ["boot", "efi"] { let dir = root.join(sub); if dir.is_dir() && dir_has_kernel(&dir, 0) { return true; } let entries = dir.join("loader/entries"); if let Ok(read) = std::fs::read_dir(&entries) { for entry in read.flatten() { if let Ok(text) = std::fs::read_to_string(entry.path()) { if text.lines().any(|line| { let t = line.trim_start(); t.starts_with("linux ") || t.starts_with("kernel ") }) { return true; } } } } } false } fn dir_has_kernel(dir: &std::path::Path, depth: usize) -> bool { if depth > 3 { return false; } let Ok(entries) = std::fs::read_dir(dir) else { return false; }; for entry in entries.flatten() { let path = entry.path(); let Ok(meta) = std::fs::symlink_metadata(&path) else { continue; }; if meta.file_type().is_symlink() { continue; } if meta.is_dir() { if dir_has_kernel(&path, depth + 1) { return true; } } else if meta.is_file() { let name = entry.file_name().to_string_lossy().to_string(); if name == "linux" || name.starts_with("vmlinuz") || name.starts_with("kernel") { return true; } } } false } /// Whether the target package database holds a record for `category/name`. /// /// The VDB layout is `var/db/pkg//-` (a directory /// per installed version), so the check matches the `name-` prefix inside /// the category directory. Matching a literal `category/name` directory /// always fails: such a directory never exists, which once failed every /// install at finalize time. fn has_vdb_record(root: &std::path::Path, category: &str, name: &str) -> bool { let dir = root.join("var/db/pkg").join(category); let Ok(entries) = std::fs::read_dir(&dir) else { return false; }; let prefix = format!("{name}-"); entries .flatten() .any(|e| e.file_name().to_string_lossy().starts_with(prefix.as_str())) } #[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}"); } #[test] fn vdb_records_match_name_version_dirs_not_literal_names() { let root = tempfile::tempdir().unwrap(); let root = root.path(); // Real VDB layout: var/db/pkg//-. let vdb = root.join("var/db/pkg/www-client/firefox-bin-156.0.1"); std::fs::create_dir_all(&vdb).unwrap(); assert!(has_vdb_record(root, "www-client", "firefox-bin")); assert!(!has_vdb_record(root, "www-client", "chromium")); assert!(!has_vdb_record(root, "app-office", "libreoffice-bin")); // A literal `category/name` directory is NOT a record (the old // finalize check matched this and failed every install). let literal = root.join("var/db/pkg/app-text/calibre"); std::fs::create_dir_all(&literal).unwrap(); assert!(!has_vdb_record(root, "app-text", "calibre")); } #[test] fn target_kernel_detection_handles_the_bls_layout() { let root = tempfile::tempdir().unwrap(); let root = root.path(); // A BLS/machine-id kernel is nested and named `linux`, not `vmlinuz`. let nested = root.join("efi/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/6.18.48"); std::fs::create_dir_all(&nested).unwrap(); std::fs::write(nested.join("linux"), b"\x1f\x8b").unwrap(); assert!(target_has_kernel(root)); // A BLS entry that names a kernel is also sufficient. let root2 = tempfile::tempdir().unwrap(); let root2 = root2.path(); let entries = root2.join("efi/loader/entries"); std::fs::create_dir_all(&entries).unwrap(); std::fs::write( entries.join("deadbeef-6.18.48.conf"), "title Gentoo\nlinux /aaaa/6.18.48/linux\n", ) .unwrap(); assert!(target_has_kernel(root2)); // An empty tree has no kernel. let root3 = tempfile::tempdir().unwrap(); std::fs::create_dir_all(root3.path().join("efi/loader")).unwrap(); assert!(!target_has_kernel(root3.path())); } #[test] fn small_disk_is_rejected_with_the_exact_requirement() { let mut inst = installer("/dev/vda", VDA_OK); // 30 GiB is below the 60 GiB workstation minimum. inst.config.desktop.profile = DesktopProfile::Mango; let issues = inst.validate(); assert!( issues .iter() .any(|i| i.message.contains("requires at least 60 GiB")), "{issues:?}" ); inst.config.desktop.profile = DesktopProfile::None; assert!( inst.validate() .iter() .all(|i| !i.message.contains("requires at least")), "headless 30 GiB must pass" ); } #[test] fn ai_reuse_writes_a_0600_user_key_and_only_the_path_enters_config() { use std::os::unix::fs::PermissionsExt; let mut inst = installer("/dev/vda", VDA_OK); inst.config.user.username = "ada".into(); inst.config.user.home = "/home".into(); inst.config.ai.provider = "deepseek".into(); inst.config.ai.reuse_ai_connection = true; inst.set_pending_ai_credentials(Some(SecretString::new("sk-test-key")), None); inst.persist_ai_connection().unwrap(); assert_eq!( inst.config.ai.direct_credential_file, "/home/ada/.config/phoebus/ai.key" ); let path = inst .exec .target() .resolve("home/ada/.config/phoebus/ai.key") .unwrap(); assert_eq!(std::fs::read_to_string(&path).unwrap(), "sk-test-key\n"); assert_eq!( std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600 ); let dir = inst .exec .target() .resolve("home/ada/.config/phoebus") .unwrap(); assert_eq!( std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700 ); } #[test] fn ai_opt_out_missing_and_local_never_write_a_key() { // Opted out: nothing written, path stays empty. let mut inst = installer("/dev/vda", VDA_OK); inst.config.user.username = "ada".into(); inst.config.ai.provider = "deepseek".into(); inst.config.ai.reuse_ai_connection = false; inst.set_pending_ai_credentials(Some(SecretString::new("sk-x")), None); inst.persist_ai_connection().unwrap(); assert!(inst.config.ai.direct_credential_file.is_empty()); assert!(!inst.exec.target().exists("home/ada/.config/phoebus/ai.key")); // Selected but no credential held: fail closed without a key, no leak. let mut inst = installer("/dev/vda", VDA_OK); inst.config.user.username = "ada".into(); inst.config.ai.provider = "deepseek".into(); inst.config.ai.reuse_ai_connection = true; inst.set_pending_ai_credentials(None, None); inst.persist_ai_connection().unwrap(); assert!(inst.config.ai.direct_credential_file.is_empty()); // Local model: no key required, nothing written. let mut inst = installer("/dev/vda", VDA_OK); inst.config.user.username = "ada".into(); inst.config.ai.provider = "local".into(); inst.config.ai.reuse_ai_connection = true; inst.set_pending_ai_credentials(Some(SecretString::new("sk-x")), None); inst.persist_ai_connection().unwrap(); assert!(inst.config.ai.direct_credential_file.is_empty()); } #[test] fn ai_credential_symlink_is_refused() { let mut inst = installer("/dev/vda", VDA_OK); inst.config.user.username = "ada".into(); inst.config.user.home = "/home".into(); inst.config.ai.provider = "deepseek".into(); inst.config.ai.reuse_ai_connection = true; inst.set_pending_ai_credentials(Some(SecretString::new("sk-x")), None); // Plant a symlink where the key would go; TargetRoot must refuse. let dir = inst .exec .target() .resolve("home/ada/.config/phoebus") .unwrap(); std::fs::create_dir_all(dir.parent().unwrap()).unwrap(); #[cfg(unix)] std::os::unix::fs::symlink("/tmp", &dir).unwrap(); let err = inst.persist_ai_connection().unwrap_err().to_string(); assert!(!err.contains("sk-x"), "secret leaked into error: {err}"); } #[test] fn install_metrics_report_is_written_and_truthful() { let mut inst = installer("/dev/vda", VDA_OK); inst.stage_seconds = vec![("desktop_install".into(), 300)]; // The recording runner answers nothing: sizes stay unmeasured rather // than fabricated. inst.write_install_metrics(); let text = std::fs::read_to_string( std::path::Path::new(&inst.exec.root).join("var/lib/phoebus/install-metrics.txt"), ) .unwrap(); assert!(text.contains("Installation measurements"), "{text}"); assert!(text.contains("desktop_install"), "{text}"); assert!(text.contains("not measured"), "{text}"); // The plan review names the delivery method and expected work. let review = inst.render_plan(); assert!(review.contains("firefox-bin"), "{review}"); assert!(review.contains("Flatpak system (Flathub)"), "{review}"); assert!(review.contains("no local compile"), "{review}"); } }