agentmux_srv_core/backend/
gh_guard.rs1use std::collections::HashMap;
31use std::path::{Path, PathBuf};
32
33pub const GH_CONFIG_DIR: &str = "GH_CONFIG_DIR";
34
35pub const META_KEY_PTYSHELL_GH_CONFIG_DIR: &str = "ptyshell:ghconfigdir";
40
41pub fn guard_dir_for(agent_env: &HashMap<String, String>) -> String {
46 guard_dir_for_target(agent_env, false)
47}
48
49pub 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
62fn 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
70const GH_HOSTS_FILE: &str = "hosts.yml";
73
74const UNATTRIBUTED: &str = "unattributed";
77
78pub 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
95pub 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 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
117pub 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
137pub 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
148pub fn has_other_github_identity(env: &HashMap<String, String>) -> bool {
153 #[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
167pub fn gh_agent_on_this_computer() -> bool {
171 gh_agent_here(&HashMap::new(), |k| std::env::var(k).ok())
172}
173
174fn 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
179fn 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
191pub 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
204pub 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 #[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 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(¬hing, 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(¬hing, 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 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 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}