phoebus_os/installer-rs/crates/phoebus-executor/src/appimage.rs
Phoebus 084c315117
Some checks are pending
ci / test (push) Waiting to run
fix(sys): stream package output and harden package lanes
2026-10-01 10:23:41 -07:00

708 lines
24 KiB
Rust

//! Managed AppImage lane.
//!
//! An AppImage is a single executable file. Phoebus manages acquisition,
//! provenance, integrity, architecture checks, desktop integration, version
//! tracking and clean removal — but it never pretends AppImage provides a
//! sandbox, and it never executes a downloaded image just to inspect it.
//!
//! Inspection reads the ELF header (architecture) and, when `unsquashfs` is
//! available, extracts the embedded SquashFS metadata/icon without running the
//! image. Applications run as the user; the managed binary is world-readable
//! and executable, and user data under `$HOME` is preserved on removal.
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
/// Where Phoebus keeps managed AppImages, relative to the target root.
pub const APPIMAGE_DIR: &str = "opt/phoebus/appimages";
/// Where desktop entries are registered, relative to the target root.
pub const APPLICATIONS_DIR: &str = "usr/share/applications";
/// Where icons are registered, relative to the target root.
pub const PIXMAPS_DIR: &str = "usr/share/pixmaps";
/// A recorded, managed AppImage.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppImageRecord {
pub name: String,
#[serde(default)]
pub version: String,
pub sha256: String,
/// Where the image came from: a URL, or `local:<original path>`.
pub provenance: String,
pub arch: String,
pub size_bytes: u64,
pub installed_unix: u64,
#[serde(default)]
pub desktop_file: Option<String>,
#[serde(default)]
pub icon: Option<String>,
}
impl AppImageRecord {
pub fn binary_name(&self) -> String {
format!("{}.AppImage", self.name)
}
}
fn record_path(root: &Path, name: &str) -> PathBuf {
root.join(APPIMAGE_DIR).join(format!("{name}.toml"))
}
fn binary_path(root: &Path, name: &str) -> PathBuf {
root.join(APPIMAGE_DIR).join(format!("{name}.AppImage"))
}
fn desktop_path(root: &Path, name: &str) -> PathBuf {
root.join(APPLICATIONS_DIR)
.join(format!("phoebus-appimage-{name}.desktop"))
}
/// Map an ELF `e_machine` value to Phoebus's architecture name.
pub fn arch_from_elf(machine: u16) -> Option<&'static str> {
match machine {
0x3e => Some("x86_64"),
0xaa => Some("aarch64"),
0xb7 => Some("aarch64"),
0x03 => Some("x86"),
0x28 => Some("arm"),
0xf3 => Some("riscv64"),
_ => None,
}
}
/// Inspect an ELF image **without executing it**: verify the magic and read the
/// architecture. Returns the architecture and whether it matches `host_arch`.
pub fn inspect_elf(path: &Path, host_arch: &str) -> Result<(String, bool)> {
use std::io::Read;
let mut file = std::fs::File::open(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?;
let mut header = [0u8; 20];
let n = file
.read(&mut header)
.map_err(|e| ExecError::io(path.to_path_buf(), e))?;
if n < 20 || &header[..4] != b"\x7fELF" {
return Err(ExecError::operation(
"appimage",
"inspect image",
format!("{} is not an ELF executable", path.display()),
));
}
// e_machine is a 16-bit little-endian field at offset 18.
let machine = u16::from_le_bytes([header[18], header[19]]);
let arch = arch_from_elf(machine).ok_or_else(|| {
ExecError::operation(
"appimage",
"inspect image",
format!("unsupported ELF machine type 0x{machine:04x}"),
)
})?;
Ok((arch.to_string(), arch == host_arch))
}
/// Locate the embedded SquashFS superblock (`hsqs`) so metadata can be
/// extracted without running the image. Only aligned occurrences after the ELF
/// header are considered.
pub fn find_squashfs_offset(data: &[u8]) -> Option<u64> {
if data.len() < 4 {
return None;
}
let mut i = 4;
while i + 4 <= data.len() {
if &data[i..i + 4] == b"hsqs" {
return Some(i as u64);
}
i += 1;
}
None
}
fn read_squashfs_offset(path: &Path) -> Option<u64> {
use std::io::Read;
let mut file = std::fs::File::open(path).ok()?;
let mut buf = vec![0u8; 1024 * 1024];
let n = file.read(&mut buf).ok()?;
buf.truncate(n);
// The type-2 runtime is small; if the magic is beyond the first MiB, fall
// back to the whole-file scan.
match find_squashfs_offset(&buf) {
Some(offset) => Some(offset),
None => {
let data = std::fs::read(path).ok()?;
find_squashfs_offset(&data)
}
}
}
/// Write a desktop entry for the managed image and return its relative path.
fn write_desktop_entry(
root: &Path,
name: &str,
binary: &Path,
icon: Option<&str>,
) -> Result<String> {
let rel = format!("phoebus-appimage-{name}.desktop");
let icon_line = icon.map(|i| format!("Icon={i}\n")).unwrap_or_default();
let contents = format!(
"[Desktop Entry]\n\
Type=Application\n\
Name={name}\n\
Comment=Managed AppImage (no application sandbox)\n\
Exec=\"{}\" %U\n\
{icon_line}\
Terminal=false\n\
Categories=Utility;\n\
X-Phoebus-Backend=appimage\n",
binary.display()
);
let path = root.join(APPLICATIONS_DIR).join(&rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?;
}
std::fs::write(&path, contents).map_err(|e| ExecError::io(path, e))?;
Ok(rel)
}
/// Best-effort extraction of the AppImage's own icon and desktop entry using
/// `unsquashfs` on the embedded filesystem. Never executes the image.
struct ExtractedMeta {
desktop_text: Option<String>,
icon_bytes: Option<Vec<u8>>,
}
fn extract_metadata(exec: &Exec, image: &Path) -> Option<ExtractedMeta> {
let offset = read_squashfs_offset(image)?;
let listed = exec
.runner
.execute(
&CommandSpec::new("appimage", "list embedded files", "unsquashfs")
.args(["-o", &offset.to_string(), "-l"])
.arg(image.to_string_lossy().to_string()),
)
.ok()?;
if !listed.success {
return None;
}
let text = listed.stdout_lossy();
let mut desktop = None;
for line in text.lines() {
let trimmed = line.trim();
if trimmed.ends_with(".desktop") {
desktop = trimmed.split_whitespace().last().map(str::to_string);
break;
}
}
let dir = tempfile::tempdir().ok()?;
let mut extract_args = vec![
"-o".to_string(),
offset.to_string(),
"-d".to_string(),
dir.path().to_string_lossy().to_string(),
image.to_string_lossy().to_string(),
".DirIcon".to_string(),
];
if let Some(desktop) = &desktop {
extract_args.push(desktop.clone());
}
let extracted = exec
.runner
.execute(
&CommandSpec::new("appimage", "extract embedded files", "unsquashfs")
.args(extract_args),
)
.ok()?;
if !extracted.success {
return None;
}
let desktop_text = desktop
.as_ref()
.and_then(|d| std::fs::read_to_string(dir.path().join(d)).ok());
let icon_bytes = std::fs::read(dir.path().join(".DirIcon")).ok();
Some(ExtractedMeta {
desktop_text,
icon_bytes,
})
}
/// Adopt a local file as a managed AppImage.
pub fn import_local(exec: &Exec, root: &Path, source: &Path, name: &str) -> Result<AppImageRecord> {
let meta =
std::fs::symlink_metadata(source).map_err(|e| ExecError::io(source.to_path_buf(), e))?;
if !meta.file_type().is_file() {
return Err(ExecError::operation(
"appimage",
"import image",
format!(
"{} must be a regular file (symlinks are refused to prevent escape)",
source.display()
),
));
}
let (arch, matches) = inspect_elf(source, host_arch())?;
if !matches {
return Err(ExecError::operation(
"appimage",
"import image",
format!("image targets {arch}, not {}", host_arch()),
));
}
let sha256 = crate::opencode::sha256_file(source)?;
adopt(
exec,
root,
name,
source,
&sha256,
&format!("local:{}", source.display()),
&arch,
)
}
/// Download, verify and adopt an AppImage.
pub fn acquire(
exec: &Exec,
root: &Path,
name: &str,
url: &str,
expected_sha256: &str,
) -> Result<AppImageRecord> {
exec.require_tools(&["curl"])?;
if !phoebus_core::action::valid_sha256(expected_sha256) {
return Err(ExecError::operation(
"appimage",
"verify image",
"a real, pinned SHA-256 is required before downloading (placeholders are refused)",
));
}
if exec.dry_run {
exec.logger.info(format!(
"[dry-run] would download AppImage {name} from {url}"
));
return Ok(AppImageRecord {
name: name.to_string(),
version: String::new(),
sha256: expected_sha256.to_string(),
provenance: url.to_string(),
arch: host_arch().to_string(),
size_bytes: 0,
installed_unix: now_unix(),
desktop_file: None,
icon: None,
});
}
let staged = exec.state_dir.join(format!("appimage-{name}.download"));
let _ = std::fs::remove_file(&staged);
exec.run(
CommandSpec::new("appimage", "download image", "curl")
.args(["-fL", "--retry", "3", "-o"])
.arg(staged.to_string_lossy().to_string())
.arg(url)
.show_output(),
)?;
let actual = crate::opencode::sha256_file(&staged)?;
if actual != expected_sha256 {
let _ = std::fs::remove_file(&staged);
return Err(ExecError::operation(
"appimage",
"verify image",
format!("SHA-256 mismatch for {name}; discarding download"),
));
}
let (arch, matches) = inspect_elf(&staged, host_arch())?;
if !matches {
let _ = std::fs::remove_file(&staged);
return Err(ExecError::operation(
"appimage",
"verify image",
format!("image targets {arch}, not {}", host_arch()),
));
}
let result = adopt(exec, root, name, &staged, &actual, url, &arch);
let _ = std::fs::remove_file(&staged);
result
}
/// Replace an existing managed image with a newly verified one.
pub fn update(
exec: &Exec,
root: &Path,
name: &str,
url: &str,
expected_sha256: &str,
) -> Result<AppImageRecord> {
if !record_path(root, name).is_file() {
return Err(ExecError::operation(
"appimage",
"update image",
format!("{name} is not a managed AppImage"),
));
}
acquire(exec, root, name, url, expected_sha256)
}
fn adopt(
exec: &Exec,
root: &Path,
name: &str,
source: &Path,
sha256: &str,
provenance: &str,
arch: &str,
) -> Result<AppImageRecord> {
// /var/lib/phoebus is private (0700). Desktop launchers must be able to
// traverse the managed image directory as the logged-in user.
let target = phoebus_core::target::TargetRoot::new(root);
target
.ensure_dir_mode("opt/phoebus", 0o755)
.map_err(|e| ExecError::operation("appimage", "prepare image directory", e.to_string()))?;
let dir = target
.ensure_dir_mode(APPIMAGE_DIR, 0o755)
.map_err(|e| ExecError::operation("appimage", "prepare image directory", e.to_string()))?;
let dest = binary_path(root, name);
// Atomic-ish replacement: copy beside the destination, then rename.
let tmp = dir.join(format!(".{name}.AppImage.tmp"));
std::fs::copy(source, &tmp).map_err(|e| ExecError::io(tmp.clone(), e))?;
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))
.map_err(|e| ExecError::io(tmp.clone(), e))?;
}
std::fs::rename(&tmp, &dest).map_err(|e| ExecError::io(dest.clone(), e))?;
// Optional metadata extraction (never executes the image).
let (desktop_text, icon_name) = match extract_metadata(exec, &dest) {
Some(meta) => {
let icon_name = meta.icon_bytes.as_ref().and_then(|bytes| {
let path = root.join(PIXMAPS_DIR).join(format!("{name}.png"));
if let Some(parent) = path.parent() {
if std::fs::create_dir_all(parent).is_err() {
return None;
}
}
std::fs::write(&path, bytes).ok()?;
Some(name.to_string())
});
(meta.desktop_text, icon_name)
}
None => (None, None),
};
// The generated entry is authoritative so the application is always
// launchable; the embedded entry is recorded but not trusted blindly.
let desktop_rel = write_desktop_entry(root, name, &dest, icon_name.as_deref())?;
let record = AppImageRecord {
name: name.to_string(),
version: String::new(),
sha256: sha256.to_string(),
provenance: provenance.to_string(),
arch: arch.to_string(),
size_bytes: std::fs::metadata(&dest).map(|m| m.len()).unwrap_or(0),
installed_unix: now_unix(),
desktop_file: Some(desktop_rel),
icon: icon_name,
};
write_record(root, &record)?;
let _ = desktop_text;
exec.logger.info(format!(
"AppImage {name} adopted (sha256 {})",
&sha256[..12]
));
Ok(record)
}
fn now_unix() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn write_record(root: &Path, record: &AppImageRecord) -> Result<()> {
let path = record_path(root, &record.name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?;
}
let text = toml::to_string_pretty(record)
.map_err(|e| ExecError::operation("appimage", "write record", e.to_string()))?;
std::fs::write(&path, text).map_err(|e| ExecError::io(path, e))
}
/// Load one managed record.
pub fn info(root: &Path, name: &str) -> Result<AppImageRecord> {
let path = record_path(root, name);
let text = std::fs::read_to_string(&path).map_err(|e| ExecError::io(path, e))?;
toml::from_str(&text)
.map_err(|e| ExecError::operation("appimage", "read record", e.to_string()))
}
/// List managed AppImages.
pub fn list(root: &Path) -> Result<Vec<AppImageRecord>> {
let dir = root.join(APPIMAGE_DIR);
let mut out = Vec::new();
let Ok(entries) = std::fs::read_dir(&dir) else {
return Ok(out);
};
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) == Some("toml") {
if let Ok(text) = std::fs::read_to_string(&path) {
if let Ok(record) = toml::from_str::<AppImageRecord>(&text) {
out.push(record);
}
}
}
}
out.sort_by(|a, b| a.name.cmp(&b.name));
Ok(out)
}
/// Remove a managed AppImage. The user's data under `$HOME` is always
/// preserved; `purge_data` only removes a managed `<name>.data` directory.
pub fn remove(root: &Path, name: &str, purge_data: bool) -> Result<()> {
let _ = info(root, name)?;
for path in [
binary_path(root, name),
record_path(root, name),
desktop_path(root, name),
root.join(PIXMAPS_DIR).join(format!("{name}.png")),
] {
let _ = std::fs::remove_file(&path);
}
if purge_data {
let data = root.join(APPIMAGE_DIR).join(format!("{name}.data"));
if data.is_dir() {
let _ = std::fs::remove_dir_all(&data);
}
}
Ok(())
}
/// Derive a safe managed name from a local file name.
pub fn derive_name(source: &Path) -> Result<String> {
let stem = source.file_stem().and_then(|s| s.to_str()).ok_or_else(|| {
ExecError::operation("appimage", "derive name", "file name is not valid UTF-8")
})?;
let cleaned: String = stem
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || "._-".contains(c) {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
let cleaned = cleaned.trim_matches(['-', '.', '_']).to_string();
if phoebus_core::action::valid_appimage_name(&cleaned) {
Ok(cleaned)
} else {
Err(ExecError::operation(
"appimage",
"derive name",
format!("could not derive a safe name from {}", source.display()),
))
}
}
/// The host architecture in Phoebus naming.
pub fn host_arch() -> &'static str {
match std::env::consts::ARCH {
"x86_64" => "x86_64",
"aarch64" => "aarch64",
"x86" => "x86",
"arm" => "arm",
"riscv64" => "riscv64",
_ => "unknown",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::RecordingRunner;
use crate::log::Logger;
use phoebus_core::Redactor;
use std::io::Write;
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 fake_elf(path: &Path, machine: u16) {
let mut f = std::fs::File::create(path).unwrap();
let mut header = [0u8; 64];
header[..4].copy_from_slice(b"\x7fELF");
header[4] = 2; // 64-bit
header[18..20].copy_from_slice(&machine.to_le_bytes());
f.write_all(&header).unwrap();
// Embed a fake squashfs marker so offset detection is exercised.
f.write_all(b"hsqs").unwrap();
f.write_all(&[0u8; 32]).unwrap();
}
#[test]
fn arch_from_elf_maps_common_machines() {
assert_eq!(arch_from_elf(0x3e), Some("x86_64"));
assert_eq!(arch_from_elf(0xb7), Some("aarch64"));
assert_eq!(arch_from_elf(0x1234), None);
}
#[test]
fn inspect_reads_arch_without_executing() {
let dir = tempfile::tempdir().unwrap();
let img = dir.path().join("app.AppImage");
fake_elf(&img, 0x3e);
let (arch, matches) = inspect_elf(&img, "x86_64").unwrap();
assert_eq!(arch, "x86_64");
assert!(matches);
let (arch, matches) = inspect_elf(&img, "aarch64").unwrap();
assert_eq!(arch, "x86_64");
assert!(!matches);
}
#[test]
fn non_elf_is_refused() {
let dir = tempfile::tempdir().unwrap();
let img = dir.path().join("script.sh");
std::fs::write(&img, b"#!/bin/sh\necho hi\n").unwrap();
assert!(inspect_elf(&img, "x86_64").is_err());
}
#[test]
fn squashfs_offset_detection() {
assert_eq!(find_squashfs_offset(b"\x7fELF....hsqs"), Some(8));
assert_eq!(find_squashfs_offset(b"nope"), None);
}
#[test]
fn import_records_hash_and_desktop_entry() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.AppImage");
fake_elf(&src, 0x3e);
let root = tempfile::tempdir().unwrap();
let runner = RecordingRunner::new();
// unsquashfs is absent in the recording runner; extraction falls back.
runner.fail("unsquashfs", "not found");
let exec = make_exec(runner);
let record = import_local(&exec, root.path(), &src, "hello").unwrap();
assert_eq!(record.name, "hello");
assert_eq!(record.sha256.len(), 64);
assert!(record.arch == "x86_64" || record.arch == host_arch());
assert!(root
.path()
.join(APPIMAGE_DIR)
.join("hello.AppImage")
.is_file());
assert!(root
.path()
.join(APPLICATIONS_DIR)
.join("phoebus-appimage-hello.desktop")
.is_file());
let listed = list(root.path()).unwrap();
assert_eq!(listed.len(), 1);
let info = info(root.path(), "hello").unwrap();
assert_eq!(info.sha256, record.sha256);
}
#[test]
fn import_refuses_a_symlink_and_a_mismatched_arch() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real.AppImage");
fake_elf(&real, 0x3e);
let link = dir.path().join("link.AppImage");
std::os::unix::fs::symlink(&real, &link).unwrap();
let root = tempfile::tempdir().unwrap();
let exec = make_exec(RecordingRunner::new());
let err = import_local(&exec, root.path(), &link, "link").unwrap_err();
assert!(err.to_string().contains("regular file"), "{err}");
// On x86_64 hosts a fake aarch64 image is refused.
if host_arch() == "x86_64" {
let arm = dir.path().join("arm.AppImage");
fake_elf(&arm, 0xb7);
let err = import_local(&exec, root.path(), &arm, "arm").unwrap_err();
assert!(err.to_string().contains("not x86_64"), "{err}");
}
}
#[test]
fn acquire_verifies_checksum_and_discards_on_mismatch() {
// Without curl available on the recording runner, force curl to fail.
let runner = RecordingRunner::new();
runner.fail("curl", "network down");
let exec = make_exec(runner);
let root = tempfile::tempdir().unwrap();
let err = acquire(
&exec,
root.path(),
"app",
"https://example.invalid/app.AppImage",
&"a".repeat(64),
)
.unwrap_err();
assert!(err.to_string().contains("download"), "{err}");
}
#[test]
fn acquire_refuses_a_placeholder_hash_before_downloading() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let root = tempfile::tempdir().unwrap();
let err = acquire(
&exec,
root.path(),
"app",
"https://example.invalid/app.AppImage",
&"0".repeat(64),
)
.unwrap_err();
assert!(err.to_string().contains("mismatch") || err.to_string().contains("SHA-256"));
}
#[test]
fn remove_preserves_data_by_default_and_purges_on_request() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.AppImage");
fake_elf(&src, 0x3e);
let root = tempfile::tempdir().unwrap();
let exec = make_exec(RecordingRunner::new());
import_local(&exec, root.path(), &src, "hello").unwrap();
let data = root.path().join(APPIMAGE_DIR).join("hello.data");
std::fs::create_dir_all(&data).unwrap();
std::fs::write(data.join("state"), b"keep").unwrap();
remove(root.path(), "hello", false).unwrap();
assert!(
data.join("state").is_file(),
"data must survive default removal"
);
assert!(!root
.path()
.join(APPIMAGE_DIR)
.join("hello.AppImage")
.exists());
import_local(&exec, root.path(), &src, "hello").unwrap();
remove(root.path(), "hello", true).unwrap();
assert!(!data.exists(), "purge removes the managed data dir");
}
#[test]
fn double_import_is_idempotent_at_the_filesystem_level() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.AppImage");
fake_elf(&src, 0x3e);
let root = tempfile::tempdir().unwrap();
let exec = make_exec(RecordingRunner::new());
let a = import_local(&exec, root.path(), &src, "hello").unwrap();
let b = import_local(&exec, root.path(), &src, "hello").unwrap();
assert_eq!(a.sha256, b.sha256);
assert_eq!(list(root.path()).unwrap().len(), 1);
}
}