Skip to main content

agentmux_srv_core/backend/
gh_guard.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Plain `gh` inside an agent process must not act as a human's `gh` login, when
5//! the agent has a GitHub identity of its own.
6//!
7//! An agent can reach GitHub through an identity of its own: `gh-agent`, which
8//! hands `gh` a per-call token, or the AgentMux App's broker, which does the same
9//! for `git` and `gh`. The `gh` CLI, run directly, instead reads whatever login a
10//! human made on the host — so an agent that types `gh` where it meant its own
11//! identity silently acts as that human, with nothing failing. `gh` finds its
12//! accounts through `$GH_CONFIG_DIR/hosts.yml`; pointing that variable at a
13//! directory with no `hosts.yml` leaves `gh` with no accounts, so it reports
14//! "not logged in" instead. The agent's own identity is unaffected: it passes its
15//! own token.
16//!
17//! An agent with no such identity has nothing to be protected into using: the
18//! person's own `gh login` is the only GitHub access it can have, so it is left
19//! alone ([`has_other_github_identity`]). A guard directory an earlier start set
20//! is dropped then, so a person who logged in with `gh auth login` and runs agents
21//! gets agents that can use `gh`.
22//!
23//! [`apply_gh_guard`] is called on every path that spawns an agent process or
24//! runs a command on an agent's behalf. Where it applies, `GH_CONFIG_DIR` is a
25//! RESERVED variable: it always overwrites whatever the env already carries (a
26//! persisted `cmd:env`, a caller's override), because a single user-supplied
27//! value would re-open the hole. Containers are not given it (host-only in `agent_env_scope`)
28//! deliberately — the host path means nothing inside the image.
29
30use std::collections::HashMap;
31use std::path::{Path, PathBuf};
32
33pub const GH_CONFIG_DIR: &str = "GH_CONFIG_DIR";
34
35/// Block meta on an agent's PtyShell: the agent's guard directory, which the
36/// PTY spawn sets as `GH_CONFIG_DIR` (`blockcontroller::shell::lifecycle`). A
37/// PTY shell's env is built from its own block, not from the agent's, so the
38/// guard has to travel on that block.
39pub const META_KEY_PTYSHELL_GH_CONFIG_DIR: &str = "ptyshell:ghconfigdir";
40
41/// The guard directory for an agent whose stored `cmd:env` is `agent_env`
42/// (the slug is read from it, as for the agent's own spawns), prepared the
43/// same way: created, with any login in it cleared. Empty when the agent is not
44/// guarded (it has no other GitHub identity), so the shell sets nothing.
45pub fn guard_dir_for(agent_env: &HashMap<String, String>) -> String {
46    guard_dir_for_target(agent_env, false)
47}
48
49/// [`guard_dir_for`] for a shell that may run elsewhere. `remote`: a WSL distro or an SSH host,
50/// whose own GitHub identity is not known from here, so the person's login is kept from it as
51/// every guarded spawn did before the guard became conditional.
52pub fn guard_dir_for_target(agent_env: &HashMap<String, String>, remote: bool) -> String {
53    let home = guard_config_home();
54    let mut env = agent_env.clone();
55    apply_gh_guard_for(&mut env, &home, remote || has_other_github_identity(agent_env));
56    match env.remove(GH_CONFIG_DIR) {
57        Some(dir) if is_own_guard_dir(&dir, &home) => dir,
58        _ => String::new(),
59    }
60}
61
62/// Whether `dir` is one of the guard directories [`agent_gh_config_dir`] makes
63/// under `config_home`, as opposed to a `GH_CONFIG_DIR` the person or their
64/// agent's definition chose.
65fn is_own_guard_dir(dir: &str, config_home: &Path) -> bool {
66    let dir = Path::new(dir);
67    dir.parent() == Some(config_home) && dir.file_name().is_some_and(|n| n.to_string_lossy().starts_with("gh-"))
68}
69
70/// The file `gh` records its accounts in. Its absence is what "logged out"
71/// means; nothing else in the directory is touched.
72const GH_HOSTS_FILE: &str = "hosts.yml";
73
74/// Directory name for an env with no agent identity on it. Still guarded —
75/// an unattributed spawn is not a reason to fall back to the human's login.
76const UNATTRIBUTED: &str = "unattributed";
77
78/// `<config_home>/gh-<slug>`, the same location `agent.open` has always used.
79///
80/// The slug is reduced to `[a-z0-9_-]` so it can never name a path outside
81/// `config_home` — this directory is one [`clear_gh_login`] deletes from.
82pub fn agent_gh_config_dir(config_home: &Path, agent_slug: Option<&str>) -> PathBuf {
83    let slug: String = agent_slug
84        .unwrap_or("")
85        .trim()
86        .to_lowercase()
87        .chars()
88        .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' })
89        .collect();
90    let slug = slug.trim_matches('-');
91    let slug = if slug.is_empty() { UNATTRIBUTED } else { slug };
92    config_home.join(format!("gh-{slug}"))
93}
94
95/// Create `dir` if needed and remove a `hosts.yml` from it.
96///
97/// A login can land here: `gh`'s own "not logged in" error tells the reader to
98/// run `gh auth login`, and doing that inside an agent writes exactly this
99/// file. Clearing it on every spawn is what keeps the guard from being undone
100/// by one well-meant login. Only that one file is removed; `gh`'s preferences
101/// (`config.yml`) are left alone.
102pub fn clear_gh_login(dir: &Path) -> std::io::Result<()> {
103    std::fs::create_dir_all(dir)?;
104    let hosts = dir.join(GH_HOSTS_FILE);
105    match std::fs::symlink_metadata(&hosts) {
106        // A file or a symlink: remove the entry itself, never a link's target.
107        Ok(meta) if !meta.is_dir() => std::fs::remove_file(&hosts),
108        Ok(_) => Err(std::io::Error::new(
109            std::io::ErrorKind::Other,
110            format!("{} is a directory, not a gh login file", hosts.display()),
111        )),
112        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
113        Err(e) => Err(e),
114    }
115}
116
117/// Point `GH_CONFIG_DIR` at this agent's login-free directory, under
118/// `config_home`. The agent is read from the env itself
119/// (`AGENTMUX_AGENT_SLUG`, then `AGENTMUX_AGENT_ID`).
120///
121/// Never fails the spawn: if the directory can't be prepared the variable is
122/// still set, and a missing directory is just as logged-out as an empty one.
123pub fn apply_gh_guard_in(env_vars: &mut HashMap<String, String>, config_home: &Path) {
124    let slug = ["AGENTMUX_AGENT_SLUG", "AGENTMUX_AGENT_ID"]
125        .iter()
126        .filter_map(|k| env_vars.get(*k))
127        .map(|v| v.trim())
128        .find(|v| !v.is_empty())
129        .map(str::to_string);
130    let dir = agent_gh_config_dir(config_home, slug.as_deref());
131    if let Err(e) = clear_gh_login(&dir) {
132        tracing::warn!(dir = %dir.display(), error = %e, "gh guard: could not clear the agent's gh login dir");
133    }
134    env_vars.insert(GH_CONFIG_DIR.to_string(), dir.to_string_lossy().into_owned());
135}
136
137/// Guard the agent when it has another GitHub identity; otherwise leave `gh` to
138/// the person's own login, and drop a guard directory an earlier start put in the
139/// env (a `GH_CONFIG_DIR` of the person's own choosing stays).
140pub fn apply_gh_guard_for(env_vars: &mut HashMap<String, String>, config_home: &Path, other_identity: bool) {
141    if other_identity {
142        apply_gh_guard_in(env_vars, config_home);
143    } else if env_vars.get(GH_CONFIG_DIR).is_some_and(|dir| is_own_guard_dir(dir, config_home)) {
144        env_vars.remove(GH_CONFIG_DIR);
145    }
146}
147
148/// Whether the agent whose spawn env is `env` has a GitHub identity besides the
149/// person's `gh` login: `gh-agent` on this machine (its hooks written, or the
150/// command on the PATH), or the AgentMux App's broker. Only then does
151/// [`apply_gh_guard`] keep the person's login from it.
152pub fn has_other_github_identity(env: &HashMap<String, String>) -> bool {
153    // Under test every spawn is guarded, as every test of a spawn env expects.
154    #[cfg(any(test, feature = "test-support"))]
155    {
156        let _ = env;
157        true
158    }
159    #[cfg(not(any(test, feature = "test-support")))]
160    {
161        crate::backend::publish_guard::hooks_dir_for(env, |k| std::env::var(k).ok()).is_some()
162            || gh_agent_on_path(env)
163            || crate::identity::github_tokens::agents_use_broker(env)
164    }
165}
166
167/// Whether this computer has gh-agent (its hooks written, or the command on this process's PATH): the part
168/// of [`has_other_github_identity`] that is about the machine, not about the AgentMux App. Connectors says
169/// it as the GitHub section's status (`github.connection`).
170pub fn gh_agent_on_this_computer() -> bool {
171    gh_agent_here(&HashMap::new(), |k| std::env::var(k).ok())
172}
173
174/// [`gh_agent_on_this_computer`] for the spawn env `env`, with `process` for anything it doesn't set.
175fn gh_agent_here(env: &HashMap<String, String>, process: impl Fn(&str) -> Option<String>) -> bool {
176    crate::backend::publish_guard::hooks_dir_for(env, process).is_some() || gh_agent_on_path(env)
177}
178
179/// Whether a `gh-agent` command is on the PATH the spawn gets (its own, else this process's).
180fn gh_agent_on_path(env: &HashMap<String, String>) -> bool {
181    let path = env
182        .iter()
183        .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
184        .map(|(_, v)| std::ffi::OsString::from(v))
185        .or_else(|| std::env::var_os("PATH"))
186        .unwrap_or_default();
187    let names: &[&str] = if cfg!(windows) { &["gh-agent.cmd", "gh-agent.exe", "gh-agent.bat"] } else { &["gh-agent"] };
188    std::env::split_paths(&path).any(|dir| names.iter().any(|name| dir.join(name).is_file()))
189}
190
191/// [`apply_gh_guard_for`] under this instance's config dir, plus the publish
192/// guard's `core.hooksPath` ([`crate::backend::publish_guard`]): every path that
193/// spawns an agent process or runs a command for one comes through here.
194pub fn apply_gh_guard(env_vars: &mut HashMap<String, String>) {
195    let other_identity = has_other_github_identity(env_vars);
196    apply_gh_guard_for(env_vars, &guard_config_home(), other_identity);
197    #[cfg(not(any(test, feature = "test-support")))]
198    {
199        crate::backend::publish_guard::apply_publish_guard(env_vars);
200        crate::identity::github_tokens::apply_agent_git(env_vars);
201    }
202}
203
204/// Where guard dirs live. Under test, a per-process temp dir: every test that
205/// builds a spawn env reaches this, and none of them should create or clear
206/// anything in the developer's real config home.
207pub fn guard_config_home() -> PathBuf {
208    #[cfg(any(test, feature = "test-support"))]
209    {
210        std::env::temp_dir().join(format!("agentmux-gh-guard-test-{}", std::process::id()))
211    }
212    #[cfg(not(any(test, feature = "test-support")))]
213    {
214        crate::backend::base::get_mux_config_dir()
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
223        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
224    }
225
226    /// A PtyShell's guard is the agent's own directory, the one its Shell and
227    /// its CLI get, read from the agent's stored env.
228    #[test]
229    fn a_ptyshell_gets_the_agents_own_guard_dir() {
230        let dir = guard_dir_for(&env(&[("AGENTMUX_AGENT_ID", "PtyGuardTest")]));
231        assert_eq!(
232            PathBuf::from(&dir),
233            agent_gh_config_dir(&guard_config_home(), Some("ptyguardtest"))
234        );
235        let mut shell_env = env(&[("AGENTMUX_AGENT_ID", "PtyGuardTest")]);
236        apply_gh_guard(&mut shell_env);
237        assert_eq!(shell_env.get(GH_CONFIG_DIR), Some(&dir), "same as the agent's Shell");
238        assert!(!guard_dir_for(&HashMap::new()).is_empty(), "unattributed is still guarded");
239    }
240
241    #[test]
242    fn sets_a_per_agent_dir_under_config_home() {
243        let home = tempfile::tempdir().unwrap();
244        let mut e = env(&[("AGENTMUX_AGENT_SLUG", "agenty")]);
245        apply_gh_guard_in(&mut e, home.path());
246        let dir = PathBuf::from(&e[GH_CONFIG_DIR]);
247        assert_eq!(dir, home.path().join("gh-agenty"));
248        assert!(dir.is_dir(), "the dir is created so gh has somewhere empty to look");
249    }
250
251    #[test]
252    fn an_agent_with_no_other_github_identity_keeps_the_persons_gh_login() {
253        // The person ran `gh auth login` and has no gh-agent and no connected account: the guard
254        // must neither point gh at an empty folder nor delete a login in it.
255        let home = tempfile::tempdir().unwrap();
256        let dir = agent_gh_config_dir(home.path(), Some("agenty"));
257        std::fs::create_dir_all(&dir).unwrap();
258        std::fs::write(dir.join("hosts.yml"), "github.com:\n  user: someone\n").unwrap();
259        let mut e = env(&[("AGENTMUX_AGENT_SLUG", "agenty")]);
260        apply_gh_guard_for(&mut e, home.path(), false);
261        assert!(!e.contains_key(GH_CONFIG_DIR), "gh finds the person's own login");
262        assert!(dir.join("hosts.yml").exists(), "nothing is cleared for an unguarded agent");
263    }
264
265    #[test]
266    fn an_unguarded_agent_drops_a_guard_dir_an_earlier_start_left_but_not_a_dir_of_the_persons_choosing() {
267        let home = tempfile::tempdir().unwrap();
268        let ours = agent_gh_config_dir(home.path(), Some("agenty")).to_string_lossy().into_owned();
269        let mut e = env(&[("AGENTMUX_AGENT_SLUG", "agenty"), (GH_CONFIG_DIR, &ours)]);
270        apply_gh_guard_for(&mut e, home.path(), false);
271        assert!(!e.contains_key(GH_CONFIG_DIR));
272
273        let mut e = env(&[("AGENTMUX_AGENT_SLUG", "agenty"), (GH_CONFIG_DIR, "/home/person/.config/gh")]);
274        apply_gh_guard_for(&mut e, home.path(), false);
275        assert_eq!(e[GH_CONFIG_DIR], "/home/person/.config/gh");
276    }
277
278    #[test]
279    fn a_guarded_agent_is_set_up_as_before() {
280        let home = tempfile::tempdir().unwrap();
281        let mut e = env(&[("AGENTMUX_AGENT_SLUG", "agenty")]);
282        apply_gh_guard_for(&mut e, home.path(), true);
283        assert_eq!(PathBuf::from(&e[GH_CONFIG_DIR]), home.path().join("gh-agenty"));
284    }
285
286    #[test]
287    fn gh_agent_on_the_path_counts_as_another_identity() {
288        let bin = tempfile::tempdir().unwrap();
289        let name = if cfg!(windows) { "gh-agent.cmd" } else { "gh-agent" };
290        let path = |dirs: &[&Path]| std::env::join_paths(dirs.iter().copied()).unwrap().to_string_lossy().into_owned();
291        let empty = tempfile::tempdir().unwrap();
292        assert!(!gh_agent_on_path(&env(&[("PATH", &path(&[empty.path()]))])));
293        std::fs::write(bin.path().join(name), "").unwrap();
294        assert!(gh_agent_on_path(&env(&[("PATH", &path(&[empty.path(), bin.path()]))])));
295    }
296
297    #[test]
298    fn this_computer_has_gh_agent_when_its_hooks_are_written_or_its_command_is_on_the_path() {
299        let hooks = tempfile::tempdir().unwrap();
300        let bin = tempfile::tempdir().unwrap();
301        let empty = tempfile::tempdir().unwrap();
302        let path = |dir: &Path| std::env::join_paths([dir]).unwrap().to_string_lossy().into_owned();
303        let process = |k: &str| (k == "GH_AGENT_HOOKS_DIR").then(|| hooks.path().to_string_lossy().into_owned());
304        let nothing = env(&[("PATH", &path(empty.path()))]);
305        assert!(!gh_agent_here(&nothing, process), "neither the hooks nor the command");
306        std::fs::write(hooks.path().join("pre-push"), "# gh-agent publish guard: written by gh-agent 0.13.0; do not edit\n").unwrap();
307        assert!(gh_agent_here(&nothing, process), "the hooks gh-agent wrote");
308        std::fs::remove_file(hooks.path().join("pre-push")).unwrap();
309        let name = if cfg!(windows) { "gh-agent.cmd" } else { "gh-agent" };
310        std::fs::write(bin.path().join(name), "").unwrap();
311        assert!(gh_agent_here(&env(&[("PATH", &path(bin.path()))]), process), "the command on the PATH");
312    }
313
314    #[test]
315    fn overrides_a_gh_config_dir_already_in_the_env() {
316        // The hole this closes: a persisted or caller-supplied value pointing
317        // at a real login must not survive into the spawn.
318        let home = tempfile::tempdir().unwrap();
319        let mut e = env(&[("AGENTMUX_AGENT_ID", "AgentY"), (GH_CONFIG_DIR, "/home/human/.config/gh")]);
320        apply_gh_guard_in(&mut e, home.path());
321        assert_eq!(PathBuf::from(&e[GH_CONFIG_DIR]), home.path().join("gh-agenty"));
322    }
323
324    #[test]
325    fn prefers_the_slug_and_falls_back_to_the_agent_id() {
326        let home = tempfile::tempdir().unwrap();
327        let mut e = env(&[("AGENTMUX_AGENT_ID", "Display Name"), ("AGENTMUX_AGENT_SLUG", "korp")]);
328        apply_gh_guard_in(&mut e, home.path());
329        assert!(e[GH_CONFIG_DIR].ends_with("gh-korp"));
330
331        let mut e = env(&[("AGENTMUX_AGENT_ID", "Korp"), ("AGENTMUX_AGENT_SLUG", "  ")]);
332        apply_gh_guard_in(&mut e, home.path());
333        assert!(e[GH_CONFIG_DIR].ends_with("gh-korp"));
334    }
335
336    #[test]
337    fn guards_an_unattributed_spawn_rather_than_skipping_it() {
338        let home = tempfile::tempdir().unwrap();
339        let mut e = HashMap::new();
340        apply_gh_guard_in(&mut e, home.path());
341        assert_eq!(PathBuf::from(&e[GH_CONFIG_DIR]), home.path().join("gh-unattributed"));
342    }
343
344    #[test]
345    fn a_slug_cannot_escape_config_home() {
346        let home = Path::new("/cfg");
347        for bad in ["../../etc", "..", "a/b", "a\\b", "C:\\x", "/abs"] {
348            let dir = agent_gh_config_dir(home, Some(bad));
349            assert_eq!(dir.parent(), Some(home), "{bad:?} -> {}", dir.display());
350            let name = dir.file_name().unwrap().to_string_lossy().into_owned();
351            assert!(name.starts_with("gh-") && !name.contains(['/', '\\', '.']), "{bad:?} -> {name}");
352        }
353    }
354
355    #[test]
356    fn clears_a_login_left_in_the_dir_and_keeps_preferences() {
357        let home = tempfile::tempdir().unwrap();
358        let dir = agent_gh_config_dir(home.path(), Some("agenty"));
359        std::fs::create_dir_all(&dir).unwrap();
360        std::fs::write(dir.join("hosts.yml"), "github.com:\n  user: someone\n").unwrap();
361        std::fs::write(dir.join("config.yml"), "editor: vim\n").unwrap();
362
363        let mut e = env(&[("AGENTMUX_AGENT_SLUG", "agenty")]);
364        apply_gh_guard_in(&mut e, home.path());
365
366        assert!(!dir.join("hosts.yml").exists(), "a login in the guard dir must not survive a spawn");
367        assert!(dir.join("config.yml").exists(), "gh preferences are not a login and are left alone");
368    }
369
370    #[test]
371    fn a_dir_named_hosts_yml_is_refused_not_recursed_into() {
372        let home = tempfile::tempdir().unwrap();
373        let dir = agent_gh_config_dir(home.path(), Some("agenty"));
374        std::fs::create_dir_all(dir.join("hosts.yml")).unwrap();
375        assert!(clear_gh_login(&dir).is_err());
376        // The variable is still set: the spawn is not failed over this.
377        let mut e = env(&[("AGENTMUX_AGENT_SLUG", "agenty")]);
378        apply_gh_guard_in(&mut e, home.path());
379        assert_eq!(PathBuf::from(&e[GH_CONFIG_DIR]), dir);
380    }
381}