Skip to main content

graphrt_core/
child_env.rs

1//! The host environment given to child processes: the minimal one for
2//! processes that do not inherit the whole environment (plugin processes,
3//! stdio MCP servers), and the computer's own environment, without what an
4//! AppImage launcher added, for every process graphrt starts.
5//!
6//! Lives in the core because both host crates that start such processes
7//! (`graphrt-plugin`, `graphrt-mcp`) already depend on it and on nothing else
8//! in common.
9//!
10//! # AppImage
11//!
12//! An application packaged as a Linux AppImage (e.g. the graphrt desktop app,
13//! which embeds these crates) runs with the bundle's folders in front of
14//! `LD_LIBRARY_PATH`, `PATH`, `PYTHONPATH`, `XDG_DATA_DIRS`, … and with
15//! `PYTHONHOME`, `GTK_PATH`, `GIO_MODULE_DIR`, … pointing into the bundle (the
16//! AppImage's `AppRun` and its GTK hook set them, without keeping the old
17//! values). The application needs them; a program of the computer started with
18//! them loads the bundle's older libraries and fails, e.g. ``/usr/bin/env:
19//! …/libsystemd.so.0: version `LIBSYSTEMD_254' not found`` for a
20//! `#!/usr/bin/env node` launcher on Ubuntu 26.04. So when the running binary
21//! is inside `$APPDIR`, every entry inside `$APPDIR` is dropped for children: a
22//! list variable keeps its other entries, a variable with nothing left is
23//! removed, and the runtime's `APPIMAGE` / `ARGV0` / `OWD` are removed. Outside
24//! an AppImage (and on macOS / Windows) nothing changes.
25
26use std::ffi::{OsStr, OsString};
27use std::path::{Path, PathBuf};
28use std::sync::OnceLock;
29
30/// Host variables always passed to a child process that does not inherit the
31/// environment.
32///
33/// - `PATH`, `HOME`, `LANG`, `TMPDIR`: what most launchers (`npx`, `uvx`,
34///   `docker`, `sh`) need to start, find their tools and pick a temp dir.
35/// - `SYSTEMROOT`, `USERPROFILE`, `APPDATA`, `TEMP`, `TMP`: what most Windows
36///   programs need to start at all and to find their profile and temp space.
37/// - `PATHEXT`: for the child's own command lookups (a shell or `node` that
38///   resolves `npm` to `npm.cmd`). It does not affect how the host resolves
39///   the child's program: Rust's `Command` ignores `PATHEXT`, so a `.cmd` or
40///   `.bat` launcher must be configured with its extension.
41pub const DEFAULT_PASS_ENV: &[&str] =
42    &["PATH", "HOME", "LANG", "TMPDIR", "SYSTEMROOT", "USERPROFILE", "APPDATA", "TEMP", "TMP", "PATHEXT"];
43
44/// The variables of [`DEFAULT_PASS_ENV`] plus `extra` that are set on the host,
45/// with their values, for a child started after `env_clear()`.
46///
47/// ```
48/// let mut command = std::process::Command::new("true");
49/// command.env_clear().envs(graphrt_core::child_env::minimal_env(["MY_TOKEN"]));
50/// ```
51///
52/// Values are read with [`host_var`], so inside an AppImage `PATH` does not
53/// start with the bundle's folders.
54pub fn minimal_env<'a>(extra: impl IntoIterator<Item = &'a str>) -> impl Iterator<Item = (&'a str, OsString)> {
55    DEFAULT_PASS_ENV.iter().copied().chain(extra).filter_map(|name| host_var(name).map(|value| (name, value)))
56}
57
58/// Set by the AppImage runtime; meaningless (or misleading) for other programs.
59const APPIMAGE_RUNTIME_VARS: &[&str] = &["APPIMAGE", "ARGV0", "OWD"];
60
61/// One change that gives a child the computer's own environment back.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum EnvFix {
64    /// Set the variable to this value (the original without the bundle's entries).
65    Set(OsString, OsString),
66    /// Remove the variable (it only pointed into the bundle).
67    Remove(OsString),
68}
69
70impl EnvFix {
71    /// The variable this fix is about.
72    pub fn name(&self) -> &OsStr {
73        match self {
74            EnvFix::Set(name, _) | EnvFix::Remove(name) => name,
75        }
76    }
77}
78
79/// The fixes for an environment `vars` of an application running from the
80/// AppImage mounted at `appdir` (see the [module docs](self)), sorted by name.
81///
82/// ```
83/// use graphrt_core::child_env::{appimage_env_fixes, EnvFix};
84/// let vars = [("LD_LIBRARY_PATH".into(), "/tmp/.mount_x/usr/lib:/opt/lib".into())];
85/// let fixes = appimage_env_fixes(vars, std::path::Path::new("/tmp/.mount_x"));
86/// # #[cfg(unix)]
87/// assert_eq!(fixes, [EnvFix::Set("LD_LIBRARY_PATH".into(), "/opt/lib".into())]);
88/// ```
89pub fn appimage_env_fixes(vars: impl IntoIterator<Item = (OsString, OsString)>, appdir: &Path) -> Vec<EnvFix> {
90    let mut fixes: Vec<EnvFix> = vars
91        .into_iter()
92        .filter_map(|(name, value)| {
93            if APPIMAGE_RUNTIME_VARS.iter().any(|runtime_var| OsStr::new(runtime_var) == name) {
94                return Some(EnvFix::Remove(name));
95            }
96            let entries = split_entries(&name, &value);
97            if !entries.iter().any(|entry| is_inside(entry, appdir)) {
98                return None;
99            }
100            let kept: Vec<&OsStr> =
101                entries.into_iter().filter(|entry| !entry.is_empty() && !is_inside(entry, appdir)).collect();
102            if kept.is_empty() {
103                return Some(EnvFix::Remove(name));
104            }
105            Some(EnvFix::Set(name, join_entries(&kept)))
106        })
107        .collect();
108    fixes.sort_by(|left, right| left.name().cmp(right.name()));
109    fixes
110}
111
112/// A value's `:`-separated entries (`LD_PRELOAD` also splits on spaces, like the loader).
113#[cfg(unix)]
114fn split_entries<'a>(name: &OsStr, value: &'a OsStr) -> Vec<&'a OsStr> {
115    use std::os::unix::ffi::OsStrExt;
116    let is_separator = |byte: &u8| *byte == b':' || (name == "LD_PRELOAD" && byte.is_ascii_whitespace());
117    value.as_bytes().split(is_separator).map(OsStr::from_bytes).collect()
118}
119
120/// AppImages are Linux-only; elsewhere a value is one entry.
121#[cfg(not(unix))]
122fn split_entries<'a>(_name: &OsStr, value: &'a OsStr) -> Vec<&'a OsStr> {
123    vec![value]
124}
125
126fn join_entries(entries: &[&OsStr]) -> OsString {
127    let mut joined = OsString::new();
128    for (index, entry) in entries.iter().enumerate() {
129        if index > 0 {
130            joined.push(":");
131        }
132        joined.push(entry);
133    }
134    joined
135}
136
137/// Whether `entry` is an absolute path in `appdir` (`$APPDIR//usr/lib` included).
138fn is_inside(entry: &OsStr, appdir: &Path) -> bool {
139    let entry = Path::new(entry);
140    entry.is_absolute() && entry.starts_with(appdir)
141}
142
143/// The AppImage folder the application runs from: `$APPDIR`, but only when the
144/// running binary is inside it (a stray `APPDIR` in the user's shell changes nothing).
145fn running_appdir(appdir_var: Option<OsString>, current_exe: Option<PathBuf>) -> Option<PathBuf> {
146    let appdir = PathBuf::from(appdir_var?);
147    let is_mounted_bundle = appdir.is_absolute() && appdir.parent().is_some() && current_exe?.starts_with(&appdir);
148    is_mounted_bundle.then_some(appdir)
149}
150
151/// The fixes for this process, worked out once from the environment at the
152/// first call (empty outside a Linux AppImage).
153pub fn host_env_fixes() -> &'static [EnvFix] {
154    static FIXES: OnceLock<Vec<EnvFix>> = OnceLock::new();
155    FIXES.get_or_init(|| {
156        if !cfg!(target_os = "linux") {
157            return Vec::new();
158        }
159        match running_appdir(std::env::var_os("APPDIR"), std::env::current_exe().ok()) {
160            Some(appdir) => appimage_env_fixes(std::env::vars_os(), &appdir),
161            None => Vec::new(),
162        }
163    })
164}
165
166/// `name` as a child gets it: the process value with [`host_env_fixes`] applied.
167pub fn host_var(name: &str) -> Option<OsString> {
168    fixed_var(name, host_env_fixes())
169}
170
171fn fixed_var(name: &str, fixes: &[EnvFix]) -> Option<OsString> {
172    match fixes.iter().find(|fix| fix.name() == name) {
173        Some(EnvFix::Set(_, value)) => Some(value.clone()),
174        Some(EnvFix::Remove(_)) => None,
175        None => std::env::var_os(name),
176    }
177}
178
179/// Sets up the environment of a child process the way plugin processes and
180/// stdio MCP servers get it: the whole host environment when `inherit`, else
181/// only [`DEFAULT_PASS_ENV`] plus `pass_env`; either way as the computer has
182/// it, without an AppImage's entries ([`host_env_fixes`]). Call it before the
183/// command's own `env` calls. A Tokio command passes `command.as_std_mut()`.
184pub fn set_child_env<'a>(
185    command: &mut std::process::Command,
186    inherit: bool,
187    pass_env: impl IntoIterator<Item = &'a str>,
188) {
189    set_child_env_with(command, inherit, pass_env, host_env_fixes());
190}
191
192/// [`set_child_env`] with explicit `fixes` instead of this process's ones (tests,
193/// or an embedder that works them out itself).
194pub fn set_child_env_with<'a>(
195    command: &mut std::process::Command,
196    inherit: bool,
197    pass_env: impl IntoIterator<Item = &'a str>,
198    fixes: &[EnvFix],
199) {
200    if inherit {
201        apply_env_fixes(command, fixes);
202        return;
203    }
204    command.env_clear();
205    for name in DEFAULT_PASS_ENV.iter().copied().chain(pass_env) {
206        if let Some(value) = fixed_var(name, fixes) {
207            command.env(name, value);
208        }
209    }
210}
211
212/// The whole environment as a child gets it (for a command started after `env_clear()`).
213pub fn host_vars() -> Vec<(OsString, OsString)> {
214    let fixes = host_env_fixes();
215    std::env::vars_os()
216        .filter_map(|(name, value)| match fixes.iter().find(|fix| fix.name() == name.as_os_str()) {
217            Some(EnvFix::Set(_, fixed)) => Some((name, fixed.clone())),
218            Some(EnvFix::Remove(_)) => None,
219            None => Some((name, value)),
220        })
221        .collect()
222}
223
224/// Gives a command that inherits the environment the computer's own one: call
225/// it before the command's own `env` calls. A Tokio command passes
226/// `command.as_std_mut()`.
227///
228/// ```
229/// let mut command = std::process::Command::new("git");
230/// graphrt_core::child_env::apply_host_env(&mut command);
231/// command.arg("--version");
232/// ```
233pub fn apply_host_env(command: &mut std::process::Command) {
234    apply_env_fixes(command, host_env_fixes());
235}
236
237/// [`apply_host_env`] with explicit `fixes` (tests, or an embedder that works them out itself).
238pub fn apply_env_fixes(command: &mut std::process::Command, fixes: &[EnvFix]) {
239    for fix in fixes {
240        match fix {
241            EnvFix::Set(name, value) => command.env(name, value),
242            EnvFix::Remove(name) => command.env_remove(name),
243        };
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn only_set_variables_are_passed() {
253        let names: Vec<&str> = minimal_env(["GRAPHRT_CHILD_ENV_SURELY_UNSET"]).map(|(name, _)| name).collect();
254        assert!(!names.contains(&"GRAPHRT_CHILD_ENV_SURELY_UNSET"));
255        assert!(names.iter().all(|name| DEFAULT_PASS_ENV.contains(name)));
256        if std::env::var_os("PATH").is_some() {
257            assert!(names.contains(&"PATH"));
258        }
259    }
260
261    const APPDIR: &str = "/tmp/.mount_graphremPBnj";
262
263    fn vars(pairs: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
264        pairs.iter().map(|(name, value)| (OsString::from(name), OsString::from(value))).collect()
265    }
266
267    fn set(name: &str, value: &str) -> EnvFix {
268        EnvFix::Set(name.into(), value.into())
269    }
270
271    fn remove(name: &str) -> EnvFix {
272        EnvFix::Remove(name.into())
273    }
274
275    #[cfg(unix)]
276    #[test]
277    fn drops_bundle_entries_from_lists_and_keeps_the_rest() {
278        let env = vars(&[
279            ("PATH", "/tmp/.mount_graphremPBnj/usr/bin/:/tmp/.mount_graphremPBnj/usr/sbin/:/usr/local/bin:/usr/bin"),
280            (
281                "XDG_DATA_DIRS",
282                "/tmp/.mount_graphremPBnj/usr/share/:/tmp/.mount_graphremPBnj/usr/share:/usr/share:/var/lib/flatpak/exports/share",
283            ),
284            ("LD_LIBRARY_PATH", "/tmp/.mount_graphremPBnj/usr/lib/:/tmp/.mount_graphremPBnj/lib64/:/opt/cuda/lib64"),
285        ]);
286        assert_eq!(
287            appimage_env_fixes(env, Path::new(APPDIR)),
288            [
289                set("LD_LIBRARY_PATH", "/opt/cuda/lib64"),
290                set("PATH", "/usr/local/bin:/usr/bin"),
291                set("XDG_DATA_DIRS", "/usr/share:/var/lib/flatpak/exports/share"),
292            ]
293        );
294    }
295
296    #[cfg(unix)]
297    #[test]
298    fn removes_variables_left_empty_and_single_bundle_paths() {
299        // AppRun ends each list with the old value, which is empty when it was unset.
300        let env = vars(&[
301            ("LD_LIBRARY_PATH", "/tmp/.mount_graphremPBnj/usr/lib/:/tmp/.mount_graphremPBnj/usr/lib64/:"),
302            ("PYTHONHOME", "/tmp/.mount_graphremPBnj/usr/"),
303            ("GIO_MODULE_DIR", "/tmp/.mount_graphremPBnj//usr/lib/gio/modules"),
304            ("APPDIR", APPDIR),
305        ]);
306        assert_eq!(
307            appimage_env_fixes(env, Path::new(APPDIR)),
308            [remove("APPDIR"), remove("GIO_MODULE_DIR"), remove("LD_LIBRARY_PATH"), remove("PYTHONHOME")]
309        );
310    }
311
312    #[test]
313    fn removes_the_appimage_runtime_variables() {
314        let env =
315            vars(&[("APPIMAGE", "/home/me/graphrt.AppImage"), ("ARGV0", "./graphrt.AppImage"), ("OWD", "/home/me")]);
316        assert_eq!(appimage_env_fixes(env, Path::new(APPDIR)), [remove("APPIMAGE"), remove("ARGV0"), remove("OWD")]);
317    }
318
319    #[test]
320    fn leaves_everything_else_alone() {
321        let env = vars(&[
322            ("HOME", "/home/me"),
323            ("PATH", "/usr/local/bin:/usr/bin"),
324            ("GTK_THEME", "Adwaita:dark"),
325            // Same prefix, different folder.
326            ("SOME_DIR", "/tmp/.mount_graphremPBnjX/usr/lib"),
327            // Relative entries never count as the bundle.
328            ("CDPATH", "tmp/.mount_graphremPBnj:."),
329            ("URL", "https://example.com:8443/tmp/.mount_graphremPBnj"),
330        ]);
331        assert!(appimage_env_fixes(env, Path::new(APPDIR)).is_empty());
332    }
333
334    #[cfg(unix)]
335    #[test]
336    fn ld_preload_splits_on_spaces_too() {
337        let env = vars(&[("LD_PRELOAD", "/tmp/.mount_graphremPBnj/usr/lib/libhack.so /usr/lib/libgamemodeauto.so.0")]);
338        assert_eq!(appimage_env_fixes(env, Path::new(APPDIR)), [set("LD_PRELOAD", "/usr/lib/libgamemodeauto.so.0")]);
339    }
340
341    #[test]
342    fn appdir_counts_only_when_the_binary_runs_from_it() {
343        let exe_inside = Some(PathBuf::from("/tmp/.mount_graphremPBnj/usr/bin/graphrt"));
344        assert_eq!(running_appdir(Some(APPDIR.into()), exe_inside.clone()), Some(PathBuf::from(APPDIR)));
345        assert_eq!(running_appdir(Some(APPDIR.into()), Some(PathBuf::from("/usr/bin/graphrt"))), None);
346        assert_eq!(running_appdir(None, exe_inside.clone()), None);
347        assert_eq!(running_appdir(Some("relative/dir".into()), exe_inside.clone()), None);
348        assert_eq!(running_appdir(Some("/".into()), exe_inside), None);
349        assert_eq!(running_appdir(Some(APPDIR.into()), None), None);
350    }
351
352    #[test]
353    fn apply_sets_and_removes_on_the_command() {
354        let mut command = std::process::Command::new("true");
355        apply_env_fixes(&mut command, &[set("PATH", "/usr/bin"), remove("LD_LIBRARY_PATH")]);
356        let envs: Vec<(&OsStr, Option<&OsStr>)> = command.get_envs().collect();
357        assert_eq!(envs, [(OsStr::new("LD_LIBRARY_PATH"), None), (OsStr::new("PATH"), Some(OsStr::new("/usr/bin")))]);
358    }
359
360    /// The variables a command sets (`None`: removed), by name.
361    fn command_env(command: &std::process::Command) -> Vec<(String, Option<String>)> {
362        command
363            .get_envs()
364            .map(|(name, value)| {
365                (name.to_string_lossy().into_owned(), value.map(|value| value.to_string_lossy().into_owned()))
366            })
367            .collect()
368    }
369
370    #[test]
371    fn an_inheriting_child_gets_the_fixes() {
372        let mut command = std::process::Command::new("true");
373        set_child_env_with(&mut command, true, [], &[remove("LD_LIBRARY_PATH"), set("PATH", "/usr/bin")]);
374        assert_eq!(command_env(&command), [("LD_LIBRARY_PATH".into(), None), ("PATH".into(), Some("/usr/bin".into()))]);
375    }
376
377    #[test]
378    fn a_minimal_child_gets_fixed_values_and_nothing_removed() {
379        let mut command = std::process::Command::new("true");
380        // `HOME` is passed by default; a fix removing it wins over the host value.
381        set_child_env_with(
382            &mut command,
383            false,
384            ["GRAPHRT_CHILD_ENV_SURELY_UNSET"],
385            &[set("PATH", "/usr/bin"), remove("HOME")],
386        );
387        let env = command_env(&command);
388        assert!(env.contains(&("PATH".into(), Some("/usr/bin".into()))));
389        assert!(env.iter().all(|(name, _)| name != "HOME" && name != "GRAPHRT_CHILD_ENV_SURELY_UNSET"));
390        assert!(env.iter().all(|(name, _)| DEFAULT_PASS_ENV.contains(&name.as_str())));
391    }
392
393    #[test]
394    fn nothing_changes_outside_an_appimage() {
395        // The test runner is not an AppImage.
396        assert!(host_env_fixes().is_empty());
397        assert_eq!(host_var("HOME"), std::env::var_os("HOME"));
398        let mut command = std::process::Command::new("true");
399        apply_host_env(&mut command);
400        assert_eq!(command.get_envs().count(), 0);
401    }
402}