Avoid executing PATH helpers before workspace trust (#42324)

## Why

Automatic startup work and `codex doctor` can run before a workspace is
trusted. A repository-controlled `PATH` must not be able to make those flows
execute workspace-provided helpers.

## What changed

- Resolve helpers used by automatic startup from trusted system installation
  directories, and give plugin-sync Git subprocesses a sanitized environment.
- Make terminal detection environment-only and have doctor inspect executable
  locations without running them. Fetch update metadata with the HTTP client
  instead of `curl`.
- Fall back conservatively when trusted terminal helpers are unavailable,
  including for tmux keyboard enhancement flags.

## Testing

Add black-box coverage with hostile workspace `PATH` entries for startup,
interactive tmux startup, support log collection, doctor, and curated plugin
sync. Add unit coverage for trusted executable resolution and bounded update
HTTP responses.

GitOrigin-RevId: 3b8995eb422b60ed53b0386951de59e8f9bfc542
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-09-02 18:34:27 +00:00
1 parent 5e26f7621c
commit 637c3227b3
19 files changed
+975 -906

No files matched your search

+25 -208
View File
@@ -4,7 +4,8 @@
//! configuration, authentication, terminal, state paths, and bounded reachability
//! probes without attempting repair or starting long-lived services. Each check
//! returns a redacted, serializable row so the same data can back the human
//! summary and `--json` support report.
//! summary and `--json` support report. PATH entries are untrusted data: checks
//! may inspect them, but must not execute the programs they select.
//!
//! A failing check should describe the problem and remediation, but it should not
//! mutate user state. That keeps the command safe to run before filing a support
@@ -21,7 +22,6 @@ use std::io::Read;
use std::net::IpAddr;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
@@ -133,10 +133,6 @@ const COLOR_ENV_VARS: &[&str] = &[
const TERMINAL_DIMENSION_ENV_VARS: &[&str] = &["COLUMNS", "LINES"];
const TERMINFO_ENV_VARS: &[&str] = &["TERMINFO", "TERMINFO_DIRS"];
const LOCALE_ENV_VARS: &[&str] = &["LC_ALL", "LC_CTYPE", "LANG"];
#[cfg(windows)]
const NPM_COMMAND: &str = "npm.cmd";
#[cfg(not(windows))]
const NPM_COMMAND: &str = "npm";
const REMOTE_TERMINAL_ENV_VARS: &[&str] = &[
"SSH_TTY",
"SSH_CONNECTION",
@@ -150,13 +146,6 @@ const REMOTE_TERMINAL_ENV_VARS: &[&str] = &[
"DISPLAY",
"WT_SESSION",
];
const TMUX_OPTION_NAMES: &[&str] = &[
"extended-keys",
"xterm-keys",
"allow-passthrough",
"set-clipboard",
"focus-events",
];
const NARROW_TERMINAL_COLUMNS: u16 = 80;
const NARROW_TERMINAL_ROWS: u16 = 24;
@@ -430,7 +419,7 @@ async fn build_report(
),
})
},
async { run_sync_check("updates", progress.clone(), || updates_check(config)) },
run_async_check("updates", progress.clone(), updates_check(config)),
async {
run_sync_check("network", progress.clone(), || network::check(Some(config)))
},
@@ -450,7 +439,9 @@ async fn build_report(
terminal_check(command.no_color)
})
},
run_async_check("git", progress.clone(), git_check(config.cwd.as_path())),
async {
run_sync_check("git", progress.clone(), || git_check(config.cwd.as_path()))
},
async {
run_sync_check("terminal title", progress.clone(), || {
terminal_title_check(config)
@@ -528,7 +519,7 @@ async fn build_report(
terminal_check(command.no_color)
})
},
run_async_check("git", progress.clone(), git_check(&cwd)),
async { run_sync_check("git", progress.clone(), || git_check(&cwd)) },
async { run_sync_check("state", progress.clone(), fallback_state_check) },
run_async_check(
"provider reachability",
@@ -907,41 +898,15 @@ fn installation_check(show_details: bool) -> DoctorCheck {
}
if doctor_managed_by_npm(current_exe.as_deref()) {
match npm_global_root_check() {
NpmRootCheck::Match { package_root } => {
details.push(format!("npm update target: {}", package_root.display()));
}
NpmRootCheck::Mismatch {
running_package_root,
npm_package_root,
} => {
status = CheckStatus::Fail;
summary =
"npm install -g @openai/codex would update a different install".to_string();
remediation = Some(format!(
"Fix PATH or npm prefix so the running package root ({}) matches the npm global package root ({}).",
running_package_root.display(),
npm_package_root.display()
));
details.push(format!(
"running package root: {}",
running_package_root.display()
));
details.push(format!("npm package root: {}", npm_package_root.display()));
}
NpmRootCheck::MissingPackageRoot => {
status = status.max(CheckStatus::Warning);
summary = "npm-managed launch is missing package-root provenance".to_string();
remediation = Some(
"Reinstall or update Codex so the JS shim provides CODEX_MANAGED_PACKAGE_ROOT."
.to_string(),
);
}
NpmRootCheck::NpmUnavailable(error) => {
status = status.max(CheckStatus::Warning);
summary = "npm-managed launch could not inspect npm global root".to_string();
details.push(format!("npm root -g failed: {error}"));
}
details
.push("npm update target: not inspected (PATH helpers are not executed)".to_string());
if env::var_os("CODEX_MANAGED_PACKAGE_ROOT").is_none() {
status = status.max(CheckStatus::Warning);
summary = "npm-managed launch is missing package-root provenance".to_string();
remediation = Some(
"Reinstall or update Codex so the JS shim provides CODEX_MANAGED_PACKAGE_ROOT."
.to_string(),
);
}
}
@@ -1063,62 +1028,6 @@ fn display_optional_path(path: Option<&Path>) -> String {
.unwrap_or_else(|| "none".to_string())
}
#[derive(Debug, PartialEq, Eq)]
enum NpmRootCheck {
Match {
package_root: PathBuf,
},
Mismatch {
running_package_root: PathBuf,
npm_package_root: PathBuf,
},
MissingPackageRoot,
NpmUnavailable(String),
}
fn npm_global_root_check() -> NpmRootCheck {
let Some(running_package_root) = env::var_os("CODEX_MANAGED_PACKAGE_ROOT").map(PathBuf::from)
else {
return NpmRootCheck::MissingPackageRoot;
};
let output = match run_command(NPM_COMMAND, ["root", "-g"]) {
Ok(output) => output,
Err(err) => return NpmRootCheck::NpmUnavailable(err),
};
let Some(npm_root) = output.lines().map(str::trim).find(|line| !line.is_empty()) else {
return NpmRootCheck::NpmUnavailable("empty output from npm root -g".to_string());
};
compare_npm_package_roots(&running_package_root, &PathBuf::from(npm_root))
}
fn compare_npm_package_roots(running_package_root: &Path, npm_root: &Path) -> NpmRootCheck {
let npm_package_root = npm_root.join("@openai").join("codex");
let running = normalize_path_for_compare(running_package_root);
let target = normalize_path_for_compare(&npm_package_root);
if running == target {
NpmRootCheck::Match {
package_root: npm_package_root,
}
} else {
NpmRootCheck::Mismatch {
running_package_root: running_package_root.to_path_buf(),
npm_package_root,
}
}
}
fn normalize_path_for_compare(path: &Path) -> String {
let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let raw = canonical.to_string_lossy().replace('\\', "/");
if cfg!(windows) {
raw.to_ascii_lowercase()
} else {
raw
}
}
fn display_list<T: AsRef<str>>(items: &[T]) -> String {
if items.is_empty() {
"none".to_string()
@@ -1132,39 +1041,16 @@ fn display_list<T: AsRef<str>>(items: &[T]) -> String {
}
fn codex_path_entries() -> Vec<String> {
#[cfg(windows)]
let result = run_command("where", ["codex"]);
#[cfg(not(windows))]
let result = run_command("which", ["-a", "codex"]);
result
.unwrap_or_default()
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(str::to_string)
let Ok(candidates) = which::which_all("codex") else {
return Vec::new();
};
let mut seen = BTreeSet::new();
candidates
.filter(|candidate| seen.insert(candidate.clone()))
.map(|path| path.display().to_string())
.collect()
}
fn run_command<I, S>(program: &str, args: I) -> Result<String, String>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let output = Command::new(program)
.args(args)
.output()
.map_err(|err| err.to_string())?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if stderr.is_empty() {
return Err(format!("exited with status {}", output.status));
}
return Err(stderr);
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
fn config_check(config: &Config) -> DoctorCheck {
let mut details = Vec::new();
details.push(format!("CODEX_HOME: {}", config.codex_home.display()));
@@ -1748,7 +1634,7 @@ impl TerminalCheckInputs {
let terminal_size = crossterm::terminal::size().map_err(|err| err.to_string());
let info = terminal_info();
let tmux_details = if matches!(info.multiplexer, Some(Multiplexer::Tmux { .. })) {
tmux_diagnostic_details()
vec!["tmux options: not inspected (PATH helpers are not executed)".to_string()]
} else {
Vec::new()
};
@@ -2147,50 +2033,6 @@ fn terminal_size_issues(inputs: &TerminalCheckInputs) -> Vec<DoctorIssue> {
issues
}
fn tmux_diagnostic_details() -> Vec<String> {
let mut details = Vec::new();
push_tmux_display_detail(&mut details, "tmux client termtype", "#{client_termtype}");
push_tmux_display_detail(&mut details, "tmux client termname", "#{client_termname}");
for option in TMUX_OPTION_NAMES {
let value = tmux_option_value(option).unwrap_or_else(|| "unavailable".to_string());
details.push(format!("tmux {option}: {value}"));
}
details
}
fn push_tmux_display_detail(details: &mut Vec<String>, label: &str, format: &str) {
if let Some(value) = tmux_display_message(format) {
details.push(format!("{label}: {value}"));
}
}
fn tmux_option_value(option: &str) -> Option<String> {
let output = Command::new("tmux")
.args(["show-options", "-gqv", option])
.output()
.ok()?;
if !output.status.success() {
return None;
}
non_empty_trimmed(String::from_utf8(output.stdout).ok()?)
}
fn tmux_display_message(format: &str) -> Option<String> {
let output = Command::new("tmux")
.args(["display-message", "-p", format])
.output()
.ok()?;
if !output.status.success() {
return None;
}
non_empty_trimmed(String::from_utf8(output.stdout).ok()?)
}
fn non_empty_trimmed(value: String) -> Option<String> {
let value = value.trim().to_string();
if value.is_empty() { None } else { Some(value) }
}
async fn state_check(config: &Config, command: &DoctorCommand) -> DoctorCheck {
let mut details = Vec::new();
path_readiness(&mut details, "CODEX_HOME", &config.codex_home);
@@ -3250,31 +3092,6 @@ mod tests {
);
}
#[test]
fn compare_npm_package_roots_detects_match() {
let running = PathBuf::from("/prefix/lib/node_modules/@openai/codex");
let npm_root = PathBuf::from("/prefix/lib/node_modules");
assert_eq!(
compare_npm_package_roots(&running, &npm_root),
NpmRootCheck::Match {
package_root: npm_root.join("@openai").join("codex")
}
);
}
#[test]
fn compare_npm_package_roots_detects_mismatch() {
let running = PathBuf::from("/old/lib/node_modules/@openai/codex");
let npm_root = PathBuf::from("/new/lib/node_modules");
assert_eq!(
compare_npm_package_roots(&running, &npm_root),
NpmRootCheck::Mismatch {
running_package_root: running,
npm_package_root: npm_root.join("@openai").join("codex"),
}
);
}
#[test]
fn startup_warning_counts_group_known_sources() {
let warnings = vec![
@@ -4366,7 +4183,7 @@ mod tests {
}
#[test]
fn terminal_check_keeps_tmux_probe_failures_non_fatal() {
fn terminal_check_allows_missing_tmux_details() {
let mut inputs = terminal_inputs();
inputs.info.multiplexer = Some(Multiplexer::Tmux { version: None });