//! 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) -> 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 { 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 { self.resolve(absolute) } pub fn etc(&self, relative: &str) -> Result { self.resolve(&format!("etc/{relative}")) } pub fn var(&self, relative: &str) -> Result { self.resolve(&format!("var/{relative}")) } pub fn boot(&self, relative: &str) -> Result { self.resolve(&format!("boot/{relative}")) } pub fn home(&self, relative: &str) -> Result { self.resolve(&format!("home/{relative}")) } pub fn ensure_dir(&self, relative: &str) -> Result { 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 { 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 { 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 { 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"); } }