fix(host): APPIMAGE is believed only when this program runs from that image

The AppImage launcher sets APPIMAGE (the image's file) and APPDIR (where
it is mounted) for the program it starts, and every program that one
starts inherits both: a terminal, an editor, an agent's app. The host's
start, the agent's pointer file, the host's check for a replaced program
and `update` each read APPIMAGE and believed it whenever it named a file.

So a wanderbooks run from inside another app's AppImage took that app's
image for its own:

- it started that image as the host, and the books never opened ("the
  books server keeps failing to start");
- `connect` would have written that image into the agent's pointer file;
- `wanderbooks update` replaced that app's file with wanderbooks.

Found by the batch's gate: the_host_outlives_the_app_scope_that_started_it
passes its own environment on (the other tests clear it), and this gate
ran in a session started from an AppImage app. The first and the third
are reproduced by two new tests, which fail without this change (the
update test read an ELF header where the other app's file had been).

The rule now (start.rs INVARIANT 6, from the AppImage documentation's
"Environment variables"): the image is this program's own only when
APPIMAGE is an absolute file, APPDIR an absolute folder, and the running
executable's file is inside APPDIR, compared as resolved paths. One
function decides (`own_appimage`), and all four readers ask it. The host
is handed APPDIR beside APPIMAGE, and neither unless both are its own.

No books and no figure are touched. The tests that pretend to be an
AppImage now set APPDIR as a launcher does; translocation.rs used a bare
APPIMAGE to stand in for a macOS path, the very thing this closes, and
names the program's folder as the mount.

The failing test's message now lists the lines that did arrive, which is
what showed the host was refused rather than slow.

Not checked against a built AppImage (none has been built with this
change): the first trial of one shows `update` and a restart find the
image.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-10 02:28:05 -07:00
1 parent 0178809a3d
commit 3bc198594b
12 files changed
+331 -52

No files matched your search

+43 -2
View File
@@ -254,12 +254,16 @@ impl Running {
/// Wait for a line containing `text`.
fn expect(&self, text: &str, secs: u64) -> String {
let deadline = Instant::now() + Duration::from_secs(secs);
let mut seen = Vec::new();
loop {
let left = deadline.saturating_duration_since(Instant::now());
match self.lines.recv_timeout(left) {
Ok(line) if line.contains(text) => return line,
Ok(_) => {}
Err(_) => panic!("no line with {text:?} in {secs} s"),
Ok(line) => seen.push(line),
// What did arrive says why: a refusal, or nothing at all.
Err(e) => {
panic!("no line with {text:?} in {secs} s ({e}); the lines seen: {seen:?}")
}
}
}
}
@@ -1203,6 +1207,43 @@ fn books_commands_hold_the_books_while_they_run() {
}
}
/// start.rs INVARIANT 6: started from inside another app's AppImage (a
/// terminal, an editor, an agent's app: each hands `APPIMAGE` and `APPDIR`
/// to everything it starts), this program is still the one that runs as
/// the host. That image is never run.
#[test]
fn another_apps_appimage_is_never_run_as_the_host() {
use std::os::unix::fs::PermissionsExt;
let home = Home::new("foreign");
// The other app: a program that leaves a mark if it is ever run.
let mark = home.dir.path().join("other-app-ran");
let other = home.dir.path().join("Other.AppImage");
std::fs::write(&other, format!("#!/bin/sh\n: > '{}'\n", mark.display())).unwrap();
std::fs::set_permissions(&other, std::fs::Permissions::from_mode(0o755)).unwrap();
let mount = home.dir.path().join("other-mount");
std::fs::create_dir(&mount).unwrap();
let mut c = home.cmd("books");
c.args(["create", "acme"])
.env("APPIMAGE", &other)
.env("APPDIR", &mount)
.stdin(Stdio::null());
let out = c.output().unwrap();
assert!(out.status.success(), "{out:?}");
let mut c = home.cmd("serve");
c.env("APPIMAGE", &other).env("APPDIR", &mount);
let held = Running::start(c);
held.expect("The books are open", 30);
let host = home.host().unwrap();
assert_eq!(
std::fs::read_link(format!("/proc/{host}/exe")).unwrap(),
std::fs::canonicalize(&home.exe).unwrap(),
"the host is another program"
);
assert!(!mark.exists(), "the other app's image was run");
held.signal(libc::SIGINT);
assert!(home.wait_closed(10));
}
/// Under a systemd app scope (as uwsm sets up), closing the app that
/// started the host leaves the host for the other holders. Run only where
/// a systemd user manager is there to make scopes.
+10 -2
View File
@@ -6,8 +6,10 @@
//!
//! The check is on the path the program would give the agent
//! (`ledger_host::start::this_executable`), so a test can stand in for
//! macOS on any Unix: `APPIMAGE` names a file there, and a path with an
//! `AppTranslocation` part is refused just as the real one is.
//! macOS on any Unix: `APPIMAGE` names a file there (with `APPDIR` naming
//! the folder the program runs from, as an image's launcher sets the two:
//! `APPIMAGE` alone is not believed, start.rs INVARIANT 6), and a path
//! with an `AppTranslocation` part is refused just as the real one is.
#![cfg(unix)]
@@ -95,9 +97,14 @@ fn translocated_app_refuses_to_connect() {
);
std::fs::create_dir_all(translocated.parent().unwrap()).unwrap();
std::fs::write(&translocated, b"").unwrap();
// The folder the program under test runs from stands in for the mount.
let mount = Path::new(env!("CARGO_BIN_EXE_wanderbooks"))
.parent()
.unwrap();
let out = home
.cmd("connect", &bin)
.env("APPIMAGE", &translocated)
.env("APPDIR", mount)
.args(["claude", "--book", "beta"])
.output()
.unwrap();
@@ -122,6 +129,7 @@ fn translocated_app_refuses_to_connect() {
let out = home
.cmd("connect", &bin)
.env("APPIMAGE", &ordinary)
.env("APPDIR", mount)
.args(["claude", "--book", "beta"])
.output()
.unwrap();
+50 -2
View File
@@ -150,7 +150,10 @@ impl Home {
/// The environment of the pretend AppImage, if this is one.
fn image_env(&self, c: &mut Command) {
if let Some(image) = &self.image {
c.env("APPIMAGE", image);
// As an AppImage's launcher sets them: the image, and the
// mount the program runs from.
c.env("APPIMAGE", image)
.env("APPDIR", self.exe.parent().unwrap());
}
}
@@ -728,6 +731,7 @@ fn update_under_writes_in(home: Home) -> (Home, Agent, Vec<String>) {
);
let key = release.dir.path().join("release.pub");
let image = home.image.clone();
let mount = home.exe.parent().unwrap().to_path_buf();
std::thread::spawn(move || {
let _keep = &release;
let mut c = Command::new(exe);
@@ -739,7 +743,7 @@ fn update_under_writes_in(home: Home) -> (Home, Agent, Vec<String>) {
.env("PATH", "/usr/bin:/bin")
.env("HOME", dir);
if let Some(image) = image {
c.env("APPIMAGE", image);
c.env("APPIMAGE", image).env("APPDIR", mount);
}
c.output().unwrap()
})
@@ -832,6 +836,50 @@ fn a_replaced_appimage_restarts_the_books() {
assert!(agent.add_account("4001").is_ok(), "the session carries on");
}
/// start.rs INVARIANT 6: `APPIMAGE` and `APPDIR` are inherited by
/// everything an AppImage app starts (a terminal, an editor, an agent's
/// app). When this program is not inside that image, the image is someone
/// else's file: an update replaces this program and never that file.
#[test]
fn an_update_never_replaces_another_apps_appimage() {
let home = Home::new("foreign");
let old = home.program();
let other = home.dir.path().join("Other.AppImage");
std::fs::write(&other, b"another app's image").unwrap();
let mount = home.dir.path().join("other-mount");
std::fs::create_dir(&mount).unwrap();
let release = Release::new();
let next = newer(&home, "9.0.0");
release.publish("9.0.0", &next, |_| {});
let mut c = Command::new(&home.exe);
c.args(["update", "--root"])
.arg(home.root())
.arg("--feed")
.arg(format!(
"file://{}",
release.dir.path().join("manifest.json").display()
))
.arg("--trusted-key")
.arg(release.dir.path().join("release.pub"))
.env_clear()
.env("PATH", "/usr/bin:/bin")
.env("HOME", home.dir.path())
.env("APPIMAGE", &other)
.env("APPDIR", &mount)
.stdin(Stdio::null());
let out = c.output().unwrap();
assert!(out.status.success(), "{}", text(&out));
assert!(
std::fs::read(&other).unwrap() == b"another app's image",
"the other app's image was written over"
);
assert_eq!(sha256(&home.program()), sha256(&next), "this program");
assert_eq!(
sha256(&std::fs::read(home.updates().join("previous/wanderbooks")).unwrap()),
sha256(&old)
);
}
#[test]
fn update_waits_for_a_running_call() {
// No call is cut off or made twice: each account written across the
+2 -6
View File
@@ -1515,12 +1515,8 @@ pub fn books_home_in(documents: &Path, book: &str) -> PathBuf {
/// this runs from one (its mount goes away with the process), else this
/// executable as it is on disk.
fn pointer_program() -> Result<PathBuf, String> {
if let Some(image) = std::env::var_os("APPIMAGE")
.map(PathBuf::from)
.filter(|p| p.is_absolute() && p.is_file())
{
return Ok(image);
}
// Its own image only (start.rs INVARIANT 6): never the image of the
// app this was started from.
crate::start::this_executable()
}
+2 -2
View File
@@ -227,8 +227,8 @@ fn identity_from(meta: &std::fs::Metadata) -> Identity {
/// image file (`APPIMAGE`), not the program inside the mount.
#[cfg(unix)]
fn running_identity() -> Option<Identity> {
if let Some(image) = crate::start::own_appimage(std::env::var_os("APPIMAGE").as_deref()) {
return Some(identity_from(&std::fs::metadata(image).ok()?));
if let Some(own) = crate::start::this_appimage() {
return Some(identity_from(&std::fs::metadata(own.image).ok()?));
}
let running = if cfg!(target_os = "linux") {
std::fs::metadata("/proc/self/exe").ok()?
+158 -28
View File
@@ -4,7 +4,8 @@
//! GOAL: the host never inherits anything from whoever opened the books:
//! not their environment, descriptors, session, umask, or the app's
//! scope (which would take the host down with the app).
//! SOURCE: plan/served.md 3.9; test host_starts_clean, host_survives_app_scope.
//! SOURCE: plan/served.md 3.9; test host_starts_clean, host_survives_app_scope;
//! for INVARIANT 6, docs.appimage.org, "Environment variables".
//! INVARIANTS:
//! 1. The host's environment is a fixed list: PATH (fixed), HOME (from
//! the account's record, never the opener's), and XDG_RUNTIME_DIR
@@ -13,8 +14,9 @@
//! it names a socket this account owns (the owner's ssh agent, so the
//! server's backups reach a private git repository, D-30). Nothing
//! else passes (a scope's own identifiers, such as INVOCATION_ID, are
//! systemd's). One more: APPIMAGE, only when it names an absolute
//! file, so the host knows its own AppImage (below).
//! systemd's). Two more: APPIMAGE and APPDIR, only when they are
//! this program's own (INVARIANT 6), so the host knows its own
//! AppImage (below).
//! 2. Its standard input and output are null, its errors go to
//! run/host.log (0600); it starts a new session with umask 077. Every
//! other descriptor is closed (std opens them close-on-exec, and the
@@ -30,6 +32,17 @@
//! reads that path about itself and never tells it to an agent (I-2),
//! so a replaced image restarts the books like any replaced program.
//! 5. The opener doesn't wait for it, and reaps it when it ends.
//! 6. APPIMAGE is believed only when this program runs from inside the
//! image it names: APPIMAGE is an absolute file, APPDIR an absolute
//! folder, and this executable's file is under APPDIR. Both are
//! inherited by everything an AppImage app starts (a terminal, an
//! editor, an agent's app), so on their own they say only that some
//! ancestor was an AppImage. A variable that is someone else's is
//! never run as the host, written into an agent's pointer file, or
//! replaced by `update`. (The AppImage documentation: APPIMAGE is
//! the "(Absolute) path to AppImage file (with symlinks resolved)",
//! APPDIR the "Path of mountpoint of the SquashFS image contained in
//! the AppImage".)
//! ```
use crate::knobs::Knobs;
@@ -70,8 +83,8 @@ const LOG_LIMIT: u64 = 8 * 1024 * 1024;
/// replaced file reads as "… (deleted)"; the path, not the old file, is
/// what a new host runs.
pub fn this_executable() -> Result<PathBuf, String> {
if let Some(image) = own_appimage(std::env::var_os("APPIMAGE").as_deref()) {
return Ok(PathBuf::from(image));
if let Some(own) = this_appimage() {
return Ok(own.image);
}
let exe = std::env::current_exe().map_err(|e| format!("can't find this program: {e}"))?;
let text = exe.to_string_lossy();
@@ -98,11 +111,50 @@ pub fn translocation_refusal(exe: &Path) -> Option<&'static str> {
)
}
/// The AppImage this process runs from: `APPIMAGE` when it is an
/// absolute path to a file.
pub fn own_appimage(value: Option<&std::ffi::OsStr>) -> Option<std::ffi::OsString> {
let path = Path::new(value?);
(path.is_absolute() && path.is_file()).then(|| path.as_os_str().to_os_string())
/// This program's own AppImage (INVARIANT 6): the image's file, and the
/// folder it is mounted (or unpacked) at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnImage {
/// `APPIMAGE`: the file a host is started from and an update replaces.
pub image: PathBuf,
/// `APPDIR`: where the program inside the image runs from.
pub mount: PathBuf,
}
/// The AppImage the program at `exe` runs from, given `APPIMAGE` and
/// `APPDIR` (INVARIANT 6): none unless the image is an absolute file,
/// the mount an absolute folder, and `exe` is inside the mount. The two
/// variables alone prove nothing: every program an AppImage app starts
/// inherits them.
pub fn own_appimage(
image: Option<&std::ffi::OsStr>,
mount: Option<&std::ffi::OsStr>,
exe: &Path,
) -> Option<OwnImage> {
let image = Path::new(image?);
let mount = Path::new(mount?);
if !image.is_absolute() || !image.is_file() || !mount.is_absolute() {
return None;
}
// Compared as the files they are, so a link in either path neither
// hides the program nor lets another folder stand in for the mount.
let inside = std::fs::canonicalize(exe)
.ok()?
.starts_with(std::fs::canonicalize(mount).ok()?);
inside.then(|| OwnImage {
image: image.to_path_buf(),
mount: mount.to_path_buf(),
})
}
/// The AppImage this process runs from, if it runs from one
/// ([`own_appimage`], of this process's environment and executable).
pub fn this_appimage() -> Option<OwnImage> {
own_appimage(
std::env::var_os("APPIMAGE").as_deref(),
std::env::var_os("APPDIR").as_deref(),
&std::env::current_exe().ok()?,
)
}
/// This account's user ID.
@@ -180,11 +232,11 @@ fn own_agent(named: Option<&std::ffi::OsStr>) -> Option<std::ffi::OsString> {
#[cfg(unix)]
/// The host's environment (INVARIANT 1), given the opener's
/// `SSH_AUTH_SOCK`.
/// `SSH_AUTH_SOCK` and its own AppImage, if it runs from one.
fn host_env(
home: &Path,
ssh_agent: Option<&std::ffi::OsStr>,
appimage: Option<&std::ffi::OsStr>,
appimage: Option<&OwnImage>,
) -> Vec<(String, std::ffi::OsString)> {
let mut env = vec![
("PATH".to_string(), PATH.into()),
@@ -199,8 +251,9 @@ fn host_env(
if let Some(agent) = own_agent(ssh_agent) {
env.push(("SSH_AUTH_SOCK".into(), agent));
}
if let Some(image) = own_appimage(appimage) {
env.push(("APPIMAGE".into(), image));
if let Some(own) = appimage {
env.push(("APPIMAGE".into(), own.image.clone().into_os_string()));
env.push(("APPDIR".into(), own.mount.clone().into_os_string()));
}
env
}
@@ -294,7 +347,7 @@ pub fn start_host(
.envs(host_env(
&home,
std::env::var_os("SSH_AUTH_SOCK").as_deref(),
std::env::var_os("APPIMAGE").as_deref(),
this_appimage().as_ref(),
))
.current_dir("/")
.stdin(Stdio::null())
@@ -569,7 +622,8 @@ mod tests {
"XDG_RUNTIME_DIR",
"DBUS_SESSION_BUS_ADDRESS",
"SSH_AUTH_SOCK",
"APPIMAGE"
"APPIMAGE",
"APPDIR"
]
.contains(n),
"{n}"
@@ -579,20 +633,96 @@ mod tests {
assert_eq!(env[1].1, "/home/someone");
}
#[test]
fn only_an_absolute_file_passes_as_the_appimage() {
let dir = tempfile::tempdir().unwrap();
let image = dir.path().join("W.AppImage");
/// A pretend image: `W.AppImage`, and the program in its mount.
fn pretend_image(dir: &Path) -> (PathBuf, PathBuf, PathBuf) {
let image = dir.join("W.AppImage");
std::fs::write(&image, b"x").unwrap();
let home = Path::new("/home/someone");
let has = |v: Option<&std::ffi::OsStr>| {
host_env(home, None, v).iter().any(|(n, _)| n == "APPIMAGE")
let mount = dir.join("mount");
std::fs::create_dir_all(mount.join("usr/bin")).unwrap();
let exe = mount.join("usr/bin/wanderbooks");
std::fs::write(&exe, b"x").unwrap();
(image, mount, exe)
}
#[test]
fn an_appimage_is_ours_only_when_the_program_runs_from_its_mount() {
let dir = tempfile::tempdir().unwrap();
let (image, mount, exe) = pretend_image(dir.path());
let own = |i: Option<&Path>, m: Option<&Path>, exe: &Path| {
own_appimage(i.map(Path::as_os_str), m.map(Path::as_os_str), exe)
};
assert!(has(Some(image.as_os_str())));
assert!(!has(None));
assert!(!has(Some("W.AppImage".as_ref())), "relative");
assert!(!has(Some(dir.path().as_os_str())), "a folder");
assert!(!has(Some(dir.path().join("gone").as_os_str())));
assert_eq!(
own(Some(&image), Some(&mount), &exe),
Some(OwnImage {
image: image.clone(),
mount: mount.clone()
})
);
// Another app's image, inherited: this program is not in its mount
// (a terminal, an editor or an agent's app that is an AppImage
// hands both variables to everything it starts).
let elsewhere = dir.path().join("bin");
std::fs::create_dir(&elsewhere).unwrap();
let other = elsewhere.join("wanderbooks");
std::fs::write(&other, b"x").unwrap();
assert_eq!(own(Some(&image), Some(&mount), &other), None);
// A folder beside the mount whose name starts like it is not it.
let beside = dir.path().join("mount-2");
std::fs::create_dir(&beside).unwrap();
let near = beside.join("wanderbooks");
std::fs::write(&near, b"x").unwrap();
assert_eq!(own(Some(&image), Some(&mount), &near), None);
// Neither variable alone, nor a path that is not what it says.
assert_eq!(own(Some(&image), None, &exe), None, "no APPDIR");
assert_eq!(own(None, Some(&mount), &exe), None, "no APPIMAGE");
assert_eq!(
own(Some(Path::new("W.AppImage")), Some(&mount), &exe),
None,
"relative"
);
assert_eq!(own(Some(dir.path()), Some(&mount), &exe), None, "a folder");
assert_eq!(
own(Some(&dir.path().join("gone")), Some(&mount), &exe),
None,
"no such file"
);
assert_eq!(
own(Some(&image), Some(Path::new("mount")), &exe),
None,
"a relative mount"
);
assert_eq!(
own(Some(&image), Some(&dir.path().join("no-mount")), &exe),
None,
"no such mount"
);
// A link to the mount is the mount; a link out of it is not in it.
let link = dir.path().join("link");
std::os::unix::fs::symlink(&mount, &link).unwrap();
assert!(own(Some(&image), Some(&link), &exe).is_some());
let out = mount.join("usr/bin/out");
std::os::unix::fs::symlink(&other, &out).unwrap();
assert_eq!(own(Some(&image), Some(&mount), &out), None);
}
#[test]
fn the_host_is_told_its_appimage_only_when_there_is_one() {
let home = Path::new("/home/someone");
let names = |own: Option<&OwnImage>| -> Vec<String> {
host_env(home, None, own)
.into_iter()
.map(|(n, _)| n)
.collect()
};
let own = OwnImage {
image: "/opt/W.AppImage".into(),
mount: "/tmp/.mount_W".into(),
};
let env = host_env(home, None, Some(&own));
let value = |name: &str| env.iter().find(|(n, _)| n == name).map(|(_, v)| v.clone());
assert_eq!(value("APPIMAGE"), Some("/opt/W.AppImage".into()));
assert_eq!(value("APPDIR"), Some("/tmp/.mount_W".into()));
assert!(!names(None).iter().any(|n| n == "APPIMAGE" || n == "APPDIR"));
}
#[test]
+5 -2
View File
@@ -143,7 +143,10 @@ pub enum Install {
/// What kind of install the executable at `exe` is. A package puts
/// `<prefix>/share/wanderbooks/install-method` beside `<prefix>/bin`, with
/// its manager's name in it; an AppImage says where it is in `APPIMAGE`.
/// its manager's name in it; an AppImage says where it is in `APPIMAGE`,
/// which is `appimage` only when the image is this program's own
/// (start.rs INVARIANT 6: an update replaces that file, so it is never
/// one another app's `APPIMAGE` names).
pub fn install_kind(exe: &Path, appimage: Option<&Path>) -> Install {
if let Some(image) = appimage.filter(|p| p.is_file()) {
return Install::SelfUpdating(image.to_path_buf());
@@ -160,7 +163,7 @@ pub fn install_kind(exe: &Path, appimage: Option<&Path>) -> Install {
/// How the running program was installed.
pub fn this_install() -> Result<Install, String> {
let exe = crate::start::this_executable()?;
let image = std::env::var_os("APPIMAGE").map(PathBuf::from);
let image = crate::start::this_appimage().map(|own| own.image);
Ok(install_kind(&exe, image.as_deref()))
}