Skip to main content

hatchery_node/
m4a_accounts.rs

1//! Per-session m4a accounts assigned by the node at spawn (owner model: session = nick = one key
2//! = one role). When `HATCHERY_M4A_AGENT_BIN` and `HATCHERY_M4A_ACCOUNTS_ROOT` are set, every PTY
3//! spawn gets its own account: the node runs `m4a-agent account provision` (registry and vaults
4//! stay under the node's accounts root, outside the session sandbox), reads the fresh capability
5//! from a one-shot 0600 file it removes at once, and injects ONLY `M4A_NICK` and
6//! `M4A_SESSION_CAP` into that session's child environment. The capability is never logged.
7
8use std::ffi::OsString;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use gate4agent_catalog::EnvMutation;
13
14/// g4a provider id -> the provider name `m4a-agent` accepts. g4a's built-in catalog is
15/// `claude`, `codex`, `grok`, `kimi`; anything else (custom agents) gets no account.
16pub fn m4a_provider(g4a_agent_id: &str) -> Option<&'static str> {
17    match g4a_agent_id {
18        "claude" => Some("claude-code"),
19        "codex" => Some("codex"),
20        "grok" => Some("grok"),
21        "kimi" => Some("kimi-code"),
22        _ => None,
23    }
24}
25
26pub const AGENT_BIN_ENV: &str = "HATCHERY_M4A_AGENT_BIN";
27pub const ACCOUNTS_ROOT_ENV: &str = "HATCHERY_M4A_ACCOUNTS_ROOT";
28
29#[derive(Debug, Clone)]
30pub struct M4aSessionAccounts {
31    bin: PathBuf,
32    base: PathBuf,
33}
34
35/// One session's account as handed to its child: nick and capability only.
36pub struct SessionAccount {
37    pub nick: String,
38    /// The provider session key the account is bound to (also given to the session as
39    /// `M4A_SESSION_ID`, so its own inbox commands address the right account).
40    pub session_id: String,
41    cap: String,
42}
43
44impl Drop for SessionAccount {
45    fn drop(&mut self) {
46        // Best effort wipe of the capability copy held by the node.
47        let bytes = unsafe { self.cap.as_bytes_mut() };
48        bytes.iter_mut().for_each(|b| *b = 0);
49    }
50}
51
52impl std::fmt::Debug for SessionAccount {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("SessionAccount").field("nick", &self.nick).finish_non_exhaustive()
55    }
56}
57
58impl SessionAccount {
59    /// The only variables the session gets from the node for m4a.
60    pub fn env_mutations(&self) -> Vec<EnvMutation> {
61        vec![
62            EnvMutation { key: OsString::from("M4A_NICK"), value: Some(OsString::from(&self.nick)) },
63            EnvMutation { key: OsString::from("M4A_SESSION_CAP"), value: Some(OsString::from(&self.cap)) },
64            EnvMutation { key: OsString::from("M4A_SESSION_ID"), value: Some(OsString::from(&self.session_id)) },
65        ]
66    }
67}
68
69impl M4aSessionAccounts {
70    /// Fallback identity channel: `<root>/sessions/<nick>.session` (owner-only), the same three
71    /// keys as [`SessionAccount::env_mutations`], for a provider whose tools run in a process
72    /// that did not inherit the session environment (`m4a-agent --session-file <path> ...`).
73    pub fn session_file_path(&self, nick: &str) -> Option<PathBuf> {
74        let ok = !nick.is_empty() && nick.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
75        ok.then(|| self.base.join("sessions").join(format!("{nick}.session")))
76    }
77
78    pub fn write_session_file(&self, account: &SessionAccount) -> Result<PathBuf, String> {
79        let path = self.session_file_path(&account.nick).ok_or("invalid nick")?;
80        let dir = path.parent().ok_or("no dir")?;
81        std::fs::create_dir_all(dir).map_err(|e| format!("sessions dir: {}", e.kind()))?;
82        let mut body = String::new();
83        for m in account.env_mutations() {
84            if let Some(v) = m.value {
85                body.push_str(&format!("{}={}\n", m.key.to_string_lossy(), v.to_string_lossy()));
86            }
87        }
88        let mut opts = std::fs::OpenOptions::new();
89        opts.write(true).create(true).truncate(true);
90        #[cfg(unix)]
91        {
92            use std::os::unix::fs::OpenOptionsExt;
93            opts.mode(0o600);
94        }
95        use std::io::Write;
96        opts.open(&path)
97            .and_then(|mut f| f.write_all(body.as_bytes()))
98            .map_err(|e| format!("session file: {}", e.kind()))?;
99        body.zeroize_best_effort();
100        Ok(path)
101    }
102
103    pub fn remove_session_file(&self, nick: &str) {
104        if let Some(path) = self.session_file_path(nick) {
105            let _ = std::fs::remove_file(path);
106        }
107    }
108
109    pub fn new(bin: impl Into<PathBuf>, base: impl Into<PathBuf>) -> Self {
110        Self { bin: bin.into(), base: base.into() }
111    }
112
113    /// The node's letter-wake token (`<root>/.node-wake-token`, 0600), created on first use.
114    pub fn wake_token(&self) -> Result<String, String> {
115        let path = self.base.join(".node-wake-token");
116        if let Ok(t) = std::fs::read_to_string(&path) {
117            if t.trim().len() >= 32 {
118                return Ok(t.trim().to_owned());
119            }
120        }
121        std::fs::create_dir_all(&self.base).map_err(|e| format!("accounts root: {}", e.kind()))?;
122        let mut raw = [0u8; 24];
123        getrandom(&mut raw)?;
124        let token: String = raw.iter().map(|b| format!("{b:02x}")).collect();
125        let mut opts = std::fs::OpenOptions::new();
126        opts.write(true).create(true).truncate(true);
127        #[cfg(unix)]
128        {
129            use std::os::unix::fs::OpenOptionsExt;
130            opts.mode(0o600);
131        }
132        use std::io::Write;
133        opts.open(&path).and_then(|mut f| f.write_all(token.as_bytes())).map_err(|e| format!("wake token: {}", e.kind()))?;
134        Ok(token)
135    }
136
137    pub fn from_env() -> Option<Self> {
138        let get = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
139        Some(Self::new(get(AGENT_BIN_ENV)?, get(ACCOUNTS_ROOT_ENV)?))
140    }
141
142    pub fn base(&self) -> &Path {
143        &self.base
144    }
145
146    /// The account of `(provider, session_key)`, created if missing, with a fresh capability
147    /// (a respawn of the same session invalidates the previous process's key).
148    pub fn provision(&self, provider: &str, session_key: &str) -> Result<SessionAccount, String> {
149        std::fs::create_dir_all(&self.base).map_err(|e| format!("accounts root: {}", e.kind()))?;
150        let mut rand = [0u8; 12];
151        getrandom(&mut rand)?;
152        let tag: String = rand.iter().map(|b| format!("{b:02x}")).collect();
153        let cap_file = self.base.join(format!(".spawn-{tag}.cap"));
154        let out = Command::new(&self.bin)
155            .args(["account", "provision", "--provider", provider, "--session", session_key, "--rotate", "--cap-out"])
156            .arg(&cap_file)
157            .env("M4A_ACCOUNTS_ROOT", &self.base)
158            .env_remove("M4A_SESSION_CAP")
159            .env_remove("M4A_PRODUCT_INVITE")
160            .output()
161            .map_err(|e| format!("m4a-agent: {}", e.kind()))?;
162        let cap = std::fs::read_to_string(&cap_file);
163        let _ = std::fs::remove_file(&cap_file);
164        if !out.status.success() {
165            return Err(format!("m4a-agent account provision failed ({})", out.status.code().unwrap_or(-1)));
166        }
167        let v: serde_json::Value = serde_json::from_slice(&out.stdout).map_err(|_| "m4a-agent answer is not json".to_string())?;
168        let nick = v["nick"].as_str().ok_or("m4a-agent answer has no nick")?.to_string();
169        let cap = cap.map_err(|_| "no capability issued".to_string())?;
170        if cap.trim().is_empty() || cap.contains('\n') {
171            return Err("capability is malformed".into());
172        }
173        Ok(SessionAccount { nick, session_id: session_key.to_owned(), cap })
174    }
175}
176
177fn getrandom(buf: &mut [u8]) -> Result<(), String> {
178    use std::io::Read;
179    std::fs::File::open("/dev/urandom")
180        .and_then(|mut f| f.read_exact(buf))
181        .or_else(|_| {
182            // Non-unix fallback: time + address entropy is enough for a unique temp name.
183            let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
184            for (i, b) in buf.iter_mut().enumerate() {
185                *b = (t >> ((i % 16) * 8)) as u8 ^ (i as u8);
186            }
187            Ok::<(), std::io::Error>(())
188        })
189        .map_err(|e| e.to_string())
190}
191
192#[cfg(all(test, unix))]
193mod tests {
194    use super::*;
195
196    fn fake_agent(dir: &Path) -> PathBuf {
197        // Stands in for m4a-agent: one nick per --session, the cap written to --cap-out.
198        let p = dir.join("fake-m4a-agent");
199        std::fs::write(
200            &p,
201            "#!/bin/sh\nwhile [ $# -gt 0 ]; do case \"$1\" in --session) s=$2; shift;; --cap-out) o=$2; shift;; esac; shift; done\n\
202             umask 077; printf 'cap-%s-%s' \"$s\" \"$$\" > \"$o\"; printf '{\"nick\":\"codex-%s\",\"cap_issued\":true}\\n' \"$s\"\n",
203        )
204        .unwrap();
205        use std::os::unix::fs::PermissionsExt;
206        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
207        p
208    }
209
210    #[test]
211    fn each_spawn_gets_its_own_account_and_only_nick_and_cap_are_injected() {
212        let dir = std::env::temp_dir().join(format!("hatch-m4a-{}", std::process::id()));
213        let _ = std::fs::remove_dir_all(&dir);
214        std::fs::create_dir_all(&dir).unwrap();
215        let acc = M4aSessionAccounts::new(fake_agent(&dir), dir.join("accounts"));
216        let a = acc.provision("codex", "inc-1").unwrap();
217        let b = acc.provision("codex", "inc-2").unwrap();
218        assert_ne!(a.nick, b.nick);
219        let env = a.env_mutations();
220        let keys: Vec<_> = env.iter().map(|m| m.key.to_string_lossy().into_owned()).collect();
221        assert_eq!(keys, ["M4A_NICK", "M4A_SESSION_CAP", "M4A_SESSION_ID"]);
222        assert_eq!(env[2].value.as_deref(), Some(std::ffi::OsStr::new("inc-1")));
223        assert_ne!(env[1].value, b.env_mutations()[1].value);
224        // The one-shot cap file is gone and the cap is not in Debug output.
225        let left: Vec<_> = std::fs::read_dir(acc.base()).unwrap().filter_map(Result::ok).filter(|e| e.file_name().to_string_lossy().ends_with(".cap")).collect();
226        assert!(left.is_empty());
227        assert!(!format!("{a:?}").contains("cap-"));
228    }
229
230    #[test]
231    fn every_builtin_g4a_provider_maps_to_an_m4a_provider() {
232        for spec in gate4agent_catalog::builtin_specs() {
233            let id = spec.id.as_str().to_string();
234            assert!(m4a_provider(&id).is_some(), "g4a provider {id} has no m4a mapping");
235        }
236        assert_eq!(m4a_provider("custom"), None);
237    }
238
239    #[cfg(unix)]
240    #[test]
241    fn wake_token_is_private_stable_and_long() {
242        use std::os::unix::fs::PermissionsExt;
243        let dir = std::env::temp_dir().join(format!("node-wake-token-{}", std::process::id()));
244        let a = M4aSessionAccounts::new("/bin/false", &dir);
245        let t1 = a.wake_token().unwrap();
246        assert_eq!(t1.len(), 48);
247        assert_eq!(a.wake_token().unwrap(), t1);
248        let mode = std::fs::metadata(dir.join(".node-wake-token")).unwrap().permissions().mode() & 0o777;
249        assert_eq!(mode, 0o600);
250        let _ = std::fs::remove_dir_all(&dir);
251    }
252
253    #[test]
254    fn a_failing_agent_injects_nothing() {
255        let acc = M4aSessionAccounts::new("/nonexistent/m4a-agent", std::env::temp_dir().join("hatch-m4a-none"));
256        assert!(acc.provision("codex", "x").is_err());
257    }
258}
259
260trait ZeroizeBestEffort {
261    fn zeroize_best_effort(&mut self);
262}
263
264impl ZeroizeBestEffort for String {
265    fn zeroize_best_effort(&mut self) {
266        // SAFETY: zero bytes keep the buffer valid UTF-8.
267        unsafe { self.as_bytes_mut() }.iter_mut().for_each(|b| *b = 0);
268    }
269}
270
271#[cfg(test)]
272mod session_file_tests {
273    use super::*;
274
275    #[test]
276    fn session_file_path_refuses_path_like_nicks() {
277        let a = M4aSessionAccounts::new("bin", std::env::temp_dir().join("m4a-sf-test"));
278        assert!(a.session_file_path("grok-1").unwrap().ends_with("sessions/grok-1.session"));
279        assert!(a.session_file_path("../x").is_none());
280        assert!(a.session_file_path("").is_none());
281    }
282}