phoebus_os/installer-rs/crates/phoebus-core/src/target.rs
Phoebus 38214ea9e7 chore: import Phoebus OS installer and Rust migration
Initial public import of the proven Bash installer (installer/) and the production Rust workspace (installer-rs/). The reference ISO, build output and local agent transcripts are gitignored.

Verified: installer/tests/run_tests.sh and cargo test --workspace both pass.
2026-09-20 02:07:33 -07:00

136 lines
4.6 KiB
Rust

//! The installation target root.
//!
//! Host-versus-target path bugs are treated as HIGH SEVERITY. `TargetRoot`
//! makes it impossible to accidentally write to the host through the normal
//! APIs: every path is relative, must not be absolute, must not contain `..`,
//! and is joined to the root.
use std::path::{Component, Path, PathBuf};
use crate::error::{CoreError, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetRoot {
root: PathBuf,
}
impl TargetRoot {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
pub fn path(&self) -> &Path {
&self.root
}
/// Resolve a relative path beneath the target root.
///
/// Rejects absolute paths, `..` traversal and `~`-style components. An
/// empty relative path resolves to the root itself.
pub fn resolve(&self, relative: &str) -> Result<PathBuf> {
let rel = Path::new(relative.trim_start_matches('/'));
for component in rel.components() {
match component {
Component::ParentDir => {
return Err(CoreError::Validation(format!(
"target path must not contain `..`: {relative}"
)));
}
Component::RootDir | Component::Prefix(_) => {
return Err(CoreError::Validation(format!(
"target path must be relative: {relative}"
)));
}
_ => {}
}
}
Ok(self.root.join(rel))
}
/// Shorthand for an absolute target path, e.g. `target.path_for("/etc/fstab")`.
pub fn path_for(&self, absolute: &str) -> Result<PathBuf> {
self.resolve(absolute)
}
pub fn etc(&self, relative: &str) -> Result<PathBuf> {
self.resolve(&format!("etc/{relative}"))
}
pub fn var(&self, relative: &str) -> Result<PathBuf> {
self.resolve(&format!("var/{relative}"))
}
pub fn boot(&self, relative: &str) -> Result<PathBuf> {
self.resolve(&format!("boot/{relative}"))
}
pub fn home(&self, relative: &str) -> Result<PathBuf> {
self.resolve(&format!("home/{relative}"))
}
pub fn ensure_dir(&self, relative: &str) -> Result<PathBuf> {
let path = self.resolve(relative)?;
std::fs::create_dir_all(&path).map_err(|e| CoreError::io(path.clone(), e))?;
Ok(path)
}
/// Create a directory with an explicit mode (on Unix).
pub fn ensure_dir_mode(&self, relative: &str, mode: u32) -> Result<PathBuf> {
use std::os::unix::fs::PermissionsExt;
let path = self.ensure_dir(relative)?;
let perms = std::fs::Permissions::from_mode(mode);
std::fs::set_permissions(&path, perms).map_err(|e| CoreError::io(path.clone(), e))?;
Ok(path)
}
pub fn write(&self, relative: &str, contents: impl AsRef<[u8]>) -> Result<PathBuf> {
let path = self.resolve(relative)?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent.to_path_buf(), e))?;
}
std::fs::write(&path, contents).map_err(|e| CoreError::io(path.clone(), e))?;
Ok(path)
}
pub fn read_to_string(&self, relative: &str) -> Result<String> {
let path = self.resolve(relative)?;
std::fs::read_to_string(&path).map_err(|e| CoreError::io(path, e))
}
pub fn exists(&self, relative: &str) -> bool {
self.resolve(relative)
.map(|p| p.exists())
.unwrap_or(false)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolves_relative_paths() {
let t = TargetRoot::new("/mnt/phoebus");
assert_eq!(t.resolve("etc/fstab").unwrap(), PathBuf::from("/mnt/phoebus/etc/fstab"));
assert_eq!(t.etc("crypttab").unwrap(), PathBuf::from("/mnt/phoebus/etc/crypttab"));
assert_eq!(t.var("tmp").unwrap(), PathBuf::from("/mnt/phoebus/var/tmp"));
// Leading slashes are stripped so callers may pass absolute-looking paths.
assert_eq!(t.resolve("/etc/hosts").unwrap(), PathBuf::from("/mnt/phoebus/etc/hosts"));
}
#[test]
fn rejects_parent_traversal() {
let t = TargetRoot::new("/mnt/phoebus");
assert!(t.resolve("../../etc/fstab").is_err());
assert!(t.resolve("etc/../../etc/fstab").is_err());
}
#[test]
fn writes_stay_inside_root() {
let dir = tempfile::tempdir().unwrap();
let t = TargetRoot::new(dir.path());
let p = t.write("etc/fstab", "hello").unwrap();
assert!(p.starts_with(dir.path()));
assert_eq!(t.read_to_string("etc/fstab").unwrap(), "hello");
}
}