Skip to main content

agentmux_common/
secret_env.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Taking a secret out of the process environment for good.
5//!
6//! The launcher hands srv and the host `AGENTMUX_AUTH_KEY` and
7//! `AGENTMUX_HOST_REG_SECRET` in their environment. `std::env::remove_var`
8//! drops the variable from the process's own view (and from the environment of
9//! any process it starts afterwards), but on Unix the strings stay where the
10//! kernel put them at `exec`, and `/proc/<pid>/environ` (Linux) and
11//! `ps eww` / `KERN_PROCARGS2` (macOS) read exactly that block, for any process
12//! of the same user. Wiping overwrites the value in place before removing it.
13//!
14//! On Windows `SetEnvironmentVariable` rewrites the process's live environment
15//! block, which is what another process reads, so removing the variable there
16//! is enough.
17//!
18//! The two startup secrets are moved out of the environment as the first thing
19//! srv and the host do ([`stash_startup_secrets`]), before they start anything,
20//! so no process they spawn inherits them; the code that needs a value takes it
21//! from the stash with [`take`].
22
23use std::collections::HashMap;
24use std::sync::Mutex;
25
26/// What the launcher hands srv and the host in their environment.
27pub const STARTUP_SECRETS: &[&str] = &["AGENTMUX_AUTH_KEY", "AGENTMUX_HOST_REG_SECRET"];
28
29static STASH: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);
30
31fn stash_map() -> std::sync::MutexGuard<'static, Option<HashMap<String, String>>> {
32    STASH.lock().unwrap_or_else(|e| e.into_inner())
33}
34
35/// Moves [`STARTUP_SECRETS`] out of the environment into the stash (wiped from
36/// the environment block in place on Unix). Call it first thing in `main`.
37pub fn stash_startup_secrets() {
38    stash(STARTUP_SECRETS);
39}
40
41/// Wipes [`STARTUP_SECRETS`] from the environment for good, keeping no copy. For
42/// a process that mints its own secrets and never needs the ones it was started
43/// with (the launcher): a pane or shell that holds an instance's key must not
44/// pass it on through `/proc/<pid>/environ`.
45pub fn discard_startup_secrets() {
46    for name in STARTUP_SECRETS {
47        take_from_env(name);
48    }
49}
50
51/// Moves each named variable that is set and not empty into the stash.
52pub fn stash(names: &[&str]) {
53    for name in names {
54        if let Some(value) = take_from_env(name).filter(|v| !v.is_empty()) {
55            stash_map().get_or_insert_with(HashMap::new).insert((*name).to_string(), value);
56        }
57    }
58}
59
60/// The stashed secrets as variables, for a process that re-executes itself and
61/// needs them again in its new environment.
62pub fn stashed() -> Vec<(String, String)> {
63    stash_map().as_ref().map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()).unwrap_or_default()
64}
65
66/// Whether `name` has a non-empty value, stashed or still in the environment.
67pub fn is_set(name: &str) -> bool {
68    stash_map().as_ref().is_some_and(|m| m.contains_key(name)) || std::env::var(name).is_ok_and(|v| !v.is_empty())
69}
70
71/// The value of `name`: the stashed one, else (a process that never stashed, a
72/// test) the environment's, wiped from there as it is read. None when unset.
73pub fn take(name: &str) -> Option<String> {
74    let stashed = stash_map().as_mut().and_then(|m| m.remove(name));
75    stashed.or_else(|| take_from_env(name))
76}
77
78/// Reads `name`, wipes its value from the process environment (in place on
79/// Unix), removes the variable, and returns the value. None when it is unset or
80/// not valid UTF-8 (the variable is removed either way).
81fn take_from_env(name: &str) -> Option<String> {
82    let value = std::env::var(name).ok();
83    #[cfg(unix)]
84    wipe_in_place(name);
85    std::env::remove_var(name);
86    value
87}
88
89/// Overwrites the bytes `getenv(name)` points at with zeros. The pointer is
90/// into the environment block (the kernel's copy from `exec`, or the allocation
91/// of a later `setenv`), which stays writable and the same size for the life of
92/// the variable.
93#[cfg(unix)]
94fn wipe_in_place(name: &str) {
95    let Ok(c_name) = std::ffi::CString::new(name) else { return };
96    // SAFETY: getenv returns a NUL-terminated string that lives until the
97    // variable is changed, which this function's caller does next, in that
98    // order and on this thread. Writing zeros over its own length stays inside
99    // the allocation.
100    unsafe {
101        let value = libc::getenv(c_name.as_ptr());
102        if value.is_null() {
103            return;
104        }
105        let len = libc::strlen(value);
106        std::ptr::write_bytes(value as *mut u8, 0, len);
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    // These mutate process-global state; each uses its own variable name.
115
116    #[test]
117    fn returns_the_value_and_removes_the_variable() {
118        std::env::set_var("AM_SECRET_ENV_TEST_A", "the-secret-value");
119        assert_eq!(take("AM_SECRET_ENV_TEST_A").as_deref(), Some("the-secret-value"));
120        assert!(std::env::var("AM_SECRET_ENV_TEST_A").is_err());
121        assert_eq!(take("AM_SECRET_ENV_TEST_A"), None);
122    }
123
124    #[test]
125    fn a_discarded_secret_leaves_the_environment_and_is_not_kept() {
126        let name = STARTUP_SECRETS[0];
127        std::env::set_var(name, "inherited-from-a-pane");
128        discard_startup_secrets();
129        assert!(std::env::var(name).is_err());
130        assert!(!is_set(name));
131        assert_eq!(take(name), None);
132    }
133
134    // What another process of the user reads: the environment block as exec left it. Runs the
135    // test binary again so the block really starts with the secret in it.
136    #[cfg(target_os = "linux")]
137    #[test]
138    fn a_discarded_secret_is_gone_from_proc_environ() {
139        const MARK: &str = "AM_DISCARD_CHILD";
140        if std::env::var_os(MARK).is_some() {
141            let before = std::fs::read("/proc/self/environ").unwrap();
142            assert!(String::from_utf8_lossy(&before).contains("inherited-secret-value"));
143            discard_startup_secrets();
144            let after = std::fs::read("/proc/self/environ").unwrap();
145            assert!(!String::from_utf8_lossy(&after).contains("inherited-secret-value"));
146            return;
147        }
148        let status = std::process::Command::new(std::env::current_exe().unwrap())
149            .args(["--exact", "secret_env::tests::a_discarded_secret_is_gone_from_proc_environ", "--test-threads=1"])
150            .env(MARK, "1")
151            .env(STARTUP_SECRETS[0], "inherited-secret-value")
152            .env(STARTUP_SECRETS[1], "inherited-secret-value")
153            .status()
154            .unwrap();
155        assert!(status.success());
156    }
157
158    #[test]
159    fn an_unset_variable_is_none() {
160        assert_eq!(take("AM_SECRET_ENV_TEST_NEVER_SET"), None);
161    }
162
163    #[test]
164    fn a_stashed_secret_is_out_of_the_environment_and_still_there_to_take_once() {
165        std::env::set_var("AM_SECRET_ENV_TEST_C", "stash-me");
166        std::env::set_var("AM_SECRET_ENV_TEST_C_EMPTY", "");
167        stash(&["AM_SECRET_ENV_TEST_C", "AM_SECRET_ENV_TEST_C_EMPTY", "AM_SECRET_ENV_TEST_C_UNSET"]);
168        // Gone from the environment, so a process started now does not inherit it.
169        assert!(std::env::var("AM_SECRET_ENV_TEST_C").is_err());
170        assert!(std::env::var("AM_SECRET_ENV_TEST_C_EMPTY").is_err());
171        // What a child started now would inherit is the process's environment as it stands.
172        assert!(std::env::vars().all(|(k, v)| k != "AM_SECRET_ENV_TEST_C" && v != "stash-me"));
173        assert!(is_set("AM_SECRET_ENV_TEST_C"));
174        assert!(!is_set("AM_SECRET_ENV_TEST_C_EMPTY"));
175        assert!(stashed().contains(&("AM_SECRET_ENV_TEST_C".to_string(), "stash-me".to_string())));
176        assert_eq!(take("AM_SECRET_ENV_TEST_C").as_deref(), Some("stash-me"));
177        assert_eq!(take("AM_SECRET_ENV_TEST_C"), None);
178        assert!(!is_set("AM_SECRET_ENV_TEST_C"));
179    }
180
181    // What /proc/<pid>/environ shows is the block the value lives in, so look
182    // at those bytes directly: after the wipe the string getenv points at is empty
183    // and every byte of the old value is zero.
184    #[cfg(unix)]
185    #[test]
186    fn the_bytes_the_environment_block_held_are_zero_after_the_wipe() {
187        let secret = "wipe-me-0123456789";
188        std::env::set_var("AM_SECRET_ENV_TEST_B", secret);
189        let c_name = std::ffi::CString::new("AM_SECRET_ENV_TEST_B").unwrap();
190        // SAFETY: a getenv pointer is valid until the variable is changed, and nothing
191        // changes it between here and the reads below (the wipe writes through it).
192        let ptr = unsafe { libc::getenv(c_name.as_ptr()) } as *const u8;
193        wipe_in_place("AM_SECRET_ENV_TEST_B");
194        let bytes = unsafe { std::slice::from_raw_parts(ptr, secret.len()) };
195        assert!(bytes.iter().all(|b| *b == 0), "the secret's bytes are still in the block: {bytes:?}");
196        assert_eq!(std::env::var("AM_SECRET_ENV_TEST_B").as_deref(), Ok(""));
197        std::env::remove_var("AM_SECRET_ENV_TEST_B");
198    }
199}