1pub const PANE_ENV_KEEP: &[&str] = &[
49 "AGENTMUX_LOCAL_URL",
57 "AGENTMUX_AUTH_KEY",
58 "AGENTMUX_BLOCKID",
60 "AGENTMUX_TABID",
61 "AGENTMUX_VERSION",
64 "AGENTMUX_BUILD",
65 "AGENTMUX_INSTANCE_CHANNEL",
66 "AGENTMUX_LOG_DIR",
67 "AGENTMUX_AGENT_ID",
78 "AGENTMUX_AGENT_SLUG",
79 "AGENTMUX_AGENT_DISPLAY",
80 "AGENTMUX_INSTANCE_SLUG",
81];
82
83const APPIMAGE_ENV: &[&str] = &["APPIMAGE", "APPDIR", "OWD", "ARGV0"];
91
92fn launch_env_edits_for(var: &dyn Fn(&str) -> Option<String>, own_bin: &[std::path::PathBuf]) -> Vec<(String, Option<String>)> {
96 let mut edits = Vec::new();
97 if var("APPIMAGE").is_some_and(|v| !v.is_empty()) {
98 edits.extend(APPIMAGE_ENV.iter().map(|k| (k.to_string(), None)));
99 }
100 if let Some(paths) = var("LD_LIBRARY_PATH") {
101 let own: Vec<String> = own_bin.iter().map(|p| p.to_string_lossy().trim_end_matches('/').to_string()).collect();
102 let kept: Vec<&str> = paths.split(':').filter(|e| !own.iter().any(|o| e.trim_end_matches('/') == o)).collect();
103 if kept.len() != paths.split(':').count() {
104 let kept: Vec<&str> = kept.into_iter().filter(|e| !e.is_empty()).collect();
105 edits.push(("LD_LIBRARY_PATH".to_string(), (!kept.is_empty()).then(|| kept.join(":"))));
106 }
107 }
108 edits
109}
110
111fn launch_env_edits() -> Vec<(String, Option<String>)> {
114 let mut own_bin: Vec<std::path::PathBuf> = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf)).into_iter().collect();
115 for root in ["APPDIR", "AGENTMUX_EXTRACTED_RUN"] {
116 own_bin.extend(std::env::var_os(root).filter(|r| !r.is_empty()).map(|r| std::path::PathBuf::from(r).join("usr/bin")));
117 }
118 launch_env_edits_for(&|k| std::env::var(k).ok(), &own_bin)
119}
120
121pub const NESTING_SENTINEL_KEY: &str = "AGENTMUX";
125
126pub const CONTAINER_CREDENTIAL_ENV: &[&str] = &[
132 "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
133 "AWS_CONTAINER_CREDENTIALS_FULL_URI",
134 "AWS_CONTAINER_AUTHORIZATION_TOKEN",
135 "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
136 "ECS_CONTAINER_METADATA_URI",
137 "ECS_CONTAINER_METADATA_URI_V4",
138 "ECS_AGENT_URI",
139];
140
141pub fn keys_to_strip() -> Vec<String> {
147 std::env::vars_os()
148 .filter_map(|(k, _)| k.into_string().ok())
149 .filter(|k| should_strip(k))
150 .collect()
151}
152
153pub fn should_strip(key: &str) -> bool {
155 if CONTAINER_CREDENTIAL_ENV.contains(&key) {
156 return true;
157 }
158 if !key.starts_with("AGENTMUX") {
159 return false;
160 }
161 if key == NESTING_SENTINEL_KEY {
163 return false;
164 }
165 !PANE_ENV_KEEP.contains(&key)
166}
167
168
169pub fn sanitize_pty_command(c: &mut portable_pty::CommandBuilder) {
183 for key in keys_to_strip() {
184 c.env_remove(&key);
185 }
186 apply_launch_env_pty(c);
187 c.env(NESTING_SENTINEL_KEY, "1");
188 for (key, value) in build_info() {
189 c.env(key, value);
190 }
191}
192
193pub fn build_info() -> &'static [(&'static str, String)] {
204 static INFO: std::sync::OnceLock<Vec<(&'static str, String)>> = std::sync::OnceLock::new();
205 INFO.get_or_init(|| {
206 let version = env!("CARGO_PKG_VERSION").to_string();
207 let build = std::env::current_exe()
208 .ok()
209 .and_then(|exe| exe.parent().and_then(agentmux_common::runtime_mode::portable_build_label))
210 .unwrap_or_else(|| version.clone());
211 let mut info = vec![("AGENTMUX_VERSION", version), ("AGENTMUX_BUILD", build)];
212 if let Some(channel) = std::env::var("AGENTMUX_CHANNEL").ok().filter(|c| !c.trim().is_empty()) {
213 info.push(("AGENTMUX_INSTANCE_CHANNEL", channel));
214 }
215 info
216 })
217}
218
219pub fn sanitize_process_command(cmd: &mut tokio::process::Command) {
226 for key in keys_to_strip() {
227 cmd.env_remove(&key);
228 }
229 apply_launch_env(cmd.as_std_mut());
230 cmd.env(NESTING_SENTINEL_KEY, "1");
231 for (key, value) in build_info() {
232 cmd.env(key, value);
233 }
234}
235
236
237pub fn sanitize_external_command(cmd: &mut tokio::process::Command) {
249 for key in all_agentmux_keys() {
250 cmd.env_remove(&key);
251 }
252 apply_launch_env(cmd.as_std_mut());
253 cmd.env(NESTING_SENTINEL_KEY, "1");
254}
255
256pub fn sanitize_external_pty_command(c: &mut portable_pty::CommandBuilder) {
258 for key in all_agentmux_keys() {
259 c.env_remove(&key);
260 }
261 apply_launch_env_pty(c);
262 c.env(NESTING_SENTINEL_KEY, "1");
263}
264
265fn all_agentmux_keys() -> Vec<String> {
267 std::env::vars_os()
268 .filter_map(|(k, _)| k.into_string().ok())
269 .filter(|k| (k.starts_with("AGENTMUX") && k != NESTING_SENTINEL_KEY) || CONTAINER_CREDENTIAL_ENV.contains(&k.as_str()))
270 .collect()
271}
272
273
274pub fn sanitize_external_std_command(cmd: &mut std::process::Command) {
280 for key in all_agentmux_keys() {
281 cmd.env_remove(&key);
282 }
283 apply_launch_env(cmd);
284 cmd.env(NESTING_SENTINEL_KEY, "1");
285}
286
287fn apply_launch_env(cmd: &mut std::process::Command) {
290 apply_edits(cmd, launch_env_edits());
291}
292
293fn apply_edits(cmd: &mut std::process::Command, edits: Vec<(String, Option<String>)>) {
296 let explicit: Vec<String> =
297 cmd.get_envs().filter(|(_, v)| v.is_some()).map(|(k, _)| k.to_string_lossy().into_owned()).collect();
298 for (key, value) in edits.into_iter().filter(|(k, _)| !explicit.contains(k)) {
299 match value {
300 Some(v) => cmd.env(key, v),
301 None => cmd.env_remove(key),
302 };
303 }
304}
305
306fn apply_launch_env_pty(c: &mut portable_pty::CommandBuilder) {
308 apply_edits_pty(c, launch_env_edits());
309}
310
311fn apply_edits_pty(c: &mut portable_pty::CommandBuilder, edits: Vec<(String, Option<String>)>) {
314 let explicit: Vec<String> = c.iter_extra_env_as_str().map(|(k, _)| k.to_string()).collect();
315 for (key, value) in edits.into_iter().filter(|(k, _)| !explicit.contains(k)) {
316 match value {
317 Some(v) => c.env(key, v),
318 None => c.env_remove(key),
319 };
320 }
321}
322
323pub fn make_cli_cmd(cli_path: &str) -> tokio::process::Command {
339 let mut cmd = agentmux_common::make_cli_cmd(cli_path);
340 sanitize_process_command(&mut cmd);
341 cmd
342}
343
344#[cfg(test)]
345mod spawn_site_coverage {
346 use std::collections::BTreeMap;
376 use std::path::{Path, PathBuf};
377
378 const SPAWN_MARKERS: &[&str] = &["CommandBuilder::new", "process::Command::new", "Command::new("];
380
381 const CLASSES: &[&str] = &["sanitized:", "allowlisted:", "probe:", "test:", "own-exe:", "not a spawn:", "mixed:"];
385
386 const SPAWN_INVENTORY: &[(&str, &str, usize, &str)] = &[
391 ("src/identity/gh_agent_token.rs", "&exe", 3,
392 "sanitized: the host's `gh-agent token` for a container agent's repository, sanitize_external_command (it is told only the agent id); and its `scan-push`, which judges a container's push from data on stdin, sanitize_external_command, run in a temp directory with fixed arguments; and its `pr merge`, which srv runs for a container agent with arguments it builds itself, sanitize_external_command, run in a temp directory"),
393 ("src/identity/aws_broker/mint.rs", "&spec.program", 1,
394 "sanitized: the host program that mints a container agent's AWS session (aws configure export-credentials, or a grant's own recipe), sanitize_external_command, then only an allowlist of the environment is passed on"),
395 ("src/backend/app_version.rs", "\"/usr/bin/plutil\"", 1,
396 "sanitized: macOS only: reads a binary Info.plist's version for Browse (`plutil -extract CFBundleShortVersionString`), sanitize_external_std_command, no input, output parsed then discarded"),
397 ("src/open_cli.rs", "\"open\"", 1,
398 "sanitized: `agentmux-srv open` starts the person's browser (macOS) at the sign-in line, sanitize_external_std_command"),
399 ("src/open_cli.rs", "\"rundll32\"", 1,
400 "sanitized: `agentmux-srv open` starts the person's browser (Windows) at the sign-in line, sanitize_external_std_command"),
401 ("src/agentmux_cli/main.rs", "&srv", 2,
402 "own-exe: `agentmux` runs the server program of its own install (`migrate --prepare`, and the `open` and `logout` sign-in client); the command drops every AGENTMUX_* variable of the shell it runs in before it spawns anything"),
403 ("src/agentmux_cli/main.rs", "srv", 1,
404 "own-exe: `agentmux run` becomes the server program of its own install (exec), with the channel's own folders in its environment; the shell's AGENTMUX_* variables were dropped first"),
405 ("src/agentmux_cli/keyring_probe.rs", "srv", 1,
406 "own-exe: `agentmux setup` on Linux runs `agentmux-srv probe-keychain` of its own install, once on a first run, to learn whether the keychain answers (it stores, reads back and deletes one test entry); no input, a few seconds' wait, output (one word) read then discarded; the shell's AGENTMUX_* variables were dropped first"),
407 ("src/backend/lan/firewall_setup.rs", "helper", 1,
408 "own-exe: Windows only, when the person clicks Set up in the AgentMux window: runs `agentmux.exe --configure-lan-firewall` of its own install (the folder above this program's), which asks Windows for administrator permission itself and adds two port rules; no input, its last stderr line is read and shown, no environment is added"),
409 ("src/agentmuxw.rs", "agentmux", 1,
410 "own-exe: `agentmuxw`, the Windows logon task's program, runs the `agentmux.exe` in its own folder with `run` and a channel name, and nothing else; no environment is added"),
411 ("src/agentmux_cli/main.rs", "exe", 1,
412 "own-exe: `agentmux start` runs `agentmux run` in the background from its own executable; the shell's AGENTMUX_* variables were dropped first"),
413 ("src/agentmux_cli/service.rs", "program", 1,
414 "mixed: `agentmux setup` and `start`/`stop` drive the person's own service manager (systemctl --user, launchctl) at their command, to install, start or stop the server's user service; no agent code runs through it, and nothing of the environment is added"),
415 ("src/agentmux_cli/uninstall.rs", "\"cmd.exe\"", 1,
416 "own-exe: `agentmux uninstall` on Windows starts a hidden `cmd` that waits a few seconds and removes the install folder this command ran from, after the command has ended (a running program's own file cannot be deleted); the path was checked to be the install folder and to hold no character `cmd` acts on, and no input or environment is passed on"),
417 ("src/agentmux_cli/doctor.rs", "\"node\"", 1,
418 "probe: `agentmux doctor` asks the installed Node.js its version (`node --version`) to compare it with the least the new-agent panel needs; no input, output parsed then discarded, no agent code runs through it"),
419 ("src/agentmux_cli/process.rs", "\"ps\"", 1,
420 "probe: names the program of one process id on macOS (`ps -o comm= -p <pid>`), to check it is the server before it is signalled; no input but the id, no environment passed on"),
421 ("src/open_cli.rs", "\"xdg-open\"", 1,
422 "sanitized: `agentmux-srv open` starts the person's browser (Linux) at the sign-in line, sanitize_external_std_command"),
423 ("src/server/files_root.rs", "\"cmd\"", 1,
424 "test: Windows only; makes a junction in a temp folder with mklink /J to prove a link swapped in after a pane opened is refused"),
425 ("src/server/agent_folder_open.rs", "\"cmd\"", 1,
426 "test: Windows only; makes a junction in a temp folder with mklink /J to prove a link opened from a pane is followed to where it leads before it is placed"),
427 ("src/server/agent_media_files.rs", "\"cmd\"", 1,
428 "test: Windows only; makes a junction in a temp folder with mklink /J to prove a link swapped in after a message's file was found is not followed"),
429 ("src/backend/blockcontroller/subprocess/container_spawn.rs", "&argv[0]", 1,
430 "test: Unix only; runs the container turn launcher on the host to prove an exported function reaches the provider"),
431 ("src/agents/runner.rs", "bin", 1,
432 "sanitized: agent CLI subprocess, sanitize_process_command"),
433 ("src/backend/skill_import.rs", "\"git\"", 1,
434 "sanitized: a shallow clone of a skill repository to import, sanitize_external_command (third-party network program, needs no instance identity)"),
435 ("src/backend/attachments/extract.rs", "exe", 1,
436 "sanitized: our own binary re-run as `__extract` to parse one attachment in isolation; it needs no instance identity, so sanitize_external_std_command"),
437 ("src/backend/file_icons/pool.rs", "exe", 1,
438 "sanitized: our own binary re-run as `__file_icons` to ask the system for a file type's icon in isolation; it needs no instance identity, so sanitize_external_std_command"),
439 ("src/backend/attachments/extract.rs", "harness", 1,
440 "test: re-runs the test harness as a child that sleeps, to prove the extraction deadline kills it"),
441 ("src/backend/spawn_env/endpoint.rs", "\"claude\"", 1,
442 "test: builds a command only to read the environment it would get, to prove an emptied login variable is removed from it; never spawned"),
443 ("src/http_client_tests.rs", "std::env::current_exe(", 1,
444 "test: re-runs the test harness as a child whose SSL_CERT_FILE names an empty, a valid or a replaced certificate bundle, because the machine's certificates are read from the environment when a client is built; the child makes requests to a loopback server only"),
445 ("src/backend/storage/muxbus.rs", "std::env::current_exe(", 1,
446 "test: re-runs the test harness as children that save and read one keychain sign-in at once (ignored; real keychain)"),
447 ("src/backend/storage/filestore/tests_checkpoint.rs", "std::env::current_exe(", 1,
448 "test: Unix only; re-runs the test harness as a child that tries the database's write lock, to prove reading the WAL index leaves a transaction's lock in place"),
449 ("src/backend/storage/filestore/tests_tail_slack.rs", "std::env::current_exe(", 1,
450 "test: re-runs the test harness as a child that appends lines in a loop until the test kills it, to prove a transcript reads back whole after a kill mid-append"),
451 ("src/backend/gpu/nvml.rs", "\"cc\"", 1,
452 "test: Linux only; compiles a tiny fake NVIDIA library (a C file written to a temp folder, fixed arguments) so the NVML calls can be exercised without a GPU; skipped where there is no C compiler"),
453 ("src/backend/git_program_settings.rs", "\"git\"", 1,
454 "sanitized: reads the person's own system and global git configuration for their ssh command, signing programs and editors (`git config --show-scope --get-regexp`, outside any repository), sanitize_external_std_command; no input, output parsed then discarded"),
455 ("src/backend/git_program_settings_tests.rs", "tool", 1,
456 "test: runs git on a pseudoterminal in a scratch repository whose own configuration names marker programs, to prove no pager it names runs; no agent code"),
457 ("src/backend/git_program_settings_tests.rs", "program", 1,
458 "test: runs git in a scratch repository whose own configuration names marker programs, with none of the person's configuration, to prove they do not run; loopback addresses only, no agent code"),
459 ("src/backend/memory/dream_model_tests.rs", "program", 1,
460 "test: runs stock programs (`cat` or `findstr` to echo its input; `sleep` or `ping` as a child that never reads it or never ends) to prove the model call gives its prompt and reads its output, and that its one deadline stops a stalled child and its process group; fixed arguments, no agent code"),
461 ("src/backend/transcript/framer_tests.rs", "&exe", 1,
462 "test: re-runs the test harness as writer, framer and reader children on one scratch store (ignored; the multi-process stress)"),
463 ("src/backend/transcript/framer_tests.rs", "\"ping\"", 1,
464 "test: a short-lived process whose environment the framer reads, to prove a srv on another home does not block; no agent code"),
465 ("src/backend/transcript/framer_tests.rs", "\"sleep\"", 1,
466 "test: a short-lived process whose environment the framer reads, to prove a srv on another home does not block; no agent code"),
467 ("src/backend/blockcontroller/app_server.rs", "fake_server_binary(", 1,
468 "test: runs the fixture server built above; lives and dies with the test"),
469 ("src/backend/remote/ssh.rs", "ssh", 1,
470 "probe: `ssh -V` for the client's version (forced askpass), output parsed then discarded"),
471 ("src/backend/remote/host.rs", "&self.ssh_path", 1,
472 "sanitized: a durable SSH pane's ssh (attach, end, helper install: one ssh_command), the same sanitize_process_command"),
473 ("src/backend/blockcontroller/persistent/tests/eager_resume.rs", "\"taskkill\"", 1,
474 "test: the eager-resume harness's Drop force-kills its stub CLI on Windows so a failed assertion cannot leave it running"),
475 ("src/backend/blockcontroller/persistent/tests/eager_resume.rs", "\"kill\"", 1,
476 "test: the same Drop teardown on Unix"),
477 ("src/backend/blockcontroller/persistent/tests/send_input.rs", "\"echo\"", 1,
478 "not a spawn: appears inside a comment explaining why `echo` cannot be spawned directly"),
479 ("src/backend/blockcontroller/shell/spawn_command.rs", "\"/bin/sh\"", 1,
480 "sanitized: Unix fallback shell, covered by the same single sanitize_pty_command"),
481 ("src/backend/blockcontroller/shell/spawn_command.rs", "\"cmd.exe\"", 1,
482 "sanitized: Windows fallback shell, covered by the same single sanitize_pty_command"),
483 ("src/backend/blockcontroller/shell/lifecycle.rs", "\"shell-under-test\"", 1,
484 "not a spawn: global_cmd_env_tests builds a CommandBuilder only to read back the cmd:env applied to it; never spawned"),
485 ("src/backend/blockcontroller/shell/spawn_command.rs", "&program", 1,
486 "sanitized: pane PTY, one choke-point sanitize_pty_command covers all four builders here"),
487 ("src/backend/blockcontroller/shell/spawn_command.rs", "&shell_path", 1,
488 "sanitized: the configured login shell, covered by the same sanitize_pty_command"),
489 ("src/backend/blockcontroller/shell/spawn_command.rs", "\"wsl.exe\"", 1,
490 "sanitized: a WSL pane's wsl.exe, covered by the same sanitize_pty_command"),
491 ("src/backend/shells.rs", "&c.path", 1,
492 "probe: each installed shell's `--version` for Settings' default-shell list, output parsed then discarded"),
493 ("src/backend/blockcontroller/shell/ssh_pane.rs", "ssh_path", 1,
494 "sanitized: an SSH pane's system ssh, built here and sanitized by lifecycle.rs's sanitize_pty_command"),
495 ("src/backend/blockcontroller/shell/container_pane.rs", "\"docker\"", 1,
496 "sanitized: a container agent's drawer shell, `docker exec` on a PTY, sanitize_pty_command here, then only the shell's own identity env and DOCKER_HOST added"),
497 ("src/backend/blockcontroller/shell/tests.rs", "\"sleep\"", 1,
498 "test: disposable `sleep 30` made its own process-group leader, to prove a group-kill reaches an isolated group"),
499 ("src/bootstrap/watchers.rs", "\"sleep\"", 1,
500 "test: disposable `sleep 60` the launcher-watcher test waits on through a pidfd, to prove a signal doesn't end the wait"),
501 ("src/backend/claude_layout.rs", "\"git\"", 1,
502 "test: builds a throwaway repository with a linked worktree in a temp dir, to check the CLI's memory-folder rule"),
503 ("src/backend/container/mounts/credential_mode.rs", "\"sh\"", 1,
504 "test: Unix only; runs the container's credential-tightening script against a temp dir, to prove what it changes and what it leaves"),
505 ("src/backend/container/cli.rs", "\"sh\"", 2,
506 "test: Unix only; runs the container CLI install and check scripts against a stub npm in a temp dir, to prove they are idempotent and write no marker on failure"),
507 ("src/backend/container/cli_release_tests.rs", "\"sh\"", 3,
508 "test: Unix only; runs the container download and uv install scripts against a fake curl in a temp dir, to prove the hash check, the size cap and the marker-last order"),
509 ("src/backend/container/cli_release_tests.rs", "\"tar\"", 2,
510 "test: Unix only; builds throwaway tarballs in a temp dir (one with a `..` member) as the download script tests' fixtures"),
511 ("src/backend/container_task_probe.rs", "\"sh\"", 1,
512 "test: Linux only; runs the probe's script against this test's own pid and a pid no process has, to prove what it prints"),
513 ("src/backend/lsp/supervisor.rs", "&resolved", 1,
514 "sanitized: language server, sanitize_process_command"),
515 ("src/backend/lsp/supervisor.rs", "\"ping\"", 1,
516 "test: Windows only; a disposable `ping -n 120 127.0.0.1` stands for a running language server, to prove the last client to stop ends the process"),
517 ("src/backend/lsp/supervisor.rs", "\"sleep\"", 1,
518 "test: Unix only; a disposable `sleep 120` stands for a running language server, to prove the last client to stop ends the process"),
519 ("src/backend/mcp_probe.rs", "command", 1,
520 "sanitized: MCP server probe, sanitize_process_command"),
521 ("src/backend/process_tracker/windows.rs", "\"cmd\"", 2,
522 "test: a short-lived child placed in a Job Object, to check the below-normal priority limit applies to it and that listing the job reads its parent, path and memory"),
523 ("src/backend/container/keychain_credentials.rs", "\"/usr/bin/security\"", 1,
524 "sanitized: macOS only; the Keychain read and write of a container agent's login, sanitize_external_std_command (the tool needs no instance identity)"),
525 ("src/backend/container/keychain_credentials/tests.rs", "\"/usr/bin/security\"", 5,
526 "test: macOS only; the ignored live tests add and delete their own throwaway entries in the real login keychain"),
527 ("src/identity/secret_store.rs", "\"/usr/bin/security\"", 1,
528 "test: adds a keychain entry that trusts no app, for the macOS needs-consent test (ignored; real keychain)"),
529 ("src/server/keychain_probe.rs", "\"/usr/bin/security\"", 1,
530 "sanitized: macOS only; asks which keychain is the user's default before a Claude sign-in (`security default-keychain -d user`), sanitize_external_command (it keeps HOME, which is what it checks), output parsed then discarded"),
531 ("src/server/app_api/blockstats.rs", "\"ping\"", 1,
532 "test: a disposable child (Windows) registered as a pane's shell, so the stats tooltip test has a Tower task to read"),
533 ("src/server/app_api/blockstats.rs", "\"sleep\"", 1,
534 "test: the same disposable child on Unix"),
535 ("src/backend/process_tracker/registry.rs", "\"cmd\"", 5,
536 "test: disposable children for the job-object tracker (assign, adopt, CPU accounting)"),
537 ("src/backend/process_tracker/registry.rs", "\"sh\"", 3,
538 "test: disposable child for the job-object tracker; two more read their own nice level (the agent-priority tests)"),
539 ("src/backend/process_tracker/registry.rs", "&argv[0]", 1,
540 "test: runs the nice-wrapped PTY argv and reads its nice level"),
541 ("src/backend/process_tracker/registry.rs", "\"ping\"", 1,
542 "test: a disposable child (Windows) put in an agent's or a terminal's tree, for the which-agent's-tree test"),
543 ("src/backend/process_tracker/registry.rs", "\"sleep\"", 1,
544 "test: the same disposable child on Unix"),
545 ("src/server/peer_process.rs", "\"lsof\"", 1,
546 "sanitized: macOS only; asks which process holds the other end of a loopback connection (`lsof -i`), sanitize_external_std_command, no input, output parsed then discarded"),
547 ("src/backend/process_tracker/scan.rs", "\"sh\"", 1,
548 "test: disposable children the scan tracker tests find and kill"),
549 ("src/backend/process_tracker/cgroup_linux.rs", "\"sleep\"", 2,
550 "test: the argv the PTY-wrap test wraps, and a child the listing test describes; never spawned as built"),
551 ("src/backend/process_tracker/roots_file.rs", "\"sleep\"", 1,
552 "test: a stand-in agent CLI the roots-file prune test records and kills"),
553 ("src/backend/process_tracker/cgroup_linux.rs", "&argv[0]", 1,
554 "test: runs the wrapped argv the cgroup tests track and kill"),
555 ("src/backend/process_tracker/cgroup_linux.rs", "\"sh\"", 2,
556 "test: disposable children the cgroup tests track and kill"),
557 ("src/sagas/close_pane.rs", "\"cmd\"", 2,
558 "test: stand-in background dev servers (Stop ends one; a failed Stop keeps one)"),
559 ("src/sagas/close_pane.rs", "\"sh\"", 2,
560 "test: stand-in background dev servers (Stop ends one; a failed Stop keeps one)"),
561 ("src/server/agent_resources.rs", "\"cmd\"", 2,
562 "test: children for the survivor check and the forced tree kill"),
563 ("src/server/agent_resources.rs", "\"sh\"", 2,
564 "test: children for the survivor check and the forced tree kill"),
565 ("src/backend/remote/helper_install.rs", "\"sh\"", 2,
566 "test: runs the install scripts in a real sh against a temp home"),
567 ("src/backend/fs_ops/host_jobs.rs", "\"mkfifo\"", 1,
568 "test: makes a FIFO for the host transfer tests (Linux only)"),
569 ("src/backend/tower/remote.rs", "\"wsl.exe\"", 1,
570 "sanitized: Tower's helper inside a WSL distribution, sanitize_external_command"),
571 ("src/backend/remote/wsl.rs", "\"wsl.exe\"", 1,
572 "probe: `wsl.exe --list --quiet`, output parsed then discarded"),
573 ("src/backend/remote/address.rs", "\"wsl.exe\"", 1,
574 "sanitized: a WSL pane's address (`cat /proc/net/...`), sanitize_external_command"),
575 ("src/backend/remote/address.rs", "binary", 1,
576 "sanitized: an SSH pane's host (`ssh -G`), sanitize_external_command"),
577 ("src/backend/shell_node.rs", "\"cmd\"", 1,
578 "sanitized: persistent shell node, choke-point sanitize_process_command"),
579 ("src/backend/shell_node.rs", "\"sh\"", 1,
580 "sanitized: Unix branch of the same node, one sanitize_process_command covers both"),
581 ("src/backend/shell_node.rs", "program", 1,
582 "sanitized: an agent Shell run elsewhere (wsl.exe for WSL, ssh for SSH), the same sanitize_process_command"),
583 ("src/backend/update/download.rs", "tar_exe(", 2,
584 "sanitized: the system tar unpacks a downloaded Linux release, sanitize_external_command (a Windows release is decoded in srv, update::unpack); the other is the Linux test that builds its tarball"),
585 ("src/backend/tool_store.rs", "\"where\"", 2,
586 "probe: Windows PATH lookup for a tool; output parsed for a path, never executed"),
587 ("src/backend/tool_store.rs", "\"which\"", 2,
588 "probe: Unix PATH lookup for a tool; output parsed for a path, never executed"),
589 ("src/backend/tool_store.rs", "cmd", 1,
590 "sanitized: probe_version runs a third-party binary, strict policy (this PR)"),
591 ("src/crash_monitor.rs", "&exe", 1,
592 "own-exe: re-spawns OUR OWN binary as the crash monitor; it must stay this instance, so inheritance is the requirement here, not the defect"),
593 ("src/crash_monitor.rs", "std::env::current_exe(", 1,
594 "test: re-runs the test harness as a child that hardens itself, to prove its crash dump is still written"),
595 ("src/backend/cli_install.rs", "\"cmd\"", 1,
596 "sanitized: shell wrapper for npm install, sanitize_external_std_command"),
597 ("src/backend/cli_install.rs", "\"npm\"", 1,
598 "sanitized: npm runs arbitrary postinstall scripts, sanitize_external_std_command"),
599 ("src/backend/cli_prune.rs", "\"ps\"", 1,
600 "sanitized: lists running command lines to see which installed CLI is in use, sanitize_external_std_command"),
601 ("src/server/cli_handlers.rs", "\"where\"", 2,
602 "probe: Windows availability check for npm before install; runs nothing else"),
603 ("src/server/cli_handlers.rs", "\"which\"", 2,
604 "probe: Unix availability check for npm before install; runs nothing else"),
605 ("src/backend/fs_ops/git.rs", "\"git\"", 6,
606 "mixed: git_command (Files pane git markers, agents' work facts) is sanitize_external_command'd, and set to fetch nothing and allow no transport; five are this file's own #[cfg(test)] module"),
607 ("src/backend/work_facts/git.rs", "\"git\"", 1,
608 "test: builds a throwaway repository in a temp dir to check the work-facts probe; production git goes through fs_ops::git's run_git"),
609 ("src/backend/fs_ops/platform.rs", "\"explorer.exe\"", 2,
610 "sanitized: Files pane open/reveal (file manager, default app), sanitize_external_std_command in platform::spawn_detached"),
611 ("src/backend/fs_ops/platform.rs", "\"open\"", 2,
612 "sanitized: Files pane open/reveal (file manager, default app), sanitize_external_std_command in platform::spawn_detached"),
613 ("src/backend/fs_ops/platform.rs", "\"xdg-open\"", 3,
614 "sanitized: Files pane open/reveal (file manager, default app), sanitize_external_std_command in platform::spawn_detached"),
615 ("src/backend/fs_ops/platform.rs", "\"dbus-send\"", 1,
616 "sanitized: Linux reveal asks the file manager over D-Bus to select the file, sanitize_external_std_command in platform::succeeds_within"),
617 ("src/backend/fs_ops/platform.rs", "\"agentmux-no-such-program-for-this-test\"", 1,
618 "test: a program that does not exist, to prove a missing program is not a success"),
619 ("src/backend/fs_ops/platform.rs", "\"false\"", 1,
620 "test: exits non-zero, to prove a failing program is not a success"),
621 ("src/backend/fs_ops/platform.rs", "\"sleep\"", 1,
622 "test: runs past the limit, to prove it is stopped and is not a success"),
623 ("src/backend/fs_ops/platform.rs", "\"true\"", 1,
624 "test: exits zero, to prove a succeeding program is a success"),
625 ("src/backend/fs_watch/pool.rs", "\"wsl.exe\"", 2,
626 "test: an ignored test writes and removes a file inside a WSL distro"),
627 ("src/server/streamed_browser/chromium.rs", "&binary", 1,
628 "allowlisted: the streamed Browser pane's Chromium (unix only): it opens pages from the web, so its environment is cleared and only a short named list (chromium.rs ENV_KEEP) is passed, never srv's own"),
629 ("src/server/streamed_browser/screen/session.rs", "program", 1,
630 "allowlisted: the screen-mode Browser pane's Xvfb, window manager and Chrome (unix only): the environment is cleared and only the same short named list as the streamed pane (chromium.rs ENV_KEEP) plus DISPLAY is passed, never srv's own"),
631 ("src/server/editor_handlers/file_io.rs", "\"explorer.exe\"", 1,
632 "sanitized: file manager, strict policy (I7 fix, this PR)"),
633 ("src/server/editor_handlers/file_io.rs", "\"open\"", 1,
634 "sanitized: file manager, strict policy (I7 fix, this PR)"),
635 ("src/server/identity_auth_spawn_steps.rs", "&spawn_program", 1,
636 "sanitized: provider OAuth CLI under a PTY (the resolved npm shim), strict policy"),
637 ("src/server/identity_auth_spawn_steps.rs", "cli_path", 1,
638 "sanitized: provider OAuth CLI, strict policy"),
639 ("src/server/install_task.rs", "if cfg!(windows", 1,
640 "sanitized: installer shell, sanitize_external_command"),
641 ("src/server/shell_handlers.rs", "&shell", 1,
642 "sanitized: /api/v1/shell/create runner (resolved POSIX shell), sanitize_process_command"),
643 ("src/server/system_install_handlers.rs", "\"apt-cache\"", 1,
644 "probe: package-manager availability query, no install"),
645 ("src/server/system_install_handlers.rs", "\"brew\"", 1,
646 "probe: package-manager availability query, no install"),
647 ("src/server/system_install_handlers.rs", "\"winget\"", 1,
648 "probe: package-manager availability query, no install"),
649 ("src/server/system_install_handlers.rs", "&step.program", 1,
650 "sanitized: package-manager install step, sanitize_external_command"),
651 ("src/server/system_install_handlers.rs", "program", 1,
652 "not a spawn: appears inside this module's header comment describing the argv rule"),
653 ("src/server/voice.rs", "&cli", 1,
654 "sanitized: voice CLI, sanitize_process_command"),
655 ("src/test_support.rs", "\"rustc\"", 1,
656 "test: builds the fixture App Server binary once per source hash, shared by the app_server tests"),
657 ("src/util.rs", "\"cmd\"", 3,
658 "mixed: one is open_browser's sanitized Windows branch; two are in this file's own #[cfg(test)] module"),
659 ("src/util.rs", "\"open\"", 1,
660 "sanitized: browser launch, strict policy (I7 fix, this PR)"),
661 ("src/util.rs", "\"xdg-open\"", 1,
662 "sanitized: browser launch, strict policy (I7 fix, this PR)"),
663 ];
664
665 fn rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
666 let Ok(entries) = std::fs::read_dir(dir) else { return };
667 for entry in entries.flatten() {
668 let path = entry.path();
669 if path.is_dir() {
670 rs_files(&path, out);
671 } else if path.extension().is_some_and(|e| e == "rs") {
672 out.push(path);
673 }
674 }
675 }
676
677 fn line_spawns(line: &str) -> bool {
680 for marker in SPAWN_MARKERS {
681 let mut from = 0;
682 while let Some(idx) = line[from..].find(marker) {
683 let at = from + idx;
684 let prev_is_ident = at > 0
685 && line[..at]
686 .chars()
687 .next_back()
688 .is_some_and(|c| c.is_alphanumeric() || c == '_');
689 if !prev_is_ident {
690 return true;
691 }
692 from = at + marker.len();
693 }
694 }
695 false
696 }
697
698 fn program_of(line: &str) -> String {
700 let Some(at) = line.find("new(") else { return "?".to_string() };
701 let rest = &line[at + 4..];
702 let end = rest.find([',', ')']).unwrap_or(rest.len());
703 rest[..end].trim().to_string()
704 }
705
706 fn actual_inventory() -> BTreeMap<(String, String), usize> {
707 let mut files = Vec::new();
708 for root in crate::test_support::server_package_dirs() {
709 let mut own = Vec::new();
710 rs_files(&root.join("src"), &mut own);
711 files.extend(own.into_iter().map(|file| (root.clone(), file)));
712 }
713 assert!(files.len() > 50, "source walk found only {} files — the walk is broken", files.len());
714
715 let mut map: BTreeMap<(String, String), usize> = BTreeMap::new();
716 for (root, file) in &files {
717 let rel = file.strip_prefix(root).unwrap_or(file).to_string_lossy().replace('\\', "/");
718 if rel.ends_with("backend/pane_env.rs") {
721 continue;
722 }
723 let Ok(src) = std::fs::read_to_string(file) else { continue };
724 for line in src.lines() {
725 if line_spawns(line) {
726 *map.entry((rel.clone(), program_of(line))).or_default() += 1;
727 }
728 }
729 }
730 map
731 }
732
733 #[test]
734 fn the_spawn_surface_matches_the_inventory_exactly() {
735 let actual = actual_inventory();
736 let expected: BTreeMap<(String, String), usize> = SPAWN_INVENTORY
737 .iter()
738 .map(|(f, p, c, _)| ((f.to_string(), p.to_string()), *c))
739 .collect();
740
741 let mut problems = Vec::new();
742 for (key, count) in &actual {
743 match expected.get(key) {
744 None => problems.push(format!(
745 "NEW spawn site: {} -> Command::new({}) x{count}",
746 key.0, key.1
747 )),
748 Some(exp) if exp != count => problems.push(format!(
749 "COUNT changed: {} -> Command::new({}): inventory says {exp}, source has {count}",
750 key.0, key.1
751 )),
752 _ => {}
753 }
754 }
755 for key in expected.keys() {
756 if !actual.contains_key(key) {
757 problems.push(format!("STALE entry (no longer in source): {} -> {}", key.0, key.1));
758 }
759 }
760
761 assert!(
762 problems.is_empty(),
763 "I7: srv's process-spawn surface changed.\n {}\n\n\
764 If you added a spawn: apply the right `pane_env::sanitize_*` to it, then add \n\
765 it to SPAWN_INVENTORY with a classification. If you removed one, drop its row. \n\
766 The inventory is pinned deliberately — a new spawn must not be able to hide \n\
767 beside an already-sanitized one (#3365 P1). Background: \n\
768 docs/retro/retro-env-inheritance-instance-isolation-breach-2026-09-17.md",
769 problems.join("\n ")
770 );
771 }
772
773 #[test]
774 fn every_inventory_row_is_classified_and_justified() {
775 let packages = crate::test_support::server_package_dirs();
776 for (file, program, _, reason) in SPAWN_INVENTORY {
777 assert!(
778 CLASSES.iter().any(|c| reason.starts_with(c)),
779 "{file} -> {program}: reason must start with one of {CLASSES:?}, got {reason:?}"
780 );
781 assert!(
782 reason.len() > 30,
783 "{file} -> {program}: needs a real reason, got {reason:?}"
784 );
785 if reason.starts_with("sanitized:") {
789 let src = packages
790 .iter()
791 .find_map(|root| std::fs::read_to_string(root.join(file)).ok())
792 .expect("read inventory file");
793 assert!(
794 SANITIZERS_FOR_AUDIT.iter().any(|s| src.contains(s)),
795 "{file} -> {program} is classified `sanitized:` but the file calls no sanitizer"
796 );
797 }
798 if reason.starts_with("allowlisted:") {
800 let src = packages
801 .iter()
802 .find_map(|root| std::fs::read_to_string(root.join(file)).ok())
803 .expect("read inventory file");
804 assert!(
805 src.contains(".env_clear()"),
806 "{file} -> {program} is classified `allowlisted:` but the file does not clear the environment"
807 );
808 }
809 }
810 }
811
812 const SANITIZERS_FOR_AUDIT: &[&str] = &[
813 "sanitize_pty_command",
814 "sanitize_process_command",
815 "sanitize_external_command",
816 "sanitize_external_pty_command",
817 "sanitize_external_std_command",
818 ];
819}
820
821#[cfg(test)]
822mod tests {
823 use super::*;
824
825 fn edits(env: &[(&str, &str)], own: &[&str]) -> Vec<(String, Option<String>)> {
826 let own: Vec<std::path::PathBuf> = own.iter().map(std::path::PathBuf::from).collect();
827 launch_env_edits_for(&|k| env.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()), &own)
828 }
829
830 #[test]
831 fn a_pane_loses_the_appimages_own_settings_and_keeps_the_users_library_path() {
832 let own = ["/home/u/.local/share/agentmux/extracted/0.59.30/usr/bin"];
833 let none = |k: &str| (k.to_string(), None);
834 let e = edits(
836 &[
837 ("APPIMAGE", "/home/u/AgentMux.AppImage"),
838 ("LD_LIBRARY_PATH", "/home/u/.local/share/agentmux/extracted/0.59.30/usr/bin:/opt/cuda/lib64:/usr/local/lib"),
839 ],
840 &own,
841 );
842 for k in ["APPIMAGE", "APPDIR", "OWD", "ARGV0"] {
843 assert!(e.contains(&none(k)), "{k}");
844 }
845 assert!(e.contains(&("LD_LIBRARY_PATH".to_string(), Some("/opt/cuda/lib64:/usr/local/lib".to_string()))), "{e:?}");
846 let e = edits(&[("LD_LIBRARY_PATH", "/home/u/.local/share/agentmux/extracted/0.59.30/usr/bin/")], &own);
848 assert_eq!(e, vec![("LD_LIBRARY_PATH".to_string(), None)]);
849 let e = edits(&[("LD_LIBRARY_PATH", "/opt/AgentMux/usr/bin:/lib")], &["/opt/AgentMux/usr/bin"]);
851 assert_eq!(e, vec![("LD_LIBRARY_PATH".to_string(), Some("/lib".to_string()))]);
852 }
853
854 #[test]
855 fn what_a_pane_sets_itself_is_kept_and_only_what_it_inherits_is_edited() {
856 let edits = vec![
857 ("LD_LIBRARY_PATH".to_string(), None),
858 ("APPIMAGE".to_string(), None),
859 ("OWD".to_string(), Some("rewritten".to_string())),
860 ];
861 let mut pty = portable_pty::CommandBuilder::new("sh");
863 pty.env("LD_LIBRARY_PATH", "/opt/cuda/lib64");
864 apply_edits_pty(&mut pty, edits.clone());
865 assert_eq!(pty.get_env("LD_LIBRARY_PATH").and_then(|v| v.to_str()), Some("/opt/cuda/lib64"));
866 assert_eq!(pty.get_env("APPIMAGE"), None);
867 assert_eq!(pty.get_env("OWD").and_then(|v| v.to_str()), Some("rewritten"));
868 let mut std_cmd = std::process::Command::new("sh");
870 std_cmd.env("LD_LIBRARY_PATH", "/opt/cuda/lib64").env("APPIMAGE", "/set/by/the/pane");
871 apply_edits(&mut std_cmd, edits);
872 let envs: std::collections::HashMap<_, _> =
873 std_cmd.get_envs().map(|(k, v)| (k.to_string_lossy().into_owned(), v.map(|v| v.to_string_lossy().into_owned()))).collect();
874 assert_eq!(envs["LD_LIBRARY_PATH"].as_deref(), Some("/opt/cuda/lib64"));
875 assert_eq!(envs["APPIMAGE"].as_deref(), Some("/set/by/the/pane"), "a pane that sets APPIMAGE itself keeps it");
876 assert_eq!(envs["OWD"].as_deref(), Some("rewritten"));
877 }
878
879 #[test]
880 fn nothing_is_touched_when_the_environment_has_none_of_it() {
881 assert!(edits(&[], &["/opt/AgentMux/usr/bin"]).is_empty());
882 assert!(edits(&[("LD_LIBRARY_PATH", "/opt/cuda/lib64")], &["/opt/AgentMux/usr/bin"]).is_empty());
883 assert!(edits(&[("ARGV0", "busybox"), ("OWD", "/x")], &[]).is_empty());
885 assert!(edits(&[("APPIMAGE", "")], &[]).is_empty());
886 }
887
888 #[test]
891 fn the_identity_vars_that_caused_the_breach_are_stripped() {
892 for key in [
893 "AGENTMUX_CHANNEL", "AGENTMUX_DATA_DIR", "AGENTMUX_DATA_HOME", "AGENTMUX_EXTRACTED_RUN", "AGENTMUX_CONFIG_DIR",
898 "AGENTMUX_CONFIG_HOME",
899 "AGENTMUX_CEF_CACHE_DIR",
900 "AGENTMUX_INSTANCE_DIR",
901 "AGENTMUX_INSTANCE_RUNTIME_DIR",
902 "AGENTMUX_AGENTS_DIR",
903 "AGENTMUX_RUNTIME_MODE",
904 "AGENTMUX_CLONE_ID",
905 "AGENTMUX_APP_PATH",
906 "AGENTMUX_SRV_PIPE_PATH",
907 "AGENTMUX_SPLASH_READY_FILE",
908 "AGENTMUX_HOME_OVERRIDE",
909 ] {
910 assert!(should_strip(key), "{key} must not be inheritable by a pane");
911 }
912 }
913
914 #[test]
915 fn the_helper_keep_set_survives() {
916 for key in PANE_ENV_KEEP {
917 assert!(!should_strip(key), "{key} is required by an in-pane helper");
918 }
919 }
920
921 #[test]
925 fn an_unknown_agentmux_var_is_stripped_by_default() {
926 assert!(should_strip("AGENTMUX_SOME_FUTURE_IDENTITY_VAR"));
927 }
928
929 #[test]
930 fn non_agentmux_vars_are_left_alone() {
931 for key in ["PATH", "HOME", "TERM", "SSH_AUTH_SOCK", "LANG", "SystemRoot", "AGENT_ID"] {
932 assert!(!should_strip(key), "{key} is not ours to strip");
933 }
934 }
935
936 #[test]
939 fn the_nesting_sentinel_is_never_stripped() {
940 assert!(!should_strip(NESTING_SENTINEL_KEY));
941 }
942
943 #[test]
947 fn the_external_policy_strips_even_the_helper_keep_set() {
948 std::env::set_var("AGENTMUX_LOCAL_URL", "http://127.0.0.1:1");
949 let stripped = all_agentmux_keys();
950 assert!(stripped.iter().any(|k| k == "AGENTMUX_LOCAL_URL"),
951 "external processes must not receive the instance API endpoint");
952 assert!(!stripped.iter().any(|k| k == NESTING_SENTINEL_KEY),
953 "the sentinel carries no identity and must survive");
954 std::env::remove_var("AGENTMUX_LOCAL_URL");
955 }
956
957 #[test]
959 fn a_pane_is_told_which_build_it_runs_in() {
960 let mut cmd = tokio::process::Command::new("agent");
961 sanitize_process_command(&mut cmd);
962 let envs: std::collections::BTreeMap<String, String> = cmd
963 .as_std()
964 .get_envs()
965 .filter_map(|(k, v)| Some((k.to_str()?.to_string(), v?.to_str()?.to_string())))
966 .collect();
967 let version = env!("CARGO_PKG_VERSION");
968 assert_eq!(envs["AGENTMUX_VERSION"], version, "the plain version: log pointer files are named by it");
969 assert!(envs["AGENTMUX_BUILD"].starts_with(version));
970 assert!(!envs.contains_key("AGENTMUX_CHANNEL"), "the data channel itself still never reaches a pane");
971 }
972
973 #[test]
975 fn a_containers_credential_variables_are_stripped_from_panes_and_external_programs() {
976 for key in CONTAINER_CREDENTIAL_ENV {
977 assert!(should_strip(key), "{key} is stripped from a pane");
978 std::env::set_var(key, "/v2/credentials/test-only");
979 }
980 assert!(keys_to_strip().iter().any(|k| k == "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"));
981 let external = all_agentmux_keys();
982 for key in CONTAINER_CREDENTIAL_ENV {
983 assert!(external.iter().any(|k| k == key), "{key} is stripped from an external program");
984 }
985 let mut cmd = std::process::Command::new("noop");
986 for key in CONTAINER_CREDENTIAL_ENV {
987 cmd.env(key, "inherited");
988 }
989 sanitize_external_std_command(&mut cmd);
990 for key in CONTAINER_CREDENTIAL_ENV {
991 assert_eq!(cmd.get_envs().find(|(k, _)| *k == std::ffi::OsStr::new(key)).map(|(_, v)| v), Some(None), "{key} is removed from the command");
992 }
993 for key in CONTAINER_CREDENTIAL_ENV {
994 std::env::remove_var(key);
995 }
996 }
997
998 #[test]
999 fn keys_to_strip_reads_the_live_environment() {
1000 std::env::set_var("AGENTMUX_TEST_ONLY_LEAK", "1");
1001 assert!(keys_to_strip().iter().any(|k| k == "AGENTMUX_TEST_ONLY_LEAK"));
1002 std::env::remove_var("AGENTMUX_TEST_ONLY_LEAK");
1003 }
1004}