//! Trusted discovery, installation, and verification of the `sys` deterministic CLI runtime //! in the installed target system. //! //! The `sys` CLI is an essential, defining subsystem of Phoebus OS: it provides the typed, //! validated execution boundary for both the AI assistant and the deterministic, network-free //! recovery fallback. It must be present in the target root before the initial recovery snapshot //! is taken. use std::path::{Path, PathBuf}; use crate::error::{ExecError, Result}; use crate::exec::Exec; use crate::portage; /// Known trusted system locations where the installer / live medium places the static `sys` binary. /// Notice that arbitrary user-controlled PATH entries are NOT searched. const TRUSTED_SYS_PATHS: &[&str] = &[ "/usr/local/bin/sys", "/run/live/medium/phoebus/bin/sys", "/usr/bin/sys", ]; /// Validate that a candidate path points to a usable, executable ELF binary. pub fn validate_sys_payload(path: &Path) -> Result<()> { if !path.is_file() { return Err(ExecError::operation( "sys_runtime", "validate sys binary", format!("path is not a regular file: {}", path.display()), )); } use std::io::Read; let mut file = std::fs::File::open(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?; let mut magic = [0u8; 4]; let n = file .read(&mut magic) .map_err(|e| ExecError::io(path.to_path_buf(), e))?; if n < 4 || &magic != b"\x7fELF" { return Err(ExecError::operation( "sys_runtime", "validate sys binary", format!( "{} is not a valid ELF executable (bad magic)", path.display() ), )); } use std::os::unix::fs::PermissionsExt; let meta = file .metadata() .map_err(|e| ExecError::io(path.to_path_buf(), e))?; if meta.permissions().mode() & 0o111 == 0 { return Err(ExecError::operation( "sys_runtime", "validate sys binary", format!("{} is not executable", path.display()), )); } Ok(()) } /// Locate a trusted `sys` executable from the installer distribution. /// /// Order of discovery: /// 1. Explicit environment override `PHOEBUS_SYS_PATH`. /// 2. Sibling binary in the same directory as the current running executable. /// 3. Well-known trusted distribution paths on the live system. pub fn find_trusted_sys_binary() -> Result { if let Some(explicit) = std::env::var_os("PHOEBUS_SYS_PATH") { let p = PathBuf::from(explicit); validate_sys_payload(&p).map_err(|e| { ExecError::operation( "sys_runtime", "find sys runtime", format!("PHOEBUS_SYS_PATH invalid: {e}"), ) })?; return Ok(p); } if let Ok(current) = std::env::current_exe() { if let Some(parent) = current.parent() { let candidate = parent.join("sys"); if candidate.is_file() && validate_sys_payload(&candidate).is_ok() { return Ok(candidate); } } } for path_str in TRUSTED_SYS_PATHS { let candidate = Path::new(path_str); if candidate.is_file() && validate_sys_payload(candidate).is_ok() { return Ok(candidate.to_path_buf()); } } Err(ExecError::operation( "sys_runtime", "find sys runtime", format!( "trusted sys binary not found; checked current_exe sibling and [{}]", TRUSTED_SYS_PATHS.join(", ") ), )) } /// Install the `sys` binary into the target filesystem and verify it executes properly. pub fn install_sys_to_target(exec: &Exec) -> Result { let target = exec.target(); if exec.dry_run { exec.logger .info("[dry-run] would install sys runtime to /usr/local/bin/sys"); return target.resolve("usr/local/bin/sys").map_err(|e| { ExecError::operation("sys_runtime", "resolve target path", e.to_string()) }); } let source_path = find_trusted_sys_binary()?; exec.logger.info(format!( "installing sys runtime from {} to /usr/local/bin/sys in target", source_path.display() )); let dest = target .copy_file("usr/local/bin/sys", &source_path, 0o755) .map_err(|e| { ExecError::operation( "sys_runtime", "copy sys to target", format!("failed to install sys binary: {e}"), ) })?; // Verify target binary exists and is executable validate_sys_payload(&dest).map_err(|e| { ExecError::operation( "sys_runtime", "verify installed sys", format!("installed target binary invalid: {e}"), ) })?; // Verify execution inside target chroot: run harmless deterministic `sys history` let root = Path::new(&exec.root); portage::chroot(exec, root, "/usr/local/bin/sys", &["history"]).map_err(|e| { ExecError::operation( "sys_runtime", "verify sys in chroot", format!("running sys history in target chroot failed: {e}"), ) })?; exec.logger .info("verified installed sys CLI execution in target"); Ok(dest) } #[cfg(test)] mod tests { use super::*; use crate::command::RecordingRunner; use crate::log::Logger; use phoebus_core::Redactor; use std::io::Write; use std::os::unix::fs::PermissionsExt; fn make_exec(runner: RecordingRunner) -> Exec { let path = tempfile::tempdir().unwrap().keep(); let logger = Logger::open(path.join("l.log"), Redactor::new(), false); Exec::new(Box::new(runner), logger, false, path.join("root"), path) } fn create_mock_elf(dir: &Path, name: &str, executable: bool) -> PathBuf { let path = dir.join(name); let mut f = std::fs::File::create(&path).unwrap(); // ELF header magic + minimal dummy payload f.write_all(b"\x7fELF\x02\x01\x01\x00dummy-payload-content") .unwrap(); f.flush().unwrap(); let mode = if executable { 0o755 } else { 0o644 }; std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); path } #[test] fn validates_valid_elf_executable() { let tmp = tempfile::tempdir().unwrap(); let elf = create_mock_elf(tmp.path(), "sys", true); assert!(validate_sys_payload(&elf).is_ok()); } #[test] fn rejects_non_elf_file() { let tmp = tempfile::tempdir().unwrap(); let path = tmp.path().join("fake_sys"); std::fs::write(&path, b"#!/bin/sh\necho hi\n").unwrap(); std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); let err = validate_sys_payload(&path).unwrap_err(); assert!(err.to_string().contains("bad magic")); } #[test] fn rejects_non_executable_elf() { let tmp = tempfile::tempdir().unwrap(); let elf = create_mock_elf(tmp.path(), "sys_non_exec", false); let err = validate_sys_payload(&elf).unwrap_err(); assert!(err.to_string().contains("not executable")); } struct EnvGuard { key: &'static str, original: Option, } impl EnvGuard { fn set(key: &'static str, val: &std::ffi::OsStr) -> Self { let original = std::env::var_os(key); std::env::set_var(key, val); Self { key, original } } } impl Drop for EnvGuard { fn drop(&mut self) { if let Some(orig) = &self.original { std::env::set_var(self.key, orig); } else { std::env::remove_var(self.key); } } } #[test] fn honors_phoebus_sys_path_override() { let tmp = tempfile::tempdir().unwrap(); let elf = create_mock_elf(tmp.path(), "custom_sys", true); let _guard = EnvGuard::set("PHOEBUS_SYS_PATH", elf.as_os_str()); let found = find_trusted_sys_binary().expect("must find via PHOEBUS_SYS_PATH"); assert_eq!(found, elf); } #[test] fn install_sys_copies_and_chroots() { let runner = RecordingRunner::new(); let exec = make_exec(runner); let tmp = tempfile::tempdir().unwrap(); let mock_elf = create_mock_elf(tmp.path(), "sys", true); let _guard = EnvGuard::set("PHOEBUS_SYS_PATH", mock_elf.as_os_str()); let installed = install_sys_to_target(&exec).unwrap(); assert!(installed.is_file()); assert_eq!(installed, Path::new(&exec.root).join("usr/local/bin/sys")); let meta = std::fs::metadata(&installed).unwrap(); assert_ne!(meta.permissions().mode() & 0o111, 0); } }