Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

60
codex-rs/cli/BUILD.bazel Normal file
View File

@@ -0,0 +1,60 @@
load("@crates//:data.bzl", "DEP_DATA")
load("@crates//:defs.bzl", "all_crate_deps")
load("@rules_rust//rust:defs.bzl", "rust_test")
load("//:defs.bzl", "MACOS_WEBRTC_RUSTC_LINK_FLAGS", "codex_rust_crate")
load("//bazel/platforms:release_binaries.bzl", "multiplatform_binaries")
load("//bazel/rules:e2e_benchmark.bzl", "codex_e2e_benchmark")
load("//bazel/rules:runtime_package.bzl", "release_binary")
codex_rust_crate(
name = "cli",
binaries_with_build_commit = ["codex"],
crate_name = "codex_cli",
extra_binaries = [
"//codex-rs/bwrap:bwrap",
],
rustc_flags_extra = MACOS_WEBRTC_RUSTC_LINK_FLAGS,
test_data_extra = glob(["src/**/snapshots/**"]),
)
# Real installation copies a full debug package. Run after other Bazel tests
# on the CI runner so remote executors do not amplify shared-disk writeback.
rust_test(
name = "cli-app_server_daemon_package-test",
timeout = "long",
srcs = [
"tests/app_server_daemon/package.rs",
"tests/app_server_daemon/support.rs",
],
args = ["--test-threads=1"],
crate_name = "app_server_daemon_package",
crate_root = "tests/app_server_daemon/package.rs",
data = [":codex"],
env = {"CARGO_BIN_EXE_codex": "$(rlocationpath :codex)"},
rustc_env = {"BAZEL_PACKAGE": "codex-rs/cli"},
rustc_flags = MACOS_WEBRTC_RUSTC_LINK_FLAGS,
tags = ["exclusive"],
target_compatible_with = select({
"@platforms//os:linux": [],
"@platforms//os:macos": [],
"//conditions:default": ["@platforms//:incompatible"],
}),
version = DEP_DATA["codex-rs/cli"]["version"],
deps = all_crate_deps(
normal = True,
normal_dev = True,
),
)
release_binary(
binary = ":codex",
)
multiplatform_binaries(
name = "codex",
)
codex_e2e_benchmark(
name = "codex-help",
binaries = [":codex"],
)

151
codex-rs/cli/Cargo.toml Normal file
View File

@@ -0,0 +1,151 @@
[package]
name = "codex-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
build = "build.rs"
default-run = "codex"
[[bin]]
name = "codex"
path = "src/main.rs"
[[bin]]
name = "logs_client"
path = "src/bin/logs_client.rs"
[[test]]
name = "app_server_daemon_package"
path = "tests/app_server_daemon/package.rs"
[lib]
name = "codex_cli"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
codex-utils-process = { workspace = true }
anyhow = { workspace = true }
chrono = { workspace = true }
clap = { workspace = true, features = ["derive", "env"] }
clap_complete = { workspace = true }
codex-app-server = { workspace = true }
codex-app-server-daemon = { workspace = true }
codex-app-server-protocol = { workspace = true }
codex-app-server-test-client = { workspace = true }
codex-arg0 = { workspace = true }
codex-build-info = { workspace = true }
codex-api = { workspace = true }
codex-chatgpt = { workspace = true }
codex-cloud-config = { workspace = true }
codex-cloud-tasks = { path = "../cloud-tasks" }
codex-utils-cli = { workspace = true }
codex-config = { workspace = true }
codex-core = { workspace = true }
codex-core-plugins = { workspace = true }
codex-history = { workspace = true }
codex-home = { workspace = true }
codex-http-client = { workspace = true }
codex-exec = { workspace = true }
codex-exec-server = { workspace = true }
codex-exec-server-cli = { workspace = true }
codex-execpolicy = { workspace = true }
codex-extension-api = { workspace = true }
codex-features = { workspace = true }
codex-multi-env-copy-file = { workspace = true }
codex-git-attribution = { workspace = true }
codex-git-utils = { workspace = true }
codex-install-context = { workspace = true }
codex-login = { workspace = true }
codex-memories-write = { workspace = true }
codex-mcp = { workspace = true }
codex-model-provider = { workspace = true }
codex-models-manager = { workspace = true }
codex-plugin = { workspace = true }
codex-protocol = { workspace = true }
codex-responses-api-proxy = { workspace = true }
codex-tcp-tunnel = { workspace = true }
codex-rmcp-client = { workspace = true }
codex-rollout = { workspace = true }
codex-rollout-trace = { workspace = true }
codex-sandboxing = { workspace = true }
codex-skills-extension = { workspace = true }
codex-state = { workspace = true }
codex-stdio-to-uds = { workspace = true }
codex-terminal-detection = { workspace = true }
codex-thread-store = { workspace = true }
codex-tui = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-path = { workspace = true }
codex-utils-path-uri = { workspace = true }
codex-utils-redacted-string = { workspace = true }
codex-websocket-auth = { workspace = true }
crossterm = { workspace = true, features = ["event-stream"] }
futures = { workspace = true }
http = { workspace = true }
libc = { workspace = true }
os_info = { workspace = true }
owo-colors = { workspace = true }
regex-lite = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sqlx = { workspace = true }
supports-color = { workspace = true }
sys-locale = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = [
"io-std",
"macros",
"net",
"process",
"rt-multi-thread",
"signal",
"time",
] }
toml = { workspace = true }
tracing = { workspace = true }
tracing-appender = { workspace = true }
tracing-subscriber = { workspace = true }
unicode-segmentation = { workspace = true }
url = { workspace = true }
which = { workspace = true }
[target.'cfg(all(target_os = "linux", target_env = "musl", any(target_arch = "x86_64", target_arch = "aarch64")))'.dependencies]
tikv-jemallocator = { workspace = true }
[target.'cfg(target_os = "windows")'.dependencies]
codex_windows_sandbox = { package = "codex-windows-sandbox", path = "../windows-sandbox-rs" }
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Storage_Packaging_Appx",
"Win32_System_Console",
"Win32_System_Threading",
] }
[dev-dependencies]
app_test_support = { workspace = true }
assert_cmd = { workspace = true }
assert_matches = { workspace = true }
codex-app-server-client = { workspace = true }
codex-utils-cargo-bin = { workspace = true }
codex-utils-pty = { workspace = true }
core_test_support = { workspace = true }
flate2 = { workspace = true }
insta = { workspace = true }
jsonwebtoken = { workspace = true }
predicates = { workspace = true }
pretty_assertions = { workspace = true }
sha2 = { workspace = true }
tar = { workspace = true }
tokio-tungstenite = { workspace = true }
vt100 = { workspace = true }
wiremock = { workspace = true }
zstd = { workspace = true }
[package.metadata.cargo-shear]
# These Rust sources are intentionally Bazel-only macrobenchmarks rather than
# Cargo targets.
ignored-paths = ["e2e_benches/*.rs"]

5
codex-rs/cli/build.rs Normal file
View File

@@ -0,0 +1,5 @@
fn main() {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
println!("cargo:rustc-link-arg=-ObjC");
}
}

View File

@@ -0,0 +1,26 @@
#![allow(clippy::expect_used)]
use std::process::Command;
use divan::Bencher;
fn main() {
divan::main();
}
/// Exercises the Bazel-backed end-to-end benchmark path with a cheap,
/// deterministic Codex invocation. Richer scenarios can add separate
/// benchmark binaries without making the shared harness depend on them.
#[divan::bench(sample_count = 20, sample_size = 1)]
fn codex_help(bencher: Bencher) {
let codex = codex_utils_cargo_bin::cargo_bin("codex")
.expect("codex binary should be available through Bazel runfiles");
bencher.bench_local(move || {
let output = Command::new(&codex)
.arg("--help")
.output()
.expect("codex --help should run");
assert!(output.status.success(), "codex --help should succeed");
});
}

View File

@@ -0,0 +1,25 @@
use clap::Parser;
use std::path::PathBuf;
#[derive(Debug, Parser)]
pub struct AppCommand {
/// Workspace path to open in the Desktop app.
#[arg(value_name = "PATH", default_value = ".")]
pub path: PathBuf,
/// Override the app installer download URL (advanced).
#[arg(long = "download-url")]
pub download_url_override: Option<String>,
}
pub async fn run_app(cmd: AppCommand) -> anyhow::Result<()> {
let workspace = std::fs::canonicalize(&cmd.path).unwrap_or(cmd.path);
#[cfg(target_os = "macos")]
{
crate::desktop_app::run_app_open_or_install(workspace, cmd.download_url_override).await
}
#[cfg(target_os = "windows")]
{
crate::desktop_app::run_app_open_or_install(workspace, cmd.download_url_override).await
}
}

View File

@@ -0,0 +1,468 @@
use std::path::PathBuf;
use std::time::Duration;
use anyhow::Context;
use chrono::DateTime;
use clap::Parser;
use clap::ValueEnum;
use codex_core::config::ConfigBuilder;
use codex_state::LogQuery;
use codex_state::LogRow;
use codex_state::SqliteConfig;
use codex_state::StateRuntime;
use codex_utils_absolute_path::AbsolutePathBuf;
use owo_colors::OwoColorize;
#[derive(Debug, Parser)]
#[command(name = "codex-state-logs")]
#[command(about = "Tail Codex logs from the dedicated logs SQLite DB with simple filters")]
struct Args {
/// Path to CODEX_HOME. Defaults to $CODEX_HOME or ~/.codex.
#[arg(long, env = "CODEX_HOME")]
codex_home: Option<PathBuf>,
/// Direct path to the logs SQLite database. Overrides --codex-home.
#[arg(long)]
db: Option<PathBuf>,
/// Minimum log level to include.
#[arg(long, value_enum, ignore_case = true)]
level: Option<LogLevelThreshold>,
/// Start timestamp (RFC3339 or unix seconds).
#[arg(long, value_name = "RFC3339|UNIX")]
from: Option<String>,
/// End timestamp (RFC3339 or unix seconds).
#[arg(long, value_name = "RFC3339|UNIX")]
to: Option<String>,
/// Substring match on module_path. Repeat to include multiple substrings.
#[arg(long = "module")]
module: Vec<String>,
/// Substring match on file path. Repeat to include multiple substrings.
#[arg(long = "file")]
file: Vec<String>,
/// Match one or more thread ids. Repeat to include multiple threads.
#[arg(long = "thread-id")]
thread_id: Vec<String>,
/// Substring match against the rendered log body.
#[arg(long)]
search: Option<String>,
/// Include logs that do not have a thread id.
#[arg(long)]
threadless: bool,
/// Number of matching rows to show before tailing.
#[arg(long, default_value_t = 200)]
backfill: usize,
/// Poll interval in milliseconds.
#[arg(long, default_value_t = 500)]
poll_ms: u64,
/// Show compact output with only time, level, and rendered log body.
#[arg(long)]
compact: bool,
}
#[derive(Debug, Clone)]
struct LogFilter {
levels_upper: Vec<String>,
from_ts: Option<i64>,
to_ts: Option<i64>,
module_like: Vec<String>,
file_like: Vec<String>,
thread_ids: Vec<String>,
search: Option<String>,
include_threadless: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum LogLevelThreshold {
Trace,
Debug,
Info,
Warn,
Error,
}
impl LogLevelThreshold {
fn levels_upper(self) -> Vec<String> {
let levels = match self {
LogLevelThreshold::Trace => &["TRACE", "DEBUG", "INFO", "WARN", "ERROR"][..],
LogLevelThreshold::Debug => &["DEBUG", "INFO", "WARN", "ERROR"],
LogLevelThreshold::Info => &["INFO", "WARN", "ERROR"],
LogLevelThreshold::Warn => &["WARN", "ERROR"],
LogLevelThreshold::Error => &["ERROR"],
};
levels.iter().map(ToString::to_string).collect()
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = Args::parse();
let sqlite = resolve_sqlite_config(&args).await?;
let filter = build_filter(&args)?;
let runtime = StateRuntime::init(sqlite, "logs-client".to_string()).await?;
let mut last_id =
print_backfill(runtime.as_ref(), &filter, args.backfill, args.compact).await?;
if last_id == 0 {
last_id = fetch_max_id(runtime.as_ref(), &filter).await?;
}
let poll_interval = Duration::from_millis(args.poll_ms);
loop {
let rows = fetch_new_rows(runtime.as_ref(), &filter, last_id).await?;
for row in rows {
last_id = last_id.max(row.id);
println!("{}", format_row(&row, args.compact));
}
tokio::time::sleep(poll_interval).await;
}
}
async fn resolve_sqlite_config(args: &Args) -> anyhow::Result<SqliteConfig> {
if let Some(db_path) = args.db.as_ref() {
let sqlite_home = db_path
.parent()
.map(ToOwned::to_owned)
.unwrap_or_else(|| PathBuf::from("."));
return Ok(SqliteConfig::from_sqlite_home_with_nfs_enforcement(
AbsolutePathBuf::relative_to_current_dir(sqlite_home)?,
/*enforce_delete_on_nfs*/ false,
));
}
let mut config_builder = ConfigBuilder::default();
if let Some(codex_home) = args.codex_home.as_ref() {
config_builder = config_builder.codex_home(codex_home.clone());
}
let config = config_builder.build().await?;
Ok(config.sqlite_config().clone())
}
fn build_filter(args: &Args) -> anyhow::Result<LogFilter> {
let from_ts = args
.from
.as_deref()
.map(parse_timestamp)
.transpose()
.context("failed to parse --from")?;
let to_ts = args
.to
.as_deref()
.map(parse_timestamp)
.transpose()
.context("failed to parse --to")?;
let levels_upper = args
.level
.map_or_else(Vec::new, LogLevelThreshold::levels_upper);
let module_like = args
.module
.iter()
.filter(|module| !module.is_empty())
.cloned()
.collect::<Vec<_>>();
let file_like = args
.file
.iter()
.filter(|file| !file.is_empty())
.cloned()
.collect::<Vec<_>>();
let thread_ids = args
.thread_id
.iter()
.filter(|thread_id| !thread_id.is_empty())
.cloned()
.collect::<Vec<_>>();
Ok(LogFilter {
levels_upper,
from_ts,
to_ts,
module_like,
file_like,
thread_ids,
search: args.search.clone(),
include_threadless: args.threadless,
})
}
fn parse_timestamp(value: &str) -> anyhow::Result<i64> {
if let Ok(secs) = value.parse::<i64>() {
return Ok(secs);
}
let dt = DateTime::parse_from_rfc3339(value)
.with_context(|| format!("expected RFC3339 or unix seconds, got {value}"))?;
Ok(dt.timestamp())
}
async fn print_backfill(
runtime: &StateRuntime,
filter: &LogFilter,
backfill: usize,
compact: bool,
) -> anyhow::Result<i64> {
if backfill == 0 {
return Ok(0);
}
let mut rows = fetch_backfill(runtime, filter, backfill).await?;
rows.reverse();
let mut last_id = 0;
for row in rows {
last_id = last_id.max(row.id);
println!("{}", format_row(&row, compact));
}
Ok(last_id)
}
async fn fetch_backfill(
runtime: &StateRuntime,
filter: &LogFilter,
backfill: usize,
) -> anyhow::Result<Vec<LogRow>> {
let query = to_log_query(
filter,
Some(backfill),
/*after_id*/ None,
/*descending*/ true,
);
runtime
.query_logs(&query)
.await
.context("failed to fetch backfill logs")
}
async fn fetch_new_rows(
runtime: &StateRuntime,
filter: &LogFilter,
last_id: i64,
) -> anyhow::Result<Vec<LogRow>> {
let query = to_log_query(
filter,
/*limit*/ None,
Some(last_id),
/*descending*/ false,
);
runtime
.query_logs(&query)
.await
.context("failed to fetch new logs")
}
async fn fetch_max_id(runtime: &StateRuntime, filter: &LogFilter) -> anyhow::Result<i64> {
let query = to_log_query(
filter, /*limit*/ None, /*after_id*/ None, /*descending*/ false,
);
runtime
.max_log_id(&query)
.await
.context("failed to fetch max log id")
}
fn to_log_query(
filter: &LogFilter,
limit: Option<usize>,
after_id: Option<i64>,
descending: bool,
) -> LogQuery {
LogQuery {
levels_upper: filter.levels_upper.clone(),
from_ts: filter.from_ts,
to_ts: filter.to_ts,
module_like: filter.module_like.clone(),
file_like: filter.file_like.clone(),
thread_ids: filter.thread_ids.clone(),
search: filter.search.clone(),
include_threadless: filter.include_threadless,
after_id,
limit,
descending,
}
}
fn format_row(row: &LogRow, compact: bool) -> String {
let timestamp = formatter::ts(row.ts, row.ts_nanos, compact);
let level = row.level.as_str();
let target = row.target.as_str();
let message = row.message.as_deref().unwrap_or("");
let level_colored = formatter::level(level);
let timestamp_colored = timestamp.dimmed().to_string();
let thread_id = row.thread_id.as_deref().unwrap_or("-");
let thread_id_colored = thread_id.blue().dimmed().to_string();
let target_colored = target.dimmed().to_string();
let message_colored = heuristic_formatting(message);
if compact {
format!("{timestamp_colored} {level_colored} {message_colored}")
} else {
format!(
"{timestamp_colored} {level_colored} [{thread_id_colored}] {target_colored} - {message_colored}"
)
}
}
fn heuristic_formatting(message: &str) -> String {
if matcher::apply_patch(message) {
formatter::apply_patch(message)
} else {
message.bold().to_string()
}
}
mod matcher {
pub(super) fn apply_patch(message: &str) -> bool {
message.contains("ToolCall: apply_patch")
}
}
mod formatter {
use chrono::DateTime;
use chrono::SecondsFormat;
use chrono::Utc;
use owo_colors::OwoColorize;
pub(super) fn apply_patch(message: &str) -> String {
message
.lines()
.map(|line| {
if line.starts_with('+') {
line.green().bold().to_string()
} else if line.starts_with('-') {
line.red().bold().to_string()
} else {
line.bold().to_string()
}
})
.collect::<Vec<_>>()
.join("\n")
}
pub(super) fn ts(ts: i64, ts_nanos: i64, compact: bool) -> String {
let nanos = u32::try_from(ts_nanos).unwrap_or(0);
match DateTime::<Utc>::from_timestamp(ts, nanos) {
Some(dt) if compact => dt.format("%H:%M:%S").to_string(),
Some(dt) => dt.to_rfc3339_opts(SecondsFormat::Millis, true),
None => format!("{ts}.{ts_nanos:09}Z"),
}
}
pub(super) fn level(level: &str) -> String {
let padded = format!("{level:<5}");
if level.eq_ignore_ascii_case("error") {
return padded.red().bold().to_string();
}
if level.eq_ignore_ascii_case("warn") {
return padded.yellow().bold().to_string();
}
if level.eq_ignore_ascii_case("info") {
return padded.green().bold().to_string();
}
if level.eq_ignore_ascii_case("debug") {
return padded.blue().bold().to_string();
}
if level.eq_ignore_ascii_case("trace") {
return padded.magenta().bold().to_string();
}
padded.bold().to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::ffi::OsString;
#[test]
fn log_level_threshold_includes_more_severe_levels() {
assert_eq!(
LogLevelThreshold::Warn.levels_upper(),
vec!["WARN".to_string(), "ERROR".to_string()]
);
assert_eq!(
LogLevelThreshold::Trace.levels_upper(),
vec![
"TRACE".to_string(),
"DEBUG".to_string(),
"INFO".to_string(),
"WARN".to_string(),
"ERROR".to_string(),
]
);
}
#[test]
fn log_level_rejects_aliases_and_unknown_values() {
assert!(Args::try_parse_from(["codex-state-logs", "--level", "warning"]).is_err());
assert!(Args::try_parse_from(["codex-state-logs", "--level", "err"]).is_err());
assert!(Args::try_parse_from(["codex-state-logs", "--level", "warn,error"]).is_err());
}
#[test]
fn log_level_accepts_canonical_values_case_insensitively() {
let args = Args::try_parse_from(["codex-state-logs", "--level", "WARN"])
.expect("parse uppercase log level");
assert_eq!(args.level, Some(LogLevelThreshold::Warn));
}
/// Explicit database selection must not parse an overridden Codex home.
#[tokio::test]
async fn direct_db_skips_codex_home_config() {
let codex_home = tempfile::tempdir().expect("create Codex home");
std::fs::write(codex_home.path().join("config.toml"), "model = [")
.expect("write invalid config");
let sqlite_home = tempfile::tempdir().expect("create SQLite home");
let db_path = sqlite_home.path().join("logs_2.sqlite");
let args = Args::try_parse_from([
OsString::from("codex-state-logs"),
OsString::from("--codex-home"),
codex_home.path().as_os_str().to_owned(),
OsString::from("--db"),
db_path.as_os_str().to_owned(),
])
.expect("parse arguments");
let sqlite = resolve_sqlite_config(&args)
.await
.expect("resolve SQLite config");
assert_eq!(sqlite.logs_db_path(), db_path);
}
/// Direct database selection must preserve native path bytes.
#[cfg(unix)]
#[tokio::test]
async fn direct_db_preserves_non_utf8_path() {
use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStringExt;
let temp_dir = tempfile::tempdir().expect("create temp dir");
let mut db_path = temp_dir.path().as_os_str().as_bytes().to_vec();
db_path.extend_from_slice(b"/non-utf8-\xff/logs_2.sqlite");
let db_path = PathBuf::from(OsString::from_vec(db_path));
let args = Args::try_parse_from([
OsString::from("codex-state-logs"),
OsString::from("--db"),
db_path.as_os_str().to_owned(),
])
.expect("parse arguments");
let sqlite = resolve_sqlite_config(&args)
.await
.expect("resolve SQLite config");
assert_eq!(sqlite.logs_db_path(), db_path);
}
}

View File

@@ -0,0 +1,80 @@
use anyhow::Context;
use anyhow::Result;
use codex_app_server::in_process::EmbeddedNetworkPolicy;
use codex_cloud_config::managed_config_bundle_loader_for_storage;
use codex_config::CloudConfigBundleLoader;
use codex_config::ConfigLoadOptions;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
use codex_core::config::ConfigOverrides;
use codex_core::config::LoaderOverrides;
use codex_core::config::bootstrap_auth_config;
use codex_core::config::find_codex_home;
use codex_core::config::load_config_toml_with_layer_stack;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_cli::CliConfigOverrides;
pub async fn load_config(
config_overrides: &CliConfigOverrides,
loader_overrides: LoaderOverrides,
) -> Result<Config> {
let mut config = config_builder(
config_overrides,
loader_overrides,
ConfigOverrides::default(),
)
.await?
.build()
.await
.context("failed to load configuration")?;
config.config_layer_stack.ensure_config_server_applied()?;
EmbeddedNetworkPolicy::default().activate(&mut config);
Ok(config)
}
pub async fn config_builder(
config_overrides: &CliConfigOverrides,
loader_overrides: LoaderOverrides,
harness_overrides: ConfigOverrides,
) -> Result<ConfigBuilder> {
let network_policy = EmbeddedNetworkPolicy::load(&loader_overrides).await;
let cli_overrides = config_overrides
.parse_overrides()
.map_err(anyhow::Error::msg)?;
let codex_home = find_codex_home().context("failed to resolve CODEX_HOME")?;
let cwd = match harness_overrides.cwd.as_deref() {
Some(cwd) => AbsolutePathBuf::relative_to_current_dir(cwd),
None => AbsolutePathBuf::current_dir(),
}
.context("failed to resolve current directory")?;
let bootstrap_config = load_config_toml_with_layer_stack(
codex_home.as_path(),
Some(&cwd),
cli_overrides.clone(),
ConfigLoadOptions {
loader_overrides: loader_overrides.clone(),
strict_config: false,
cloud_config_bundle: CloudConfigBundleLoader::default(),
},
)
.await
.context("failed to load bootstrap configuration")?;
let cloud_config_bundle = managed_config_bundle_loader_for_storage(
network_policy.bind_bootstrap_auth(
bootstrap_auth_config(codex_home.as_path(), &bootstrap_config)
.context("failed to resolve cloud configuration authentication")?,
),
bootstrap_config.config_layer_stack.requirements_toml(),
/*enable_codex_api_key_env*/ false,
)
.await
.context("failed to initialize cloud configuration authentication")?;
Ok(ConfigBuilder::default()
.codex_home(codex_home.to_path_buf())
.cli_overrides(cli_overrides)
.loader_overrides(loader_overrides)
.harness_overrides(harness_overrides)
.cloud_config_bundle(cloud_config_bundle)
.fallback_cwd(Some(cwd.to_path_buf())))
}

View File

@@ -0,0 +1,29 @@
//! Preserve config overrides across command boundaries without changing typed child arguments.
use crate::MultitoolCli;
use clap::CommandFactory;
use clap::FromArgMatches;
use codex_utils_cli::collect_config_overrides;
use std::ffi::OsString;
pub(super) fn try_parse_from(
args: impl IntoIterator<Item = impl Into<OsString>>,
) -> Result<MultitoolCli, clap::Error> {
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
let mut command = MultitoolCli::command();
let mut matches = command.try_get_matches_from_mut(&args)?;
crate::queue_cmd::validate_options(&command, &matches)?;
let mut cli = MultitoolCli::from_arg_matches_mut(&mut matches)
.map_err(|error| error.format(&mut command))?;
if cli.subcommand.is_none() || cli.config_overrides.raw_overrides.is_empty() {
return Ok(cli);
}
// Keep child copies unchanged: dispatch merges apply them after feature overrides.
cli.config_overrides = collect_config_overrides(MultitoolCli::command(), args)?;
Ok(cli)
}
#[cfg(test)]
#[path = "config_override_args_tests.rs"]
mod tests;

View File

@@ -0,0 +1,37 @@
//! Regression coverage for overrides split across CLI command boundaries.
use super::try_parse_from;
use crate::Subcommand;
use crate::mcp_cmd::McpSubcommand;
use pretty_assertions::assert_eq;
#[test]
fn preserves_scoped_overrides_and_forwarded_arguments() {
let cli = try_parse_from([
"codex",
"--config=a=1",
"mcp",
"-cb=2",
"add",
"example",
"-c",
"a=3",
"--",
"program",
"-c",
"payload",
])
.expect("parse");
assert_eq!(cli.config_overrides.raw_overrides, ["a=1", "b=2", "a=3"]);
let Some(Subcommand::Mcp(mcp)) = cli.subcommand else {
panic!("expected mcp");
};
assert_eq!(mcp.config_overrides.raw_overrides, ["a=3"]);
let McpSubcommand::Add(add) = mcp.subcommand else {
panic!("expected add");
};
assert_eq!(
add.transport_args.stdio.expect("stdio transport").command,
["program", "-c", "payload"],
);
}

View File

@@ -0,0 +1,42 @@
//! Confirmation for copying the invoking CLI package into a daemon installation.
use std::io::IsTerminal;
use anyhow::Result;
use codex_app_server_daemon::InstallRequest;
pub(crate) fn confirm_install(request: &InstallRequest, yes: bool) -> Result<bool> {
eprintln!("{}", describe_install(request));
if yes {
return Ok(true);
}
anyhow::ensure!(
std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),
"daemon installation requires confirmation; rerun with --yes to copy this CLI package"
);
let confirmed = crate::confirm("Copy this package? [y/N]: ")?;
if !confirmed {
eprintln!("Daemon installation cancelled.");
}
Ok(confirmed)
}
fn describe_install(request: &InstallRequest) -> String {
let mut message = format!(
"Replace installed daemon version {} with CLI version {} from {}.\nThe daemon package will be installed in {}.\nThe selected package will be pinned. Run `codex app-server daemon update` to return to production updates.",
request.installed_version.as_deref().unwrap_or("unknown"),
request.version,
request.source.display(),
request.destination.display()
);
if request.restart_required {
message.push_str(
"\nThe running daemon will restart; active or queued work may be interrupted.",
);
}
message
}
#[cfg(test)]
#[path = "daemon_install_tests.rs"]
mod tests;

View File

@@ -0,0 +1,18 @@
use super::*;
#[test]
fn running_daemon_replacement_prompt() {
let request = InstallRequest {
source: "/cli/package".into(),
version: "0.0.0".into(),
destination: "/home/packages/app-server-daemon".into(),
installed_version: Some("0.152.0".into()),
restart_required: true,
};
insta::assert_snapshot!(describe_install(&request), @r"
Replace installed daemon version 0.152.0 with CLI version 0.0.0 from /cli/package.
The daemon package will be installed in /home/packages/app-server-daemon.
The selected package will be pinned. Run `codex app-server daemon update` to return to production updates.
The running daemon will restart; active or queued work may be interrupted.
");
}

View File

@@ -0,0 +1,60 @@
//! Foreground daemon observations use the CLI's existing consent and identity handling.
//! Detached updater entry points never call this module.
use codex_utils_cli::CliConfigOverrides;
use std::time::Duration;
use tokio::time::timeout;
pub(crate) async fn record_command(
overrides: &CliConfigOverrides,
analytics_default_enabled: bool,
target: &'static str,
result: &anyhow::Result<Option<codex_app_server_daemon::UpdateOutput>>,
) {
if std::env::var_os(codex_app_server_daemon::telemetry::HANDOFF_ENV).is_some() {
return;
}
// Skip telemetry if consent-aware configuration cannot be loaded promptly.
let Ok(Ok(config)) = timeout(
Duration::from_secs(/*secs*/ 2),
crate::cloud_config::load_config(overrides, codex_config::LoaderOverrides::default()),
)
.await
else {
return;
};
use codex_app_server_daemon::UpdateStatus;
let outcome = match result {
Ok(Some(output)) => match output.status {
UpdateStatus::Updated => "updated",
UpdateStatus::NoUpdate => "no_update",
UpdateStatus::Unsupported => "unsupported",
},
Ok(None) => "cancelled",
Err(_) => "unconfirmed",
};
let Ok(Ok(Some(otel))) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
codex_core::otel_init::build_provider(
&config,
env!("CARGO_PKG_VERSION"),
/*service_name_override*/ None,
analytics_default_enabled,
)
})) else {
return;
};
if let Some(metrics) = otel.metrics() {
let mut tags = codex_app_server_daemon::telemetry::settings_tags(&config.codex_home)
.await
.to_vec();
tags.extend([
("initiation_source", "cli"),
("update_target", target),
("outcome", outcome),
]);
let _ = metrics.counter("codex.daemon.update", /*inc*/ 1, &tags);
}
let _ = otel
.shutdown_with_timeout(std::time::Duration::from_secs(/*secs*/ 2))
.await;
}

View File

@@ -0,0 +1,69 @@
#![cfg(test)]
use super::*;
use codex_tui::DaemonUpdateSource;
use pretty_assertions::assert_eq;
use std::os::unix::fs::PermissionsExt;
#[test]
fn package_update_runs_outside_the_project() -> anyhow::Result<()> {
const CHILD: &str = "CODEX_TEST_PACKAGE_UPDATE_CHILD";
if std::env::var_os(CHILD).is_some() {
return run_update_action(UpdateAction::PnpmGlobalLatest, /*cli_executable*/ None);
}
let project = tempfile::tempdir()?;
let bin = tempfile::tempdir()?;
codex_utils_cargo_bin::write_executable(
&bin.path().join("pnpm"),
"#!/bin/sh\npwd -P > \"$0.cwd\"\n",
)?;
assert_cmd::Command::new(std::env::current_exe()?)
.args([
"--exact",
"daemon_update_tests::package_update_runs_outside_the_project",
])
.current_dir(project.path())
.env("TMPDIR", project.path())
.env("PATH", bin.path())
.env(CHILD, "1")
.assert()
.success();
let cwd = std::fs::read_to_string(bin.path().join("pnpm.cwd"))?;
assert!(!std::path::Path::new(cwd.trim_end()).starts_with(project.path().canonicalize()?));
Ok(())
}
#[test]
fn daemon_handoff_uses_selected_executable_and_propagates_failure() -> anyhow::Result<()> {
let dir = tempfile::tempdir()?;
let executable = dir.path().join("launching CLI");
let receipt = dir.path().join("launching CLI.args");
codex_utils_cargo_bin::write_executable(
&executable,
"#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$0.args\"\n",
)?;
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(/*mode*/ 0o700))?;
for (source, expected) in [
(
DaemonUpdateSource::PublicStable,
"app-server\ndaemon\nupdate\n",
),
(
DaemonUpdateSource::ThisCli,
"app-server\ndaemon\nupdate\n--from-cli\n--yes\n",
),
] {
run_update_action(UpdateAction::Daemon(source), Some(&executable))?;
assert_eq!(std::fs::read_to_string(&receipt)?, expected);
}
codex_utils_cargo_bin::write_executable(&executable, "#!/bin/sh\nexit 7\n")?;
let error = run_update_action(
UpdateAction::Daemon(DaemonUpdateSource::ThisCli),
Some(&executable),
)
.unwrap_err();
assert!(error.to_string().contains("Daemon update failed"));
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,57 @@
use codex_app_server::in_process::EmbeddedNetworkPolicy;
use codex_cloud_config::chatgpt_config_bundle_loader_for_storage;
use codex_config::CloudConfigBundleLoader;
use codex_config::ConfigLoadOptions;
use codex_core::config::bootstrap_auth_config;
use codex_core::config::load_config_toml_with_layer_stack;
use codex_utils_absolute_path::AbsolutePathBuf;
use toml::Value as TomlValue;
use super::DebugSandboxConfigOptions;
use super::ManagedRequirementsMode;
pub(super) async fn bootstrap_cloud_config_bundle(
cli_overrides: &[(String, TomlValue)],
options: &DebugSandboxConfigOptions,
resolve_codex_home: impl FnOnce() -> std::io::Result<AbsolutePathBuf>,
strict_config: bool,
) -> anyhow::Result<CloudConfigBundleLoader> {
if options.sandbox_state.sandbox_state_json.is_some()
|| !matches!(
options.managed_requirements_mode,
ManagedRequirementsMode::Include
)
{
return Ok(CloudConfigBundleLoader::default());
}
let codex_home = resolve_codex_home()?;
let cwd = match options.cwd.as_deref() {
Some(cwd) => AbsolutePathBuf::relative_to_current_dir(cwd)?,
None => AbsolutePathBuf::current_dir()?,
};
let network_policy = EmbeddedNetworkPolicy::load(&options.loader_overrides).await;
let bootstrap_config = load_config_toml_with_layer_stack(
codex_home.as_path(),
Some(&cwd),
cli_overrides.to_vec(),
ConfigLoadOptions {
loader_overrides: options.loader_overrides.clone(),
strict_config,
cloud_config_bundle: CloudConfigBundleLoader::default(),
},
)
.await?;
Ok(chatgpt_config_bundle_loader_for_storage(
network_policy.bind_bootstrap_auth(bootstrap_auth_config(
codex_home.as_path(),
&bootstrap_config,
)?),
/*enable_codex_api_key_env*/ false,
)
.await?)
}
#[cfg(test)]
#[path = "cloud_config_tests.rs"]
mod tests;

View File

@@ -0,0 +1,185 @@
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::ConfigRequirementsToml;
use codex_config::LoaderOverrides;
use codex_config::types::AuthCredentialsStoreMode;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::super::DebugSandboxConfigOptions;
use super::super::ManagedRequirementsMode;
use super::super::load_debug_sandbox_config_with_codex_home;
use super::bootstrap_cloud_config_bundle;
const CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS: &str = r#"
default_permissions = "managed-cloud"
[allowed_permission_profiles]
managed-cloud = true
[permissions.managed-cloud]
extends = ":workspace"
[permissions.managed-cloud.network]
enabled = true
"#;
#[tokio::test]
async fn sandbox_fetches_managed_profile_only_when_local_policy_allows_backend() -> Result<()> {
let server = MockServer::start().await;
let expected_requirements = json!([{
"id": "req-managed-cloud",
"name": "Managed permissions",
"contents": CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
}]);
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"requirements_toml": {
"enterprise_managed": expected_requirements.clone(),
},
})))
.expect(1)
.mount(&server)
.await;
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{}/backend-api\"\n",
server.uri(),
),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
let mut options = DebugSandboxConfigOptions {
sandbox_state: Default::default(),
permissions_profile: None,
cwd: Some(codex_home.path().to_path_buf()),
managed_requirements_mode: ManagedRequirementsMode::Include,
loader_overrides: LoaderOverrides::without_managed_config_for_tests(),
};
let bootstrap = async |options: &DebugSandboxConfigOptions| {
bootstrap_cloud_config_bundle(
&[],
options,
|| AbsolutePathBuf::from_absolute_path(codex_home.path()),
/*strict_config*/ false,
)
.await
};
let requirements = codex_home.path().join("requirements.toml");
std::fs::write(&requirements, "[application.network]\nenabled = true\n")?;
options.loader_overrides.system_requirements_path = Some(requirements);
let denied = bootstrap(&options)
.await?
.get()
.await
.expect_err("local policy denies the bundle endpoint");
assert_eq!(
denied.to_string(),
"destination denied by application network policy"
);
assert!(
server
.received_requests()
.await
.context("mock request log")?
.is_empty()
);
options.permissions_profile = Some("managed-cloud".to_string());
options.loader_overrides = LoaderOverrides::without_managed_config_for_tests();
let cloud_config_bundle = bootstrap(&options).await?;
let config = load_debug_sandbox_config_with_codex_home(
Vec::new(),
/*codex_linux_sandbox_exe*/ None,
options,
Some(codex_home.path().to_path_buf()),
cloud_config_bundle,
/*strict_config*/ false,
)
.await?;
assert_eq!(
config
.permissions
.active_permission_profile()
.map(|profile| profile.id),
Some("managed-cloud".to_string()),
);
assert_eq!(
config.permissions.network_sandbox_policy(),
NetworkSandboxPolicy::Enabled,
);
assert_eq!(
config.config_layer_stack.requirements_toml(),
&toml::from_str::<ConfigRequirementsToml>(CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS,)?,
);
let cache: Value = serde_json::from_slice(&std::fs::read(
codex_home.path().join("cloud-config-bundle-cache.json"),
)?)?;
assert_eq!(
json!({
"chatgpt_user_id": cache["signed_payload"]["chatgpt_user_id"],
"account_id": cache["signed_payload"]["account_id"],
"requirements_toml": cache["signed_payload"]["bundle"]["requirements_toml"],
}),
json!({
"chatgpt_user_id": "user-123",
"account_id": "workspace-123",
"requirements_toml": {
"enterprise_managed": expected_requirements,
},
}),
);
server.verify().await;
Ok(())
}
#[tokio::test]
async fn sandbox_state_skips_cloud_bootstrap() -> Result<()> {
let options = DebugSandboxConfigOptions {
sandbox_state: crate::SandboxStateArgs {
sandbox_state_json: Some("{}".into()),
..Default::default()
},
permissions_profile: None,
cwd: None,
managed_requirements_mode: ManagedRequirementsMode::Include,
loader_overrides: LoaderOverrides::without_managed_config_for_tests(),
};
bootstrap_cloud_config_bundle(
&[],
&options,
|| panic!("supplied state must skip CODEX_HOME resolution"),
/*strict_config*/ false,
)
.await?;
Ok(())
}

View File

@@ -0,0 +1,372 @@
use std::collections::HashSet;
use tokio::task::JoinHandle;
use tracing::warn;
/// Tracks the (recursive) descendants of a process by using `kqueue` to watch for fork events, and
/// `proc_listchildpids` to list the children of a process.
pub(crate) struct PidTracker {
kq: libc::c_int,
handle: JoinHandle<HashSet<i32>>,
}
impl PidTracker {
pub(crate) fn new(root_pid: i32) -> Option<Self> {
if root_pid <= 0 {
return None;
}
let kq = unsafe { libc::kqueue() };
let handle = tokio::task::spawn_blocking(move || track_descendants(kq, root_pid));
Some(Self { kq, handle })
}
pub(crate) async fn stop(self) -> HashSet<i32> {
trigger_stop_event(self.kq);
self.handle.await.unwrap_or_default()
}
}
unsafe extern "C" {
fn proc_listchildpids(
ppid: libc::c_int,
buffer: *mut libc::c_void,
buffersize: libc::c_int,
) -> libc::c_int;
}
/// Wrap proc_listchildpids.
fn list_child_pids(parent: i32) -> Vec<i32> {
unsafe {
let mut capacity: usize = 16;
loop {
let mut buf: Vec<i32> = vec![0; capacity];
let count = proc_listchildpids(
parent as libc::c_int,
buf.as_mut_ptr() as *mut libc::c_void,
(buf.len() * std::mem::size_of::<i32>()) as libc::c_int,
);
if count <= 0 {
return Vec::new();
}
let returned = count as usize;
if returned < capacity {
buf.truncate(returned);
return buf;
}
capacity = capacity.saturating_mul(2).max(returned + 16);
}
}
}
fn pid_is_alive(pid: i32) -> bool {
if pid <= 0 {
return false;
}
let res = unsafe { libc::kill(pid as libc::pid_t, 0) };
if res == 0 {
true
} else {
matches!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::EPERM)
)
}
}
enum WatchPidError {
ProcessGone,
Other(std::io::Error),
}
/// Add `pid` to the watch list in `kq`.
fn watch_pid(kq: libc::c_int, pid: i32) -> Result<(), WatchPidError> {
if pid <= 0 {
return Err(WatchPidError::ProcessGone);
}
let kev = libc::kevent {
ident: pid as libc::uintptr_t,
filter: libc::EVFILT_PROC,
flags: libc::EV_ADD | libc::EV_CLEAR,
fflags: libc::NOTE_FORK | libc::NOTE_EXEC | libc::NOTE_EXIT,
data: 0,
udata: std::ptr::null_mut(),
};
let res = unsafe { libc::kevent(kq, &kev, 1, std::ptr::null_mut(), 0, std::ptr::null()) };
if res < 0 {
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
Err(WatchPidError::ProcessGone)
} else {
Err(WatchPidError::Other(err))
}
} else {
Ok(())
}
}
fn watch_children(
kq: libc::c_int,
parent: i32,
seen: &mut HashSet<i32>,
active: &mut HashSet<i32>,
) {
for child_pid in list_child_pids(parent) {
add_pid_watch(kq, child_pid, seen, active);
}
}
/// Watch `pid` and its children, updating `seen` and `active` sets.
fn add_pid_watch(kq: libc::c_int, pid: i32, seen: &mut HashSet<i32>, active: &mut HashSet<i32>) {
if pid <= 0 {
return;
}
let newly_seen = seen.insert(pid);
let mut should_recurse = newly_seen;
if active.insert(pid) {
match watch_pid(kq, pid) {
Ok(()) => {
should_recurse = true;
}
Err(WatchPidError::ProcessGone) => {
active.remove(&pid);
return;
}
Err(WatchPidError::Other(err)) => {
warn!("failed to watch pid {pid}: {err}");
active.remove(&pid);
return;
}
}
}
if should_recurse {
watch_children(kq, pid, seen, active);
}
}
const STOP_IDENT: libc::uintptr_t = 1;
fn register_stop_event(kq: libc::c_int) -> bool {
let kev = libc::kevent {
ident: STOP_IDENT,
filter: libc::EVFILT_USER,
flags: libc::EV_ADD | libc::EV_CLEAR,
fflags: 0,
data: 0,
udata: std::ptr::null_mut(),
};
let res = unsafe { libc::kevent(kq, &kev, 1, std::ptr::null_mut(), 0, std::ptr::null()) };
res >= 0
}
fn trigger_stop_event(kq: libc::c_int) {
if kq < 0 {
return;
}
let kev = libc::kevent {
ident: STOP_IDENT,
filter: libc::EVFILT_USER,
flags: 0,
fflags: libc::NOTE_TRIGGER,
data: 0,
udata: std::ptr::null_mut(),
};
let _ = unsafe { libc::kevent(kq, &kev, 1, std::ptr::null_mut(), 0, std::ptr::null()) };
}
/// Put all of the above together to track all the descendants of `root_pid`.
fn track_descendants(kq: libc::c_int, root_pid: i32) -> HashSet<i32> {
if kq < 0 {
let mut seen = HashSet::new();
seen.insert(root_pid);
return seen;
}
if !register_stop_event(kq) {
let mut seen = HashSet::new();
seen.insert(root_pid);
let _ = unsafe { libc::close(kq) };
return seen;
}
let mut seen: HashSet<i32> = HashSet::new();
let mut active: HashSet<i32> = HashSet::new();
add_pid_watch(kq, root_pid, &mut seen, &mut active);
const EVENTS_CAP: usize = 32;
let mut events: [libc::kevent; EVENTS_CAP] =
unsafe { std::mem::MaybeUninit::zeroed().assume_init() };
let mut stop_requested = false;
loop {
if active.is_empty() {
if !pid_is_alive(root_pid) {
break;
}
add_pid_watch(kq, root_pid, &mut seen, &mut active);
if active.is_empty() {
continue;
}
}
let nev = unsafe {
libc::kevent(
kq,
std::ptr::null::<libc::kevent>(),
0,
events.as_mut_ptr(),
EVENTS_CAP as libc::c_int,
std::ptr::null(),
)
};
if nev < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::Interrupted {
continue;
}
break;
}
if nev == 0 {
continue;
}
for ev in events.iter().take(nev as usize) {
let pid = ev.ident as i32;
if ev.filter == libc::EVFILT_USER && ev.ident == STOP_IDENT {
stop_requested = true;
break;
}
if (ev.flags & libc::EV_ERROR) != 0 {
if ev.data == libc::ESRCH as isize {
active.remove(&pid);
}
continue;
}
if (ev.fflags & libc::NOTE_FORK) != 0 {
watch_children(kq, pid, &mut seen, &mut active);
}
if (ev.fflags & libc::NOTE_EXIT) != 0 {
active.remove(&pid);
}
}
if stop_requested {
break;
}
}
let _ = unsafe { libc::close(kq) };
seen
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
use std::process::Stdio;
use std::time::Duration;
#[test]
fn pid_is_alive_detects_current_process() {
let pid = std::process::id() as i32;
assert!(pid_is_alive(pid));
}
#[cfg(target_os = "macos")]
#[test]
fn list_child_pids_includes_spawned_child() {
let mut child = Command::new("/bin/sleep")
.arg("5")
.stdin(Stdio::null())
.spawn()
.expect("failed to spawn child process");
let child_pid = child.id() as i32;
let parent_pid = std::process::id() as i32;
let mut found = false;
for _ in 0..100 {
if list_child_pids(parent_pid).contains(&child_pid) {
found = true;
break;
}
std::thread::sleep(Duration::from_millis(10));
}
let _ = child.kill();
let _ = child.wait();
assert!(found, "expected to find child pid {child_pid} in list");
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn pid_tracker_collects_spawned_children() {
let tracker = PidTracker::new(std::process::id() as i32).expect("failed to create tracker");
let mut child = Command::new("/bin/sleep")
.arg("0.1")
.stdin(Stdio::null())
.spawn()
.expect("failed to spawn child process");
let child_pid = child.id() as i32;
let parent_pid = std::process::id() as i32;
let _ = child.wait();
let seen = tracker.stop().await;
assert!(
seen.contains(&parent_pid),
"expected tracker to include parent pid {parent_pid}"
);
assert!(
seen.contains(&child_pid),
"expected tracker to include child pid {child_pid}"
);
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn pid_tracker_collects_bash_subshell_descendants() {
let tracker = PidTracker::new(std::process::id() as i32).expect("failed to create tracker");
let child = Command::new("/bin/bash")
.arg("-c")
.arg("(sleep 0.1 & echo $!; wait)")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.expect("failed to spawn bash");
let output = child.wait_with_output().unwrap().stdout;
let subshell_pid = String::from_utf8_lossy(&output)
.trim()
.parse::<i32>()
.expect("failed to parse subshell pid");
let seen = tracker.stop().await;
assert!(
seen.contains(&subshell_pid),
"expected tracker to include subshell pid {subshell_pid}"
);
}
}

View File

@@ -0,0 +1,114 @@
use std::collections::HashSet;
use tokio::io::AsyncBufReadExt;
use tokio::process::Child;
use tokio::task::JoinHandle;
use super::pid_tracker::PidTracker;
pub struct SandboxDenial {
pub name: String,
pub capability: String,
}
pub struct DenialLogger {
log_stream: Child,
pid_tracker: Option<PidTracker>,
log_reader: Option<JoinHandle<Vec<u8>>>,
}
impl DenialLogger {
pub(crate) fn new() -> Option<Self> {
let mut log_stream = start_log_stream()?;
let stdout = log_stream.stdout.take()?;
let log_reader = tokio::spawn(async move {
let mut reader = tokio::io::BufReader::new(stdout);
let mut logs = Vec::new();
let mut chunk = Vec::new();
loop {
match reader.read_until(b'\n', &mut chunk).await {
Ok(0) | Err(_) => break,
Ok(_) => {
logs.extend_from_slice(&chunk);
chunk.clear();
}
}
}
logs
});
Some(Self {
log_stream,
pid_tracker: None,
log_reader: Some(log_reader),
})
}
pub(crate) fn on_child_spawn(&mut self, child: &Child) {
if let Some(root_pid) = child.id() {
self.pid_tracker = PidTracker::new(root_pid as i32);
}
}
pub(crate) async fn finish(mut self) -> Vec<SandboxDenial> {
let pid_set = match self.pid_tracker {
Some(tracker) => tracker.stop().await,
None => Default::default(),
};
if pid_set.is_empty() {
return Vec::new();
}
let _ = self.log_stream.kill().await;
let _ = self.log_stream.wait().await;
let logs_bytes = match self.log_reader.take() {
Some(handle) => handle.await.unwrap_or_default(),
None => Vec::new(),
};
let logs = String::from_utf8_lossy(&logs_bytes);
let mut seen: HashSet<(String, String)> = HashSet::new();
let mut denials: Vec<SandboxDenial> = Vec::new();
for line in logs.lines() {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(line)
&& let Some(msg) = json.get("eventMessage").and_then(|v| v.as_str())
&& let Some((pid, name, capability)) = parse_message(msg)
&& pid_set.contains(&pid)
&& seen.insert((name.clone(), capability.clone()))
{
denials.push(SandboxDenial { name, capability });
}
}
denials
}
}
fn start_log_stream() -> Option<Child> {
use std::process::Stdio;
const PREDICATE: &str = r#"(((processID == 0) AND (senderImagePath CONTAINS "/Sandbox")) OR (subsystem == "com.apple.sandbox.reporting"))"#;
tokio::process::Command::new("log")
.args(["stream", "--style", "ndjson", "--predicate", PREDICATE])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.ok()
}
fn parse_message(msg: &str) -> Option<(i32, String, String)> {
// Example message:
// Sandbox: processname(1234) deny(1) capability-name args...
static RE: std::sync::OnceLock<regex_lite::Regex> = std::sync::OnceLock::new();
let re = RE.get_or_init(|| {
#[expect(clippy::unwrap_used)]
regex_lite::Regex::new(r"^Sandbox:\s*(.+?)\((\d+)\)\s+deny\(.*?\)\s*(.+)$").unwrap()
});
let (_, [name, pid_str, capability]) = re.captures(msg)?.extract();
let pid = pid_str.trim().parse::<i32>().ok()?;
Some((pid, name.to_string(), capability.to_string()))
}

View File

@@ -0,0 +1,513 @@
use anyhow::Context as _;
use std::ffi::CString;
use std::path::Path;
use std::path::PathBuf;
use tempfile::Builder;
use tokio::process::Command;
const CODEX_BUNDLE_IDENTIFIER: &str = "com.openai.codex";
const OPENAI_APPLE_TEAM_IDENTIFIER: &str = "2DC432GLL2";
const CODEX_DMG_URL_ARM64: &str = "https://persistent.oaistatic.com/codex-app-prod/Codex.dmg";
const CODEX_DMG_URL_X64: &str =
"https://persistent.oaistatic.com/codex-app-prod/Codex-latest-x64.dmg";
pub async fn run_mac_app_open_or_install(
workspace: PathBuf,
download_url_override: Option<String>,
) -> anyhow::Result<()> {
if let Some(app_path) = find_existing_codex_app_path(&codex_app_search_dirs()) {
eprintln!(
"Opening Desktop app at {app_path}...",
app_path = app_path.display()
);
open_codex_app(&app_path, &workspace).await?;
return Ok(());
}
eprintln!("Desktop app not found; downloading installer...");
let download_url = download_url_override.unwrap_or_else(|| {
let default_url = if is_apple_silicon_mac() {
CODEX_DMG_URL_ARM64
} else {
CODEX_DMG_URL_X64
};
default_url.to_string()
});
let installed_app = download_and_install_codex_to_user_applications(&download_url)
.await
.context("failed to download/install Desktop app")?;
eprintln!(
"Launching Desktop app from {installed_app}...",
installed_app = installed_app.display()
);
open_codex_app(&installed_app, &workspace).await?;
Ok(())
}
fn is_apple_silicon_mac() -> bool {
fn macos_sysctl_flag(name: &str) -> Option<bool> {
let name = CString::new(name).ok()?;
let mut value: libc::c_int = 0;
let mut size = std::mem::size_of_val(&value);
let result = unsafe {
libc::sysctlbyname(
name.as_ptr(),
(&mut value as *mut libc::c_int).cast::<libc::c_void>(),
&mut size,
std::ptr::null_mut(),
0,
)
};
(result == 0).then_some(value != 0)
}
std::env::consts::ARCH == "aarch64"
|| macos_sysctl_flag("sysctl.proc_translated").unwrap_or(false)
|| macos_sysctl_flag("hw.optional.arm64").unwrap_or(false)
}
fn find_existing_codex_app_path(applications_dirs: &[PathBuf]) -> Option<PathBuf> {
applications_dirs
.iter()
.flat_map(|dir| ["ChatGPT.app", "Codex.app"].map(|app_name| dir.join(app_name)))
.find(|candidate| is_codex_app_bundle(candidate))
}
fn codex_app_search_dirs() -> Vec<PathBuf> {
let mut paths = vec![PathBuf::from("/Applications")];
if let Some(home) = std::env::var_os("HOME") {
paths.push(PathBuf::from(home).join("Applications"));
}
paths
}
fn is_codex_app_bundle(app_path: &Path) -> bool {
if !app_path.is_dir() {
return false;
}
std::process::Command::new("/usr/bin/plutil")
.arg("-extract")
.arg("CFBundleIdentifier")
.arg("raw")
.arg("-o")
.arg("-")
.arg(app_path.join("Contents/Info.plist"))
.output()
.is_ok_and(|output| {
output.status.success()
&& String::from_utf8_lossy(&output.stdout).trim() == CODEX_BUNDLE_IDENTIFIER
})
}
async fn open_codex_app(app_path: &Path, workspace: &Path) -> anyhow::Result<()> {
verify_codex_app_bundle(app_path).await?;
eprintln!(
"Opening workspace {workspace}...",
workspace = workspace.display()
);
let url = codex_new_thread_url(workspace);
let status = Command::new("open")
.arg("-a")
.arg(app_path)
.arg(&url)
.status()
.await
.context("failed to invoke `open`")?;
if status.success() {
return Ok(());
}
anyhow::bail!(
"`open -a {app_path} {url}` exited with {status}",
app_path = app_path.display(),
url = url
);
}
async fn verify_codex_app_bundle(app_path: &Path) -> anyhow::Result<()> {
let requirement = format!(
"identifier \"{CODEX_BUNDLE_IDENTIFIER}\" and anchor apple generic and certificate leaf[subject.OU] = \"{OPENAI_APPLE_TEAM_IDENTIFIER}\""
);
let output = Command::new("/usr/bin/codesign")
.args(["--verify", "--deep", "--strict"])
.arg(format!("-R={requirement}"))
.arg(app_path)
.output()
.await
.context("failed to verify Desktop app signature")?;
if output.status.success() {
return Ok(());
}
anyhow::bail!(
"Desktop app at {} failed OpenAI signature verification (team {OPENAI_APPLE_TEAM_IDENTIFIER}, bundle {CODEX_BUNDLE_IDENTIFIER}): {}",
app_path.display(),
String::from_utf8_lossy(&output.stderr).trim()
);
}
fn codex_new_thread_url(workspace: &Path) -> String {
let workspace = workspace.as_os_str().to_string_lossy();
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
serializer.append_pair("path", workspace.as_ref());
let query = serializer.finish();
format!("codex://threads/new?{query}")
}
async fn download_and_install_codex_to_user_applications(dmg_url: &str) -> anyhow::Result<PathBuf> {
let temp_dir = Builder::new()
.prefix("codex-app-installer-")
.tempdir()
.context("failed to create temp dir")?;
let tmp_root = temp_dir.path().to_path_buf();
let _temp_dir = temp_dir;
let dmg_path = tmp_root.join("Codex.dmg");
download_dmg(dmg_url, &dmg_path).await?;
eprintln!("Mounting Desktop app installer...");
let mount_point = mount_dmg(&dmg_path).await?;
eprintln!(
"Installer mounted at {mount_point}.",
mount_point = mount_point.display()
);
let result = async {
let app_in_volume = find_codex_app_in_mount(&mount_point)
.context("failed to locate Codex.app in mounted dmg")?;
verify_codex_app_bundle(&app_in_volume)
.await
.context("refusing to install an unverified Desktop app")?;
install_codex_app_bundle(&app_in_volume).await
}
.await;
let detach_result = detach_dmg(&mount_point).await;
if let Err(err) = detach_result {
eprintln!(
"warning: failed to detach dmg at {mount_point}: {err}",
mount_point = mount_point.display()
);
}
result
}
async fn install_codex_app_bundle(app_in_volume: &Path) -> anyhow::Result<PathBuf> {
for applications_dir in candidate_applications_dirs()? {
eprintln!(
"Installing Desktop app into {applications_dir}...",
applications_dir = applications_dir.display()
);
std::fs::create_dir_all(&applications_dir).with_context(|| {
format!(
"failed to create applications dir {applications_dir}",
applications_dir = applications_dir.display()
)
})?;
let dest_app = applications_dir.join("Codex.app");
if dest_app.is_dir() {
return Ok(dest_app);
}
match copy_app_bundle(app_in_volume, &dest_app).await {
Ok(()) => return Ok(dest_app),
Err(err) => {
eprintln!(
"warning: failed to install Codex.app to {applications_dir}: {err}",
applications_dir = applications_dir.display()
);
}
}
}
anyhow::bail!("failed to install Codex.app to any applications directory");
}
fn candidate_applications_dirs() -> anyhow::Result<Vec<PathBuf>> {
let mut dirs = vec![PathBuf::from("/Applications")];
dirs.push(user_applications_dir()?);
Ok(dirs)
}
async fn download_dmg(url: &str, dest: &Path) -> anyhow::Result<()> {
eprintln!("Downloading installer...");
let status = Command::new("curl")
.arg("-fL")
.arg("--retry")
.arg("3")
.arg("--retry-delay")
.arg("1")
.arg("-o")
.arg(dest)
.arg(url)
.status()
.await
.context("failed to invoke `curl`")?;
if status.success() {
return Ok(());
}
anyhow::bail!("curl download failed with {status}");
}
async fn mount_dmg(dmg_path: &Path) -> anyhow::Result<PathBuf> {
let output = Command::new("hdiutil")
.arg("attach")
.arg("-nobrowse")
.arg("-readonly")
.arg(dmg_path)
.output()
.await
.context("failed to invoke `hdiutil attach`")?;
if !output.status.success() {
anyhow::bail!(
"`hdiutil attach` failed with {status}: {stderr}",
status = output.status,
stderr = String::from_utf8_lossy(&output.stderr)
);
}
let stdout = String::from_utf8_lossy(&output.stdout);
parse_hdiutil_attach_mount_point(&stdout)
.map(PathBuf::from)
.with_context(|| format!("failed to parse mount point from hdiutil output:\n{stdout}"))
}
async fn detach_dmg(mount_point: &Path) -> anyhow::Result<()> {
let status = Command::new("hdiutil")
.arg("detach")
.arg(mount_point)
.status()
.await
.context("failed to invoke `hdiutil detach`")?;
if status.success() {
return Ok(());
}
anyhow::bail!("hdiutil detach failed with {status}");
}
fn find_codex_app_in_mount(mount_point: &Path) -> anyhow::Result<PathBuf> {
let direct = mount_point.join("Codex.app");
if direct.is_dir() {
return Ok(direct);
}
for entry in std::fs::read_dir(mount_point).with_context(|| {
format!(
"failed to read {mount_point}",
mount_point = mount_point.display()
)
})? {
let entry = entry.context("failed to read mount directory entry")?;
let path = entry.path();
if path.extension().is_some_and(|ext| ext == "app") && path.is_dir() {
return Ok(path);
}
}
anyhow::bail!(
"no .app bundle found at {mount_point}",
mount_point = mount_point.display()
);
}
async fn copy_app_bundle(src_app: &Path, dest_app: &Path) -> anyhow::Result<()> {
let status = Command::new("ditto")
.arg(src_app)
.arg(dest_app)
.status()
.await
.context("failed to invoke `ditto`")?;
if status.success() {
return Ok(());
}
anyhow::bail!("ditto copy failed with {status}");
}
fn user_applications_dir() -> anyhow::Result<PathBuf> {
let home = std::env::var_os("HOME").context("HOME is not set")?;
Ok(PathBuf::from(home).join("Applications"))
}
fn parse_hdiutil_attach_mount_point(output: &str) -> Option<String> {
output.lines().find_map(|line| {
if !line.contains("/Volumes/") {
return None;
}
if let Some((_, mount)) = line.rsplit_once('\t') {
return Some(mount.trim().to_string());
}
line.split_whitespace()
.find(|field| field.starts_with("/Volumes/"))
.map(str::to_string)
})
}
#[cfg(test)]
mod tests {
use super::codex_new_thread_url;
use super::find_existing_codex_app_path;
use super::open_codex_app;
use super::parse_hdiutil_attach_mount_point;
use super::verify_codex_app_bundle;
use pretty_assertions::assert_eq;
use std::fs;
use std::path::Path;
fn write_app_bundle(app_path: &Path, bundle_identifier: &str) {
let contents_path = app_path.join("Contents");
fs::create_dir_all(&contents_path).expect("create app bundle");
fs::write(
contents_path.join("Info.plist"),
format!(
r#"<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>{bundle_identifier}</string></dict></plist>"#
),
)
.expect("write Info.plist");
}
#[test]
fn finds_chatgpt_app_with_codex_bundle_identifier() {
let temp_dir = tempfile::tempdir().expect("create temp dir");
let app_path = temp_dir.path().join("ChatGPT.app");
write_app_bundle(&app_path, "com.openai.codex");
assert_eq!(
find_existing_codex_app_path(&[temp_dir.path().to_path_buf()]),
Some(app_path)
);
}
#[test]
fn ignores_classic_chatgpt_app() {
let temp_dir = tempfile::tempdir().expect("create temp dir");
write_app_bundle(&temp_dir.path().join("ChatGPT.app"), "com.openai.chat");
let codex_app_path = temp_dir.path().join("Codex.app");
write_app_bundle(&codex_app_path, "com.openai.codex");
assert_eq!(
find_existing_codex_app_path(&[temp_dir.path().to_path_buf()]),
Some(codex_app_path)
);
}
#[tokio::test]
async fn rejects_unsigned_app_with_codex_bundle_identifier() {
let temp_dir = tempfile::tempdir().expect("create temp dir");
let app_path = temp_dir.path().join("Codex.app");
write_app_bundle(&app_path, "com.openai.codex");
let err = verify_codex_app_bundle(&app_path)
.await
.expect_err("unsigned app should not satisfy the OpenAI signing requirement");
assert!(
err.to_string()
.contains("failed OpenAI signature verification"),
"unexpected verification error: {err}"
);
}
#[tokio::test]
async fn rejects_valid_signature_without_openai_signing_identity() {
let temp_dir = tempfile::tempdir().expect("create temp dir");
let app_path = temp_dir.path().join("Codex.app");
let contents_path = app_path.join("Contents");
let executable_path = contents_path.join("MacOS/Codex");
fs::create_dir_all(executable_path.parent().expect("executable parent"))
.expect("create executable directory");
codex_utils_cargo_bin::copy_executable(Path::new("/usr/bin/true"), &executable_path)
.expect("copy executable into app bundle");
fs::write(
contents_path.join("Info.plist"),
r#"<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>com.openai.codex</string><key>CFBundleExecutable</key><string>Codex</string></dict></plist>"#,
)
.expect("write Info.plist");
let sign_status = std::process::Command::new("/usr/bin/codesign")
.args(["--force", "--sign", "-"])
.arg(&app_path)
.status()
.expect("sign app bundle");
assert!(sign_status.success(), "failed to ad-hoc sign app bundle");
let verify_status = std::process::Command::new("/usr/bin/codesign")
.args(["--verify", "--deep", "--strict"])
.arg(&app_path)
.status()
.expect("verify app bundle signature");
assert!(verify_status.success(), "ad-hoc signature should be valid");
let err = verify_codex_app_bundle(&app_path)
.await
.expect_err("valid signature without the OpenAI team should not be trusted");
assert!(
err.to_string()
.contains("failed OpenAI signature verification"),
"unexpected verification error: {err}"
);
}
#[tokio::test]
async fn refuses_to_launch_unsigned_existing_codex_app() {
let temp_dir = tempfile::tempdir().expect("create temp dir");
let app_path = temp_dir.path().join("Codex.app");
write_app_bundle(&app_path, "com.openai.codex");
let err = open_codex_app(&app_path, temp_dir.path())
.await
.expect_err("unsigned existing app should not be launched");
assert!(
err.to_string()
.contains("failed OpenAI signature verification"),
"unexpected launch error: {err}"
);
}
#[test]
fn parses_mount_point_from_tab_separated_hdiutil_output() {
let output = "/dev/disk2s1\tApple_HFS\tCodex\t/Volumes/Codex\n";
assert_eq!(
parse_hdiutil_attach_mount_point(output).as_deref(),
Some("/Volumes/Codex")
);
}
#[test]
fn parses_mount_point_with_spaces() {
let output = "/dev/disk2s1\tApple_HFS\tCodex Installer\t/Volumes/Codex Installer\n";
assert_eq!(
parse_hdiutil_attach_mount_point(output).as_deref(),
Some("/Volumes/Codex Installer")
);
}
#[test]
fn codex_new_thread_url_encodes_workspace_path() {
let url = url::Url::parse(&codex_new_thread_url(Path::new("/tmp/codex workspace/#1")))
.expect("deep link should parse");
assert_eq!(
(
url.scheme().to_string(),
url.host_str().map(str::to_string),
url.path().to_string(),
url.query_pairs().into_owned().collect::<Vec<_>>(),
),
(
"codex".to_string(),
Some("threads".to_string()),
"/new".to_string(),
vec![("path".to_string(), "/tmp/codex workspace/#1".to_string())],
)
);
}
}

View File

@@ -0,0 +1,22 @@
#[cfg(target_os = "macos")]
mod mac;
#[cfg(target_os = "windows")]
mod windows;
/// Run the app install/open logic for the current OS.
#[cfg(target_os = "macos")]
pub async fn run_app_open_or_install(
workspace: std::path::PathBuf,
download_url_override: Option<String>,
) -> anyhow::Result<()> {
mac::run_mac_app_open_or_install(workspace, download_url_override).await
}
/// Run the app install/open logic for the current OS.
#[cfg(target_os = "windows")]
pub async fn run_app_open_or_install(
workspace: std::path::PathBuf,
download_url_override: Option<String>,
) -> anyhow::Result<()> {
windows::run_windows_app_open_or_install(workspace, download_url_override).await
}

View File

@@ -0,0 +1,133 @@
use anyhow::Context as _;
use std::path::Path;
use std::path::PathBuf;
use tokio::process::Command;
const CODEX_WINDOWS_INSTALLER_URL: &str =
"https://get.microsoft.com/installer/download/9PLM9XGG6VKS?cid=website_cta_psi";
const CODEX_MICROSOFT_STORE_WEB_URL: &str = "https://apps.microsoft.com/detail/9plm9xgg6vks";
pub async fn run_windows_app_open_or_install(
workspace: PathBuf,
download_url_override: Option<String>,
) -> anyhow::Result<()> {
let workspace_path = workspace.display().to_string();
let display_workspace = display_workspace_path(&workspace);
if codex_app_is_installed().await? {
eprintln!("Opening workspace {display_workspace} in the Desktop app...");
open_url(&codex_new_thread_url(&workspace_path)).await?;
return Ok(());
}
eprintln!("Desktop app not found; opening Windows installer...");
let download_url = download_url_override
.as_deref()
.unwrap_or(CODEX_WINDOWS_INSTALLER_URL);
if open_url(download_url).await.is_err() && download_url_override.is_none() {
open_url(CODEX_MICROSOFT_STORE_WEB_URL).await?;
}
eprintln!("After installing the Desktop app, open workspace {display_workspace}.");
Ok(())
}
async fn codex_app_is_installed() -> anyhow::Result<bool> {
// This package identity is stable across Codex- and ChatGPT-branded builds.
let output = Command::new("powershell.exe")
.arg("-NoProfile")
.arg("-Command")
.arg(
"Get-StartApps | Where-Object AppID -Like 'OpenAI.Codex_*!App' | Select-Object -First 1 -ExpandProperty AppID",
)
.output()
.await
.context("failed to invoke `powershell.exe`")?;
if !output.status.success() {
return Ok(false);
}
Ok(!String::from_utf8_lossy(&output.stdout).trim().is_empty())
}
async fn open_url(url: &str) -> anyhow::Result<()> {
let status = Command::new("powershell.exe")
.arg("-NoProfile")
.arg("-Command")
.arg("& { param($target) Start-Process -FilePath $target }")
.arg(url)
.status()
.await
.with_context(|| format!("failed to open {url}"))?;
if status.success() {
Ok(())
} else {
anyhow::bail!("failed to open {url} with {status}");
}
}
fn codex_new_thread_url(workspace: &str) -> String {
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
serializer.append_pair("path", workspace);
let query = serializer.finish();
format!("codex://threads/new?{query}")
}
fn display_workspace_path(workspace: &Path) -> String {
let path = workspace.display().to_string();
if let Some(path) = path.strip_prefix(r"\\?\UNC\") {
format!(r"\\{path}")
} else if let Some(path) = path.strip_prefix(r"\\?\") {
path.to_string()
} else {
path
}
}
#[cfg(test)]
mod tests {
use super::codex_new_thread_url;
use super::display_workspace_path;
use pretty_assertions::assert_eq;
use std::path::Path;
#[test]
fn display_workspace_path_removes_windows_extended_prefix() {
assert_eq!(
display_workspace_path(Path::new(r"\\?\C:\Users\fcoury\code\codex")),
r"C:\Users\fcoury\code\codex"
);
}
#[test]
fn display_workspace_path_preserves_unc_prefix() {
assert_eq!(
display_workspace_path(Path::new(r"\\?\UNC\server\share\codex")),
r"\\server\share\codex"
);
}
#[test]
fn display_workspace_path_leaves_regular_paths_unchanged() {
assert_eq!(
display_workspace_path(Path::new(r"C:\Users\fcoury\code\codex")),
r"C:\Users\fcoury\code\codex"
);
}
#[test]
fn codex_new_thread_url_encodes_windows_workspace_path() {
assert_eq!(
codex_new_thread_url(r"C:\Users\akuma\repos\koba"),
r"codex://threads/new?path=C%3A%5CUsers%5Cakuma%5Crepos%5Ckoba"
);
}
#[test]
fn codex_new_thread_url_preserves_verbatim_workspace_path() {
assert_eq!(
codex_new_thread_url(r"\\?\C:\Users\akuma\repos\koba"),
r"codex://threads/new?path=%5C%5C%3F%5CC%3A%5CUsers%5Cakuma%5Crepos%5Ckoba"
);
}
}

4678
codex-rs/cli/src/doctor.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,365 @@
//! Reports app-server daemon state without starting or stopping the daemon.
//!
//! The background-server check is deliberately passive. It reads the daemon
//! state directory, PID files, settings file, and control socket path, then
//! attempts only a bounded initialize probe when a socket already exists. That
//! keeps doctor safe to run while the user is debugging startup or update-loop
//! issues.
use std::io::Read;
use std::num::NonZeroU32;
use std::path::Path;
use codex_core::config::Config;
use serde::Deserialize;
use super::CheckStatus;
use super::DoctorCheck;
const MAX_PROBE_ERROR_CHARS: usize = 120;
const STATE_DIR_NAME: &str = "app-server-daemon";
const SETTINGS_FILE_NAME: &str = "settings.json";
const PID_FILE_NAME: &str = "app-server.pid";
const UPDATE_PID_FILE_NAME: &str = "app-server-updater.pid";
const MAX_SETTINGS_BYTES: u64 = 16 * 1024;
#[derive(Deserialize)]
struct ConfiguredSettings {
updater: Option<ConfiguredUpdater>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ConfiguredUpdater {
auto_update_enabled: Option<bool>,
update_interval_minutes: Option<NonZeroU32>,
}
/// Builds the app-server status row from existing daemon state.
///
/// Missing files are expected for the ephemeral/not-running case and should not
/// be treated as failures. A stale socket is a warning because it can explain
/// client connection problems without proving the daemon itself is broken.
pub(super) async fn background_server_check(config: &Config) -> DoctorCheck {
let mut details = Vec::new();
let state_dir = config.codex_home.join(STATE_DIR_NAME);
details.push(format!("daemon state dir: {}", state_dir.display()));
push_file_detail(
&mut details,
"settings",
&state_dir.join(SETTINGS_FILE_NAME),
);
push_file_detail(&mut details, "pid file", &state_dir.join(PID_FILE_NAME));
push_file_detail(
&mut details,
"update-loop pid file",
&state_dir.join(UPDATE_PID_FILE_NAME),
);
push_file_detail(
&mut details,
"dedicated pid file",
&state_dir.join("daemon.pid"),
);
push_file_detail(
&mut details,
"dedicated update-loop pid file",
&state_dir.join("daemon-updater.pid"),
);
push_configured_updater(&mut details, &state_dir.join(SETTINGS_FILE_NAME));
let socket_path = match codex_app_server::app_server_control_socket_path(&config.codex_home) {
Ok(socket_path) => socket_path,
Err(err) => {
return DoctorCheck::new(
"app_server.status",
"app-server",
CheckStatus::Warning,
"background server socket path could not be resolved",
)
.details(details)
.detail(err.to_string());
}
};
details.push(format!("control socket: {}", socket_path.display()));
let status = socket_status(socket_path.as_path()).await;
details.push(format!("status: {}", status.detail_label()));
if let Some(version_detail) = status.app_server_version_detail() {
details.push(version_detail);
}
details.push(format!("mode: {}", server_mode(&state_dir)));
let mut check = DoctorCheck::new(
"app_server.status",
"app-server",
status.check_status(),
status.summary(),
)
.details(details);
if status.check_status() == CheckStatus::Warning {
check = check.remediation("Run codex app-server daemon version for more details.");
}
check
}
fn push_file_detail(details: &mut Vec<String>, label: &str, path: &Path) {
match std::fs::metadata(path) {
Ok(metadata) if metadata.is_file() => {
details.push(format!("{label}: {} (file)", path.display()));
}
Ok(_) => {
details.push(format!("{label}: {} (not a file)", path.display()));
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
details.push(format!("{label}: {} (missing)", path.display()));
}
Err(err) => details.push(format!("{label}: {} ({err})", path.display())),
}
}
fn push_configured_updater(details: &mut Vec<String>, path: &Path) {
if !path.is_file() {
return;
}
let mut contents = Vec::new();
let read = std::fs::File::open(path)
.and_then(|file| file.take(MAX_SETTINGS_BYTES + 1).read_to_end(&mut contents));
let settings = read
.ok()
.filter(|_| contents.len() as u64 <= MAX_SETTINGS_BYTES)
.and_then(|_| serde_json::from_slice::<ConfiguredSettings>(&contents).ok());
let Some(settings) = settings else {
details.push("configured updater settings: unreadable or invalid".into());
return;
};
if let Some(updater) = settings.updater {
if let Some(enabled) = updater.auto_update_enabled {
details.push(format!(
"automatic updates: {} (configured)",
if enabled { "enabled" } else { "disabled" }
));
}
if let Some(minutes) = updater.update_interval_minutes {
details.push(format!("update interval: {minutes} minutes (configured)"));
}
}
}
fn server_mode(state_dir: &Path) -> &'static str {
if state_dir.join(SETTINGS_FILE_NAME).is_file() {
"persistent"
} else {
"ephemeral"
}
}
enum SocketStatus {
NotRunning,
Running(String),
StaleOrUnreachable(String),
}
impl SocketStatus {
fn check_status(&self) -> CheckStatus {
match self {
Self::NotRunning | Self::Running(_) => CheckStatus::Ok,
Self::StaleOrUnreachable(_) => CheckStatus::Warning,
}
}
fn summary(&self) -> &'static str {
match self {
Self::NotRunning => "background server is not running",
Self::Running(_) => "background server is running",
Self::StaleOrUnreachable(_) => "background server socket is stale or unreachable",
}
}
fn detail_label(&self) -> &'static str {
match self {
Self::NotRunning => "not running",
Self::Running(_) => "running",
Self::StaleOrUnreachable(_) => "stale or unreachable",
}
}
fn app_server_version_detail(&self) -> Option<String> {
match self {
Self::NotRunning => None,
Self::Running(app_server_version) => {
Some(format!("app-server version: {app_server_version}"))
}
Self::StaleOrUnreachable(error) => {
Some(format!("app-server version: unavailable ({error})"))
}
}
}
}
async fn socket_status(socket_path: &Path) -> SocketStatus {
if !socket_path.exists() {
return SocketStatus::NotRunning;
}
match codex_app_server_daemon::probe_app_server_version(socket_path).await {
Ok(app_server_version) => SocketStatus::Running(app_server_version),
Err(err) => SocketStatus::StaleOrUnreachable(concise_probe_error(&err, socket_path)),
}
}
fn concise_probe_error(err: &anyhow::Error, socket_path: &Path) -> String {
let socket_path = socket_path.display().to_string();
let message = err
.to_string()
.replace(&socket_path, "control socket")
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
if message.is_empty() {
return "unknown error".to_string();
}
let mut chars = message.chars();
let truncated = chars
.by_ref()
.take(MAX_PROBE_ERROR_CHARS)
.collect::<String>();
if chars.next().is_some() {
format!("{truncated}...")
} else {
message
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use codex_core::config::ConfigBuilder;
use pretty_assertions::assert_eq;
use super::*;
async fn test_config(codex_home: PathBuf) -> Config {
ConfigBuilder::default()
.codex_home(codex_home)
.build()
.await
.expect("config")
}
fn create_socket_placeholder(config: &Config) {
let socket_path = codex_app_server::app_server_control_socket_path(&config.codex_home)
.expect("socket path");
std::fs::create_dir_all(socket_path.parent().expect("socket parent"))
.expect("create socket dir");
std::fs::write(socket_path, "").expect("create socket placeholder");
}
#[tokio::test]
async fn not_running_background_server_stays_ok_without_version() {
let temp = tempfile::tempdir().expect("tempdir");
let config = test_config(temp.path().to_path_buf()).await;
let check = background_server_check(&config).await;
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(check.summary, "background server is not running");
assert!(check.details.contains(&"status: not running".to_string()));
assert!(
!check
.details
.iter()
.any(|detail| detail.starts_with("app-server version:"))
);
}
#[test]
fn running_background_server_reports_app_server_version() {
let status = SocketStatus::Running("1.2.3".to_string());
assert_eq!(status.check_status(), CheckStatus::Ok);
assert_eq!(status.summary(), "background server is running");
assert_eq!(status.detail_label(), "running");
assert_eq!(
status.app_server_version_detail(),
Some("app-server version: 1.2.3".to_string())
);
}
#[tokio::test]
async fn failed_version_probe_reports_unavailable() {
let temp = tempfile::tempdir().expect("tempdir");
let config = test_config(temp.path().to_path_buf()).await;
create_socket_placeholder(&config);
let check = background_server_check(&config).await;
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(
check.summary,
"background server socket is stale or unreachable"
);
assert!(
check
.details
.contains(&"status: stale or unreachable".to_string())
);
assert!(
check
.details
.iter()
.any(|detail| detail.starts_with("app-server version: unavailable ("))
);
}
#[tokio::test]
async fn configured_updates_and_missing_updater_record_are_visible() {
let temp = tempfile::tempdir().expect("tempdir");
let state_dir = temp.path().join(STATE_DIR_NAME);
std::fs::create_dir(&state_dir).expect("state dir");
std::fs::write(
state_dir.join(SETTINGS_FILE_NAME),
r#"{"updater":{"autoUpdateEnabled":false,"updateIntervalMinutes":90}}"#,
)
.expect("settings");
let config = test_config(temp.path().to_path_buf()).await;
let check = background_server_check(&config).await;
let details = check
.details
.iter()
.filter(|detail| {
detail.starts_with("automatic updates:")
|| detail.starts_with("update interval:")
|| detail.starts_with("update-loop pid file:")
|| detail.starts_with("dedicated")
})
.map(|detail| {
detail
.replace(&temp.path().display().to_string(), "CODEX_HOME")
.replace('\\', "/")
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!("configured_updater", details);
}
#[test]
fn invalid_settings_are_not_reported_as_effective() {
let temp = tempfile::tempdir().expect("tempdir");
let path = temp.path().join(SETTINGS_FILE_NAME);
for contents in [
r#"{"updater":{"autoUpdateEnabled":"no"}}"#,
r#"{"updater":{"updateIntervalMinutes":0}}"#,
] {
std::fs::write(&path, contents).expect("settings");
let mut details = Vec::new();
push_configured_updater(&mut details, &path);
insta::allow_duplicates! {
insta::assert_snapshot!(details.join("\n"), @"configured updater settings: unreadable or invalid");
}
}
}
}

View File

@@ -0,0 +1,320 @@
use std::cmp::Reverse;
use std::env;
use std::fs;
use std::io;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
use std::time::SystemTime;
use chrono::DateTime;
use chrono::FixedOffset;
use chrono::Utc;
use super::CheckStatus;
use super::DoctorCheck;
#[cfg(target_os = "macos")]
mod macos_security;
pub(super) mod platform;
#[cfg(any(target_os = "windows", test))]
mod windows_security;
const MAX_DIRECTORY_ENTRIES: usize = 256;
const MAX_LOG_FILES: usize = 64;
const MAX_SESSION_LOG_FILES: usize = 8;
const MAX_LOG_SEGMENT_BYTES: u64 = 10 * 1024 * 1024;
const HANDSHAKE_CHECK_ID: &str = "desktop.app_server.handshake";
pub(super) struct DesktopDiagnostics {
pub(super) checks: Vec<DoctorCheck>,
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(super) application: Option<platform::InstalledApp>,
}
struct DesktopLog {
path: PathBuf,
session_id: String,
process_id: u32,
modified: SystemTime,
}
struct HandshakeEvent {
timestamp: DateTime<FixedOffset>,
outcome: HandshakeOutcome,
websocket: bool,
}
enum HandshakeOutcome {
Success,
Failure,
}
enum DesktopLogEvent {
ConnectionContext { local_websocket: bool },
Handshake(HandshakeEvent),
}
pub(super) async fn collect() -> Option<DesktopDiagnostics> {
let application = match platform::installed_app().await {
Ok(Some(application)) => application,
Ok(None) => return None,
Err(_) => {
return Some(DesktopDiagnostics {
checks: vec![
unavailable(
"desktop.app.version",
"the desktop application installation could not be inspected",
),
#[cfg(target_os = "windows")]
windows_security::collect().await,
],
#[cfg(any(target_os = "macos", target_os = "windows"))]
application: None,
});
}
};
let directory = desktop_log_root(application.identity);
let (running, handshake) = match &directory {
Some(root) => inspect_desktop_session(
&root.join(Utc::now().format("%Y/%m/%d").to_string()),
|pid| platform::application_running(&application, pid),
),
None => (false, stopped_desktop_check()),
};
let log_directory = directory
.as_deref()
.map_or_else(|| "unavailable".to_string(), redacted_path);
let application_check = platform::desktop_check(
"desktop.app.version",
CheckStatus::Ok,
"the desktop application is installed",
)
.detail(format!("version: {}", application.version))
.detail(format!("running: {running}"))
.detail(format!("log directory: {log_directory}"));
Some(DesktopDiagnostics {
checks: vec![
application_check,
handshake,
#[cfg(target_os = "macos")]
macos_security::collect(&application.bundle).await,
#[cfg(target_os = "windows")]
windows_security::collect().await,
],
#[cfg(any(target_os = "macos", target_os = "windows"))]
application: Some(application),
})
}
pub(super) fn inspect_desktop_session(
directory: &Path,
application_running: impl Fn(u32) -> bool,
) -> (bool, DoctorCheck) {
let logs = discover_desktop_logs(directory);
let Some(session) = logs.iter().find(|log| application_running(log.process_id)) else {
return (false, stopped_desktop_check());
};
let check = latest_session_handshake(&logs, &session.session_id).map_or_else(
|| {
platform::desktop_check(
HANDSHAKE_CHECK_ID,
CheckStatus::Ok,
"no desktop app-server handshake was recorded",
)
},
|event| event.outcome.into_check(),
);
(true, check)
}
fn desktop_log_root(identity: &str) -> Option<PathBuf> {
let root = match env::consts::OS {
"macos" => PathBuf::from(env::var_os("HOME")?)
.join("Library/Logs")
.join(identity),
"windows" => {
let local = env::var_os("LOCALAPPDATA").map(PathBuf::from).or_else(|| {
env::var_os("USERPROFILE").map(|home| PathBuf::from(home).join("AppData/Local"))
})?;
local.join("Codex/Logs")
}
_ => return None,
};
Some(root)
}
fn discover_desktop_logs(directory: &Path) -> Vec<DesktopLog> {
let Ok(entries) = fs::read_dir(directory) else {
return Vec::new();
};
let mut logs = entries
.take(MAX_DIRECTORY_ENTRIES)
.filter_map(Result::ok)
.filter_map(DesktopLog::from_entry)
.collect::<Vec<_>>();
logs.sort_unstable_by_key(|log| Reverse(log.modified));
logs.truncate(MAX_LOG_FILES);
logs
}
fn latest_session_handshake(logs: &[DesktopLog], session_id: &str) -> Option<HandshakeEvent> {
let mut latest: Option<HandshakeEvent> = None;
for log in logs
.iter()
.filter(|log| log.session_id == session_id)
.take(MAX_SESSION_LOG_FILES)
{
let Ok(contents) = read_log_segment(&log.path) else {
continue;
};
let mut local_websocket = false;
for line in String::from_utf8_lossy(&contents).lines() {
match DesktopLogEvent::parse(line) {
Some(DesktopLogEvent::ConnectionContext {
local_websocket: local,
}) => {
local_websocket = local;
}
Some(DesktopLogEvent::Handshake(event))
if (!event.websocket || local_websocket)
&& latest
.as_ref()
.is_none_or(|current| event.timestamp >= current.timestamp) =>
{
latest = Some(event);
}
_ => {}
}
}
}
latest
}
impl DesktopLog {
fn from_entry(entry: fs::DirEntry) -> Option<Self> {
let metadata = entry.metadata().ok()?;
if !metadata.is_file() {
return None;
}
let name = entry.file_name();
let name = name
.to_str()?
.strip_prefix("codex-desktop-")?
.strip_suffix(".log")?;
let (session_and_pid, _) = name.split_once("-t")?;
let (session_id, process_id) = session_and_pid.rsplit_once('-')?;
Some(Self {
path: entry.path(),
session_id: session_id.to_string(),
process_id: process_id.parse().ok().filter(|pid| *pid > 0)?,
modified: metadata.modified().ok()?,
})
}
}
fn read_log_segment(path: &Path) -> io::Result<Vec<u8>> {
let mut contents = Vec::new();
fs::File::open(path)?
.take(MAX_LOG_SEGMENT_BYTES)
.read_to_end(&mut contents)?;
Ok(contents)
}
impl DesktopLogEvent {
fn parse(line: &str) -> Option<Self> {
let (timestamp, line) = line.split_once(' ')?;
let timestamp = DateTime::parse_from_rfc3339(timestamp).ok()?;
let (_, message) = line.split_once(" [AppServerConnection] ")?;
if let Some(fields) = message
.strip_prefix("Starting app-server connection ")
.or_else(|| message.strip_prefix("app_server_connection.state_changed "))
{
return Some(Self::ConnectionContext {
local_websocket: log_field(fields, "hostId") == Some("local")
&& log_field(fields, "transport") == Some("websocket"),
});
}
let fields = message.strip_prefix("initialize_handshake_result ")?;
let outcome = match log_field(fields, "outcome")? {
"success" => HandshakeOutcome::Success,
"failure" => HandshakeOutcome::Failure,
_ => return None,
};
let websocket = match log_field(fields, "transportKind")? {
"stdio" => false,
"websocket" => true,
_ => return None,
};
Some(Self::Handshake(HandshakeEvent {
timestamp,
outcome,
websocket,
}))
}
}
impl HandshakeOutcome {
fn into_check(self) -> DoctorCheck {
let (status, summary) = match self {
Self::Success => (
CheckStatus::Ok,
"the desktop app-server initialized successfully",
),
Self::Failure => (
CheckStatus::Fail,
"the desktop app-server failed to initialize",
),
};
platform::desktop_check(HANDSHAKE_CHECK_ID, status, summary)
}
}
fn log_field<'a>(fields: &'a str, name: &str) -> Option<&'a str> {
fields.split_whitespace().rev().find_map(|field| {
let (key, value) = field.split_once('=')?;
(key == name).then_some(value)
})
}
fn stopped_desktop_check() -> DoctorCheck {
platform::desktop_check(
HANDSHAKE_CHECK_ID,
CheckStatus::Ok,
"the desktop application is not running",
)
}
fn unavailable(id: &'static str, summary: &'static str) -> DoctorCheck {
platform::desktop_check(id, CheckStatus::Warning, summary)
.remediation("restore desktop diagnostic access and rerun codex doctor")
}
fn redacted_path(path: &Path) -> String {
for variable in ["HOME", "USERPROFILE"] {
if let Some(home) = env::var_os(variable)
&& let Ok(relative) = path.strip_prefix(Path::new(&home))
{
return Path::new("$HOME").join(relative).display().to_string();
}
}
path.file_name()
.unwrap_or(path.as_os_str())
.to_string_lossy()
.into_owned()
}

View File

@@ -0,0 +1,236 @@
use super::super::CheckStatus;
use super::super::DoctorCheck;
use super::platform::desktop_check;
use std::io;
use std::path::Path;
use std::process::Output;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::time::timeout;
const PROBE_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_OUTPUT_BYTES: usize = 256 * 1024;
const SECURITY_LOG_PREDICATE: &str = concat!(
"(process == 'syspolicyd' OR process == 'AppleSystemPolicy' ",
"OR process BEGINSWITH 'XProtect' OR subsystem BEGINSWITH 'com.apple.syspolicy' ",
"OR subsystem CONTAINS[c] 'XProtect' ",
"OR subsystem == 'com.apple.security.assessment') AND ",
"(eventMessage CONTAINS[c] 'codex' OR eventMessage CONTAINS[c] 'chatgpt' ",
"OR eventMessage CONTAINS[c] '.plugin-appserver' ",
"OR eventMessage CONTAINS[c] '100024' OR eventMessage CONTAINS[c] 'EMFILE' ",
"OR eventMessage CONTAINS[c] 'ENFILE' ",
"OR eventMessage CONTAINS[c] 'too many open files' ",
"OR eventMessage CONTAINS[c] 'Unexpected Xprotect assessment')"
);
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
enum Evidence {
Clear,
Audit,
Exhausted,
Blocked,
Malware,
Unavailable,
}
pub(super) async fn collect(bundle: &Path) -> DoctorCheck {
let (gatekeeper, events) = tokio::join!(inspect_gatekeeper(bundle), inspect_security_events());
enforcement_check(gatekeeper, events)
}
async fn inspect_gatekeeper(bundle: &Path) -> Evidence {
let mut command = Command::new("/usr/sbin/spctl");
command
.args(["--assess", "--type", "execute", "--verbose=2"])
.arg(bundle);
classify_gatekeeper(run_command(&mut command).await.as_ref())
}
fn classify_gatekeeper(output: Option<&Output>) -> Evidence {
let Some(output) = output.filter(|output| !is_truncated(output)) else {
return Evidence::Unavailable;
};
if output.status.success() {
return Evidence::Clear;
}
let error = String::from_utf8_lossy(&output.stderr).to_ascii_lowercase();
if error.contains("rejected") || error.contains("no usable signature") {
Evidence::Blocked
} else {
Evidence::Unavailable
}
}
async fn inspect_security_events() -> Evidence {
let mut command = Command::new("/usr/bin/log");
command.args([
"show",
"--last",
"30m",
"--info",
"--style",
"compact",
"--predicate",
SECURITY_LOG_PREDICATE,
]);
let Some(output) = run_command(&mut command)
.await
.filter(|output| output.status.success())
else {
return Evidence::Unavailable;
};
let evidence = classify_security_events(&String::from_utf8_lossy(&output.stdout));
if is_truncated(&output) && evidence < Evidence::Exhausted {
Evidence::Unavailable
} else {
evidence
}
}
fn classify_security_events(output: &str) -> Evidence {
let mut evidence = Evidence::Clear;
for line in output.lines().map(str::to_ascii_lowercase) {
let contains = |values: &[&str]| values.iter().any(|value| line.contains(value));
if !contains(&[
"com.openai.codex",
"codex.app",
"chatgpt.app",
".plugin-appserver",
"codex-command-runner",
]) || contains(&["not blocked", "not denied"])
{
continue;
}
let event = if contains(&["100024", "emfile", "enfile", "too many open files"]) {
Evidence::Exhausted
} else if contains(&["would block", "would deny"]) {
Evidence::Audit
} else if contains(&[
"xp_malware_detected",
"xp_malware_remediated",
"malware detected",
"malware blocked",
"malware removed",
"remediat",
]) {
Evidence::Malware
} else if contains(&[
"blocked",
"denied",
"rejected",
"notarization failed",
"signature invalid",
"execution prevented",
"unexpected xprotect assessment",
"damaged and",
]) {
Evidence::Blocked
} else if contains(&["audit"]) {
Evidence::Audit
} else {
Evidence::Clear
};
evidence = evidence.max(event);
}
evidence
}
fn enforcement_check(gatekeeper: Evidence, events: Evidence) -> DoctorCheck {
let id = "desktop.security.enforcement";
let (status, summary, remedy) = if events == Evidence::Malware {
(
CheckStatus::Fail,
"macos XProtect blocked or remediated the desktop application",
"collect the XProtect detection and ask your security administrator to review the official Codex installation",
)
} else if gatekeeper == Evidence::Blocked {
(
CheckStatus::Fail,
"macos gatekeeper rejected the desktop application",
"ask your security administrator to review the application policy",
)
} else if events == Evidence::Blocked {
(
CheckStatus::Fail,
"a recent macos security event blocked the desktop application",
"ask your security administrator to review the matching prevention event",
)
} else if events == Evidence::Exhausted {
(
CheckStatus::Warning,
"macos system-policy diagnostics indicate file descriptor exhaustion",
"restart your Mac, retry Codex once, and contact support if the problem returns",
)
} else if events == Evidence::Audit {
(
CheckStatus::Warning,
"recent desktop security events are audit-only",
"ask your security administrator to verify the application policy",
)
} else if gatekeeper == Evidence::Unavailable {
(
CheckStatus::Warning,
"the desktop security assessment was unavailable",
"check access to macos gatekeeper diagnostics",
)
} else if events == Evidence::Unavailable {
(
CheckStatus::Warning,
"recent macos security enforcement history was unavailable",
"check access to macos unified security logs and rerun codex doctor",
)
} else {
return desktop_check(
id,
CheckStatus::Ok,
"the desktop application passed available macos security assessments",
)
.detail("gatekeeper: accepted");
};
desktop_check(id, status, summary).remediation(remedy)
}
fn is_truncated(output: &Output) -> bool {
output.stdout.len() > MAX_OUTPUT_BYTES || output.stderr.len() > MAX_OUTPUT_BYTES
}
async fn run_command(command: &mut Command) -> Option<Output> {
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = command.spawn().ok()?;
let (stdout, stderr) = (child.stdout.take()?, child.stderr.take()?);
timeout(PROBE_TIMEOUT, async {
let (stdout, stderr, status) =
tokio::join!(read_bounded(stdout), read_bounded(stderr), child.wait());
Some(Output {
status: status.ok()?,
stdout: stdout.ok()?,
stderr: stderr.ok()?,
})
})
.await
.ok()
.flatten()
}
async fn read_bounded<R: AsyncRead + Unpin>(mut reader: R) -> io::Result<Vec<u8>> {
let mut bytes = Vec::new();
(&mut reader)
.take(MAX_OUTPUT_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.await?;
if bytes.len() > MAX_OUTPUT_BYTES {
tokio::io::copy(&mut reader, &mut tokio::io::sink()).await?;
}
Ok(bytes)
}
#[cfg(test)]
#[path = "macos_security_tests.rs"]
mod tests;

View File

@@ -0,0 +1,67 @@
use super::CheckStatus;
use super::Evidence;
use super::classify_gatekeeper;
use super::classify_security_events;
use super::enforcement_check;
use pretty_assertions::assert_eq;
use std::os::unix::process::ExitStatusExt;
use std::process::ExitStatus;
use std::process::Output;
#[test]
fn only_matching_enforced_apple_security_events_are_failures() {
for (event, expected) in [
("denied com.openai.codex", Evidence::Blocked),
(
"denied /Applications/Codex.app/Contents/MacOS/Codex",
Evidence::Blocked,
),
("malware detected ChatGPT.app", Evidence::Malware),
("audit token blocked ChatGPT.app", Evidence::Blocked),
(
"audit token XP_MALWARE_DETECTED ChatGPT.app",
Evidence::Malware,
),
("XP_MALWARE_REMEDIATED ChatGPT.app", Evidence::Malware),
("denied .plugin-appserver", Evidence::Blocked),
("audit would block ChatGPT.app", Evidence::Audit),
("OSStatus 100024 ChatGPT.app", Evidence::Exhausted),
("not blocked ChatGPT.app", Evidence::Clear),
("denied EMFILE com.example.other", Evidence::Clear),
("EMFILE\nmalware detected ChatGPT.app", Evidence::Malware),
] {
assert_eq!(classify_security_events(event), expected, "{event}");
}
}
#[test]
fn gatekeeper_failures_require_actionable_security_evidence() {
for (message, expected) in [
("ChatGPT.app: rejected", Evidence::Blocked),
("operation not permitted", Evidence::Unavailable),
] {
let output = Output {
status: ExitStatus::from_raw(1 << 8),
stdout: Vec::new(),
stderr: message.as_bytes().to_vec(),
};
assert_eq!(classify_gatekeeper(Some(&output)), expected);
}
}
#[test]
fn exhaustion_and_unavailable_history_have_actionable_warnings() {
for (events, remedy) in [
(Evidence::Exhausted, "restart"),
(Evidence::Unavailable, "unified security logs"),
] {
let check = enforcement_check(Evidence::Clear, events);
assert_eq!(check.status, CheckStatus::Warning);
assert!(
check
.remediation
.as_deref()
.is_some_and(|value| value.contains(remedy))
);
}
}

View File

@@ -0,0 +1,283 @@
#[cfg(target_os = "macos")]
use std::ffi::CStr;
#[cfg(target_os = "macos")]
use std::ffi::OsStr;
#[cfg(target_os = "macos")]
use std::fs;
#[cfg(target_os = "macos")]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "windows")]
use std::os::windows::io::AsRawHandle;
#[cfg(target_os = "windows")]
use std::os::windows::io::FromRawHandle;
#[cfg(target_os = "windows")]
use std::os::windows::io::OwnedHandle;
#[cfg(target_os = "macos")]
use std::path::Path;
#[cfg(target_os = "macos")]
use std::path::PathBuf;
#[cfg(target_os = "macos")]
use std::process::Stdio;
#[cfg(target_os = "macos")]
use std::time::Duration;
#[cfg(target_os = "macos")]
use serde_json::Value;
#[cfg(target_os = "macos")]
use tokio::process::Command;
#[cfg(target_os = "macos")]
use tokio::time::timeout;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Storage::Packaging::Appx::FindPackagesByPackageFamily;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Storage::Packaging::Appx::GetPackageFamilyName;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Storage::Packaging::Appx::PACKAGE_FILTER_HEAD;
#[cfg(target_os = "windows")]
use windows_sys::Win32::System::Threading::OpenProcess;
#[cfg(target_os = "windows")]
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
use super::super::CheckStatus;
use super::super::DoctorCheck;
pub(in crate::doctor) struct InstalledApp {
pub(in crate::doctor) identity: &'static str,
pub(in crate::doctor) version: String,
#[cfg(target_os = "windows")]
package_family: &'static str,
#[cfg(target_os = "macos")]
pub(in crate::doctor) bundle: PathBuf,
#[cfg(target_os = "macos")]
pub(in crate::doctor) build: u64,
}
#[derive(Clone, Copy, Debug)]
pub(in crate::doctor) struct DiscoveryError;
pub(super) async fn installed_app() -> Result<Option<InstalledApp>, DiscoveryError> {
#[cfg(target_os = "windows")]
{
installed_windows_app()
}
#[cfg(target_os = "macos")]
{
installed_macos_app().await
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
{
Ok(None)
}
}
#[cfg(target_os = "macos")]
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
process_executable_path(candidate_pid)
.is_some_and(|path| path.starts_with(application.bundle.join("Contents/MacOS")))
}
#[cfg(target_os = "macos")]
fn process_executable_path(pid: u32) -> Option<PathBuf> {
let pid = i32::try_from(pid).ok()?;
let mut buffer = [0_u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
let result =
unsafe { libc::proc_pidpath(pid, buffer.as_mut_ptr().cast(), buffer.len() as u32) };
if result <= 0 {
return None;
}
let executable = CStr::from_bytes_until_nul(&buffer).ok()?;
Some(PathBuf::from(OsStr::from_bytes(executable.to_bytes())))
}
#[cfg(target_os = "windows")]
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
process_package_family(candidate_pid).as_deref() == Some(application.package_family)
}
#[cfg(target_os = "windows")]
fn process_package_family(pid: u32) -> Option<String> {
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
if handle.is_null() {
return None;
}
let process = unsafe { OwnedHandle::from_raw_handle(handle) };
let mut family_length = 0;
let result = unsafe {
GetPackageFamilyName(
process.as_raw_handle(),
&mut family_length,
std::ptr::null_mut(),
)
};
if result != ERROR_INSUFFICIENT_BUFFER || family_length == 0 {
return None;
}
let mut family = vec![0_u16; family_length as usize];
let result = unsafe {
GetPackageFamilyName(
process.as_raw_handle(),
&mut family_length,
family.as_mut_ptr(),
)
};
if result != ERROR_SUCCESS {
return None;
}
let end = family.iter().position(|value| *value == 0)?;
String::from_utf16(&family[..end]).ok()
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
pub(super) fn application_running(_application: &InstalledApp, _candidate_pid: u32) -> bool {
false
}
pub(super) fn desktop_check(
id: impl Into<String>,
status: CheckStatus,
summary: impl Into<String>,
) -> DoctorCheck {
DoctorCheck::new(id, "desktop", status, summary)
}
#[cfg(target_os = "windows")]
fn installed_windows_app() -> Result<Option<InstalledApp>, DiscoveryError> {
const PACKAGE_FAMILY: &str = "OpenAI.Codex_2p2nqsd0c76g0";
let family = PACKAGE_FAMILY
.encode_utf16()
.chain(std::iter::once(0))
.collect::<Vec<_>>();
let mut count = 0;
let mut length = 0;
let result = unsafe {
FindPackagesByPackageFamily(
family.as_ptr(),
PACKAGE_FILTER_HEAD,
&mut count,
std::ptr::null_mut(),
&mut length,
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
if result == ERROR_SUCCESS && count == 0 {
return Ok(None);
}
if result != ERROR_INSUFFICIENT_BUFFER {
return Err(DiscoveryError);
}
let mut names = vec![std::ptr::null_mut(); count as usize];
let mut buffer = vec![0_u16; length as usize];
let result = unsafe {
FindPackagesByPackageFamily(
family.as_ptr(),
PACKAGE_FILTER_HEAD,
&mut count,
names.as_mut_ptr(),
&mut length,
buffer.as_mut_ptr(),
std::ptr::null_mut(),
)
};
if result != ERROR_SUCCESS {
return Err(DiscoveryError);
}
if count == 0 {
return Ok(None);
}
let end = buffer
.iter()
.position(|value| *value == 0)
.ok_or(DiscoveryError)?;
let package = String::from_utf16(&buffer[..end]).map_err(|_| DiscoveryError)?;
let version = package
.strip_prefix("OpenAI.Codex_")
.and_then(|name| name.split('_').next())
.filter(|version| {
version
.split('.')
.all(|part| !part.is_empty() && part.bytes().all(|digit| digit.is_ascii_digit()))
})
.ok_or(DiscoveryError)?;
Ok(Some(InstalledApp {
identity: "OpenAI.Codex",
version: version.to_string(),
package_family: PACKAGE_FAMILY,
}))
}
#[cfg(target_os = "macos")]
async fn installed_macos_app() -> Result<Option<InstalledApp>, DiscoveryError> {
let applications = std::iter::once(PathBuf::from("/Applications"))
.chain(std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Applications")))
.flat_map(|directory| {
["ChatGPT.app", "Codex.app"]
.into_iter()
.map(move |application| directory.join(application))
});
for bundle in applications {
match fs::metadata(&bundle) {
Ok(metadata) if metadata.is_dir() => {}
Ok(_) => continue,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(_) => return Err(DiscoveryError),
}
if let Some(application) = inspect_macos_bundle(&bundle).await? {
return Ok(Some(application));
}
}
Ok(None)
}
#[cfg(target_os = "macos")]
pub(in crate::doctor) async fn inspect_macos_bundle(
bundle: &Path,
) -> Result<Option<InstalledApp>, DiscoveryError> {
let mut command = Command::new("/usr/bin/plutil");
command
.args(["-convert", "json", "-o", "-"])
.arg(bundle.join("Contents/Info.plist"))
.stdin(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
let output = timeout(Duration::from_secs(5), command.output())
.await
.map_err(|_| DiscoveryError)?
.map_err(|_| DiscoveryError)?;
if !output.status.success() || output.stdout.len() > 64 * 1024 {
return Err(DiscoveryError);
}
let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|_| DiscoveryError)?;
if metadata.get("CFBundleIdentifier").and_then(Value::as_str) != Some("com.openai.codex") {
return Ok(None);
}
let version = metadata
.get("CFBundleShortVersionString")
.or_else(|| metadata.get("CFBundleVersion"))
.and_then(Value::as_str)
.ok_or(DiscoveryError)?;
let build = metadata
.get("CFBundleVersion")
.and_then(Value::as_str)
.and_then(|value| value.parse().ok())
.ok_or(DiscoveryError)?;
Ok(Some(InstalledApp {
identity: "com.openai.codex",
version: version.to_string(),
bundle: bundle.to_path_buf(),
build,
}))
}

View File

@@ -0,0 +1,232 @@
use std::env;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::time::timeout;
use super::super::CheckStatus;
use super::super::DoctorCheck;
use super::platform::desktop_check;
const MAX_EVENTS_PER_CHANNEL: usize = 256;
const MAX_RENDERED_EVENTS: usize = 16;
const MAX_EVENT_OUTPUT_BYTES: usize = 2 * 1024 * 1024;
type Channel = (&'static str, &'static str, &'static [u32]);
type Evidence = (CheckStatus, String);
const CHANNELS: [Channel; 5] = [
(
"microsoft_defender",
"Microsoft-Windows-Windows Defender/Operational",
&[
1006, 1007, 1116, 1117, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128,
],
),
(
"applocker",
"Microsoft-Windows-AppLocker/EXE and DLL",
&[8003, 8004],
),
(
"applocker",
"Microsoft-Windows-AppLocker/Packaged app-Execution",
&[8021, 8022],
),
(
"applocker",
"Microsoft-Windows-AppLocker/MSI and Script",
&[8006, 8007],
),
(
"windows_app_control",
"Microsoft-Windows-CodeIntegrity/Operational",
&[3076, 3077],
),
];
pub(super) async fn collect() -> DoctorCheck {
let Some(system_root) = env::var_os("SystemRoot") else {
return classify(&[]);
};
let wevtutil = Path::new(&system_root).join("System32/wevtutil.exe");
let mut channels = Vec::with_capacity(CHANNELS.len());
for pair in CHANNELS.chunks(/*chunk_size*/ 2) {
let first = query_channel(&wevtutil, pair[0]);
if let Some(second) = pair.get(/*index*/ 1) {
let (first, second) = tokio::join!(first, query_channel(&wevtutil, *second));
channels.extend([first, second]);
} else {
channels.push(first.await);
}
}
classify(&channels)
}
async fn query_channel(wevtutil: &Path, channel: Channel) -> Option<Vec<Evidence>> {
let events = channel
.2
.iter()
.map(|id| format!("EventID={id}"))
.collect::<Vec<_>>()
.join(" or ");
let mut child = Command::from(codex_utils_process::background_command(wevtutil))
.args(["qe", channel.1])
.arg(format!(
"/q:*[System[({events}) and TimeCreated[timediff(@SystemTime) <= 604800000]]]"
))
.arg(format!("/c:{MAX_EVENTS_PER_CHANNEL}"))
.args(["/rd:true", "/f:xml"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.ok()?;
let mut output = Vec::new();
let status = timeout(Duration::from_secs(10), async {
let mut reader = child.stdout.take()?.take(MAX_EVENT_OUTPUT_BYTES as u64 + 1);
reader.read_to_end(&mut output).await.ok()?;
if output.len() > MAX_EVENT_OUTPUT_BYTES {
return None;
}
child.wait().await.ok()
})
.await
.ok()
.flatten()?;
status
.success()
.then(|| parse_events(&String::from_utf8_lossy(&output), channel))
}
fn parse_events(xml: &str, (source, _, ids): Channel) -> Vec<Evidence> {
xml.split("</Event>")
.take(MAX_EVENTS_PER_CHANNEL)
.filter_map(|event| {
let id = element(event, "EventID")?.parse().ok()?;
if !ids.contains(&id) {
return None;
}
let target = event
.split("<Data")
.skip(/*n*/ 1)
.filter_map(|data| data.split_once('>')?.1.split_once("</Data>").map(|v| v.0))
.chain(
["FilePath", "FileName", "Image", "PackageName", "PackageFamilyName"]
.into_iter()
.filter_map(|name| element(event, name)),
)
.find_map(event_target)?;
let timestamp = event.split_once("SystemTime=\"")?.1.split_once('"')?.0;
let (status, action) = match id {
1121 | 1123 | 1126 | 1127 | 8004 | 8007 | 8022 | 3077 => {
(CheckStatus::Fail, "blocked")
}
1122 | 1124 | 1125 | 1128 | 8003 | 8006 | 8021 | 3076 => {
(CheckStatus::Warning, "audited")
}
1006 | 1116 => (CheckStatus::Warning, "detected"),
1007 | 1117 => defender_action(event),
_ => return None,
};
Some((
status,
format!(
"source: {source}; event: {id}; target: {target}; action: {action}; time: {timestamp}"
),
))
})
.collect()
}
fn event_target(value: &str) -> Option<&'static str> {
let value = value.to_ascii_lowercase();
let parts = value.split(['\\', '/']).map(str::trim).collect::<Vec<_>>();
let name = *parts.last()?;
let package = parts.iter().any(|part| part.starts_with("openai.codex_"));
let trusted = package || parts.windows(2).any(|pair| pair == ["openai", "codex"]);
match name {
"codex-windows-sandbox-setup.exe" => Some("sandbox_setup"),
"codex-command-runner.exe" => Some("command_runner"),
"codex.exe" => Some("codex"),
"codex-desktop.exe" => Some("codex_desktop"),
"chatgpt.exe" | "electron.exe" if trusted => Some("codex_desktop"),
"rg.exe" if trusted => Some("ripgrep"),
_ if package => Some("codex_desktop_package"),
_ => None,
}
}
fn defender_action(event: &str) -> (CheckStatus, &'static str) {
let action = [
"Action Name",
"ActionName",
"Action",
"Action ID",
"ActionID",
]
.into_iter()
.find_map(|name| data_value(event, name))
.or_else(|| element(event, "ActionName"))
.unwrap_or_default()
.to_ascii_lowercase();
match action.as_str() {
"quarantine" | "2" => (CheckStatus::Fail, "quarantined"),
"clean" | "remove" | "block" | "1" | "3" | "10" => (CheckStatus::Fail, "blocked"),
"allow" | "ignore" | "none" | "no action" | "user defined" | "6" | "8" | "9" | "11" => {
(CheckStatus::Ok, "allowed")
}
_ => (CheckStatus::Warning, "detected"),
}
}
fn classify(channels: &[Option<Vec<Evidence>>]) -> DoctorCheck {
let visible = channels.iter().any(Option::is_some);
let mut status = if visible {
CheckStatus::Ok
} else {
CheckStatus::Warning
};
let mut details = Vec::new();
for (event_status, detail) in channels.iter().flatten().flatten() {
status = status.max(*event_status);
if details.len() < MAX_RENDERED_EVENTS {
details.push(detail.clone());
}
}
let summary = match (status, visible) {
(CheckStatus::Ok, _) if channels.contains(&None) => "security event coverage is incomplete",
(CheckStatus::Ok, _) => "no locally visible recent Codex security enforcement was found",
(CheckStatus::Warning, false) => "security event channels could not be inspected",
(CheckStatus::Warning, true) => "recent Codex security audit or detection requires review",
(CheckStatus::Fail, _) => "endpoint security blocked or quarantined a Codex executable",
};
let mut check = desktop_check("desktop.security.enforcement", status, summary).details(details);
if status != CheckStatus::Ok {
check = check.remediation(
"ask your organization's security administrator to review endpoint security events and the approved Codex application policy",
);
}
check
}
fn element<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
let body = xml.split_once(&format!("<{name}"))?.1.split_once('>')?.1;
Some(body.split_once(&format!("</{name}>"))?.0.trim())
}
fn data_value<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
let body = xml
.split_once(&format!("Name=\"{name}\""))?
.1
.split_once('>')?
.1;
Some(body.split_once("</Data>")?.0.trim())
}
#[cfg(test)]
#[path = "windows_security_tests.rs"]
mod tests;

View File

@@ -0,0 +1,85 @@
use pretty_assertions::assert_eq;
use super::CHANNELS;
use super::CheckStatus;
use super::MAX_RENDERED_EVENTS;
use super::classify;
use super::parse_events;
#[cfg(not(target_os = "windows"))]
#[tokio::test]
async fn an_unavailable_reader_is_not_reported_as_clean() {
assert_eq!(super::collect().await.status, CheckStatus::Warning);
}
#[test]
fn every_source_distinguishes_audits_from_blocks() {
for (channel, audit, block) in [
(0, 1122, 1121),
(0, 1125, 1126),
(1, 8003, 8004),
(2, 8021, 8022),
(3, 8006, 8007),
(4, 3076, 3077),
] {
for (id, expected) in [(audit, CheckStatus::Warning), (block, CheckStatus::Fail)] {
let events = parse_events(&fixture(id, "codex.exe", &[]), CHANNELS[channel]);
assert_eq!(events[0].0, expected, "misclassified event {id}");
}
}
}
#[test]
fn defender_distinguishes_detection_and_remediation() {
for (id, action, expected) in [
(1116, "", CheckStatus::Warning),
(1117, "Allow", CheckStatus::Ok),
(1117, "Quarantine", CheckStatus::Fail),
(1117, "Remove", CheckStatus::Fail),
] {
let events = parse_events(
&fixture(id, "codex.exe", &[("Action Name", action)]),
CHANNELS[0],
);
assert_eq!(classify(&[Some(events)]).status, expected);
}
}
#[test]
fn only_trusted_codex_executables_are_reported() {
for (path, expected) in [
("codex.exe", true),
(r"OpenAI.Codex_2p2nqsd0c76g0\ChatGPT.exe", true),
("evil-codex.exe", false),
(r"C:\Other\ChatGPT.exe", false),
(r"OpenAI.CodexEvil_1\ChatGPT.exe", false),
] {
let events = parse_events(&fixture(/*id*/ 1121, path, &[]), CHANNELS[0]);
assert_eq!(!events.is_empty(), expected, "misclassified {path}");
}
}
#[test]
fn evidence_is_bounded_redacted_and_correctly_classified() {
assert_eq!(classify(&[None]).status, CheckStatus::Warning);
assert_eq!(classify(&[Some(Vec::new()), None]).status, CheckStatus::Ok);
let audits = fixture(/*id*/ 1122, "codex.exe", &[]).repeat(MAX_RENDERED_EVENTS);
let secret = "private-customer-secret";
let block = fixture(/*id*/ 1121, "codex.exe", &[("User", secret)]);
let events = parse_events(&format!("{audits}{block}"), CHANNELS[0]);
let check = classify(&[Some(events)]);
assert_eq!(check.id, "desktop.security.enforcement");
assert_eq!(check.status, CheckStatus::Fail);
assert_eq!(check.details.len(), MAX_RENDERED_EVENTS);
assert!(!serde_json::to_string(&check).unwrap().contains(secret));
}
fn fixture(id: u32, path: &str, fields: &[(&str, &str)]) -> String {
let data = fields
.iter()
.map(|(name, value)| format!("<Data Name=\"{name}\">{value}</Data>"))
.collect::<String>();
format!(
"<Event><System><EventID>{id}</EventID><TimeCreated SystemTime=\"2026-01-01T00:00:00Z\"/></System><EventData><Data Name=\"Path\">{path}</Data>{data}</EventData></Event>"
)
}

View File

@@ -0,0 +1,97 @@
use std::fs;
use std::path::Path;
use pretty_assertions::assert_eq;
use super::CheckStatus;
use super::desktop::inspect_desktop_session;
const CURRENT_SESSION: &str = "12345678-1234-1234-1234-123456789abc";
const CURRENT_PROCESS: u32 = 12345;
#[test]
fn current_desktop_session_reports_the_latest_local_handshake() {
let directory = tempfile::tempdir().expect("temporary directory should be created");
write_log(
directory.path(),
concat!(
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
"2026-08-07T12:01:00.000Z info [AppServerConnection] Starting app-server connection hostId=local transport=websocket\n",
"2026-08-07T12:02:00.000Z info [AppServerConnection] initialize_handshake_result outcome=success transportKind=websocket\n",
"2026-08-07T12:03:00.000Z info [AppServerConnection] app_server_connection.state_changed hostId=remote transport=websocket\n",
"2026-08-07T12:04:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=websocket\n",
),
);
let (running, check) = inspect_desktop_session(directory.path(), |pid| pid == CURRENT_PROCESS);
assert!(running);
assert_eq!(check.id, "desktop.app_server.handshake");
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(
check.summary,
"the desktop app-server initialized successfully"
);
}
#[test]
fn failed_handshake_does_not_expose_sensitive_log_fields() {
let directory = tempfile::tempdir().expect("temporary directory should be created");
write_log(
directory.path(),
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result errorMessage=\"desktop-secret outcome=success\" outcome=failure transportKind=stdio\n",
);
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
assert!(running);
assert_eq!(check.status, CheckStatus::Fail);
assert_eq!(check.summary, "the desktop app-server failed to initialize");
assert!(
!serde_json::to_string(&check)
.unwrap()
.contains("desktop-secret")
);
}
#[test]
fn handshake_failure_in_the_middle_of_a_log_segment_is_detected() {
let directory = tempfile::tempdir().expect("temporary directory should be created");
let padding = "x".repeat(96 * 1024);
write_log(
directory.path(),
&format!(
"{padding}\n2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n{padding}"
),
);
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
assert!(running);
assert_eq!(check.status, CheckStatus::Fail);
}
#[test]
fn stopped_desktop_does_not_report_a_failure() {
let directory = tempfile::tempdir().expect("temporary directory should be created");
write_log(
directory.path(),
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
);
let (running, check) = inspect_desktop_session(directory.path(), |_| false);
assert!(!running);
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(check.summary, "the desktop application is not running");
}
fn write_log(directory: &Path, contents: &str) {
fs::write(
directory.join(format!(
"codex-desktop-{CURRENT_SESSION}-{CURRENT_PROCESS}-t0-i0-120000-0.log"
)),
contents,
)
.expect("desktop log fixture should be created");
}

View File

@@ -0,0 +1,178 @@
use std::io;
use std::path::Path;
use codex_core::config::Config;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorIssue;
use super::find_codex_home;
const GIB: u64 = 1024 * 1024 * 1024;
const FAIL_THRESHOLD: u64 = GIB;
const WARNING_THRESHOLD: u64 = 5 * GIB;
pub(super) fn check(config: Option<&Config>, cwd: &Path) -> DoctorCheck {
let home = config
.map(|config| config.codex_home.as_path().to_path_buf())
.or_else(|| find_codex_home().ok().map(Into::into))
.or_else(|| std::env::var_os("CODEX_HOME").map(Into::into));
check_with_paths(home.as_deref(), cwd, available_space)
}
fn check_with_paths(
home: Option<&Path>,
cwd: &Path,
measure: impl Fn(&Path) -> io::Result<u64>,
) -> DoctorCheck {
let home = home.and_then(|path| std::path::absolute(path).ok());
let mut check = DoctorCheck::new(
"system.disk",
"disk",
CheckStatus::Ok,
"sufficient free disk space",
)
.detail(format!(
"warning threshold: {}",
format_capacity(WARNING_THRESHOLD)
))
.detail(format!(
"failure threshold: {}",
format_capacity(FAIL_THRESHOLD)
));
let mut lowest = None;
for (label, path) in [("CODEX_HOME", home.as_deref()), ("worktree", Some(cwd))] {
let field = format!("{label} available");
let available = path
.and_then(|path| path.ancestors().find(|ancestor| ancestor.is_dir()))
.map(&measure)
.unwrap_or_else(|| Err(io::ErrorKind::NotFound.into()));
match available {
Ok(available) => {
let measured = format_capacity(available);
check = check.detail(format!("{field}: {measured}"));
lowest = Some(lowest.map_or(available, |lowest: u64| lowest.min(available)));
let status = match available {
0..FAIL_THRESHOLD => CheckStatus::Fail,
FAIL_THRESHOLD..WARNING_THRESHOLD => CheckStatus::Warning,
WARNING_THRESHOLD.. => CheckStatus::Ok,
};
if status != CheckStatus::Ok {
check.status = check.status.max(status);
check = check.issue(
DoctorIssue::new(status, format!("{label} has insufficient disk space"))
.measured(measured)
.expected(format!("at least {}", format_capacity(WARNING_THRESHOLD)))
.remedy("Free disk space or move the worktree to a larger volume.")
.field(field),
);
}
}
Err(error) => {
check.status = check.status.max(CheckStatus::Warning);
check = check
.detail(format!("{field}: unavailable ({:?})", error.kind()))
.issue(
DoctorIssue::new(
CheckStatus::Warning,
format!("disk space for {label} could not be checked"),
)
.measured(format!("{:?}", error.kind()))
.expected("readable filesystem capacity")
.remedy("Check filesystem access and available disk space.")
.field(field),
);
}
}
}
check.summary = match (check.status, lowest) {
(CheckStatus::Fail, Some(available)) => {
format!("critically low disk space ({})", format_capacity(available))
}
(CheckStatus::Warning, Some(available)) if available < WARNING_THRESHOLD => {
format!("low disk space ({})", format_capacity(available))
}
(CheckStatus::Warning, _) => "disk capacity could not be fully verified".to_string(),
(CheckStatus::Ok, Some(available)) => {
format!(
"sufficient free disk space ({})",
format_capacity(available)
)
}
(CheckStatus::Ok | CheckStatus::Fail, None) => {
"disk capacity could not be verified".to_string()
}
};
check
}
fn format_capacity(bytes: u64) -> String {
if bytes >= GIB {
format!("{:.1} GiB", bytes as f64 / GIB as f64)
} else {
format!("{:.1} MiB", bytes as f64 / (1024 * 1024) as f64)
}
}
#[cfg(unix)]
fn available_space(path: &Path) -> io::Result<u64> {
use std::ffi::CString;
use std::mem::MaybeUninit;
use std::os::unix::ffi::OsStrExt;
let path = CString::new(path.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?;
let mut stats = MaybeUninit::<libc::statvfs>::uninit();
if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
let stats = unsafe { stats.assume_init() };
if stats.f_files > 0 && stats.f_favail == 0 {
return Ok(0);
}
u64::try_from(u128::from(stats.f_bavail) * u128::from(stats.f_frsize))
.map_err(|_| io::Error::other("available disk space exceeds u64"))
}
#[cfg(windows)]
fn available_space(path: &Path) -> io::Result<u64> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
let mut path = path.as_os_str().encode_wide().collect::<Vec<_>>();
if path.last() != Some(&u16::from(b'\\')) {
path.push(u16::from(b'\\'));
}
path.push(0);
let mut available = 0;
if unsafe {
GetDiskFreeSpaceExW(
path.as_ptr(),
&mut available,
std::ptr::null_mut(),
std::ptr::null_mut(),
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok(available)
}
#[cfg(not(any(unix, windows)))]
fn available_space(_path: &Path) -> io::Result<u64> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"filesystem capacity is unavailable on this platform",
))
}
#[cfg(test)]
#[path = "disk_tests.rs"]
mod tests;

View File

@@ -0,0 +1,160 @@
use std::cell::RefCell;
use std::io;
use std::path::Path;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::CheckStatus;
use super::FAIL_THRESHOLD;
use super::GIB;
use super::WARNING_THRESHOLD;
use super::check;
use super::check_with_paths;
#[test]
fn disk_capacity_is_reported_without_loaded_configuration() {
let check = check(/*config*/ None, Path::new("."));
for label in ["CODEX_HOME available: ", "worktree available: "] {
assert!(
check
.details
.iter()
.any(|detail| detail.starts_with(label) && !detail.contains("unavailable"))
);
}
}
#[test]
fn disk_capacity_thresholds_produce_complete_diagnostics() {
for (available, status, measured, summary) in [
(0, "fail", "0.0 MiB", "critically low disk space (0.0 MiB)"),
(
FAIL_THRESHOLD - 1,
"fail",
"1024.0 MiB",
"critically low disk space (1024.0 MiB)",
),
(
FAIL_THRESHOLD,
"warning",
"1.0 GiB",
"low disk space (1.0 GiB)",
),
(
WARNING_THRESHOLD - 1,
"warning",
"5.0 GiB",
"low disk space (5.0 GiB)",
),
(
WARNING_THRESHOLD,
"ok",
"5.0 GiB",
"sufficient free disk space (5.0 GiB)",
),
(
WARNING_THRESHOLD + GIB,
"ok",
"6.0 GiB",
"sufficient free disk space (6.0 GiB)",
),
] {
let issues = ["CODEX_HOME", "worktree"]
.into_iter()
.filter(|_| status != "ok")
.map(|label| {
json!({
"severity": status,
"cause": format!("{label} has insufficient disk space"),
"measured": measured,
"expected": "at least 5.0 GiB",
"remedy": "Free disk space or move the worktree to a larger volume.",
"fields": [format!("{label} available")],
})
})
.collect::<Vec<_>>();
let check = check_with_paths(Some(Path::new(".")), Path::new("."), |_| Ok(available));
assert_eq!(
serde_json::to_value(check).unwrap(),
json!({
"id": "system.disk",
"category": "disk",
"status": status,
"summary": summary,
"details": [
"warning threshold: 5.0 GiB",
"failure threshold: 1.0 GiB",
format!("CODEX_HOME available: {measured}"),
format!("worktree available: {measured}"),
],
"issues": issues,
"remediation": null,
"durationMs": 0,
}),
"available bytes: {available}"
);
}
}
#[test]
fn disk_measurement_errors_produce_complete_warning_diagnostics() {
let check = check_with_paths(Some(Path::new(".")), Path::new("."), |_| {
Err(io::ErrorKind::PermissionDenied.into())
});
let issues = ["CODEX_HOME", "worktree"]
.into_iter()
.map(|label| {
json!({
"severity": "warning",
"cause": format!("disk space for {label} could not be checked"),
"measured": "PermissionDenied",
"expected": "readable filesystem capacity",
"remedy": "Check filesystem access and available disk space.",
"fields": [format!("{label} available")],
})
})
.collect::<Vec<_>>();
assert_eq!(
serde_json::to_value(check).unwrap(),
json!({
"id": "system.disk",
"category": "disk",
"status": "warning",
"summary": "disk capacity could not be fully verified",
"details": [
"warning threshold: 5.0 GiB",
"failure threshold: 1.0 GiB",
"CODEX_HOME available: unavailable (PermissionDenied)",
"worktree available: unavailable (PermissionDenied)",
],
"issues": issues,
"remediation": null,
"durationMs": 0,
})
);
}
#[test]
fn nonexistent_relative_codex_home_uses_current_directory_capacity() {
let measured_paths = RefCell::new(Vec::new());
let check = check_with_paths(
Some(Path::new("doctor-nonexistent-relative-home/nested")),
Path::new("."),
|path| {
measured_paths.borrow_mut().push(path.to_path_buf());
Ok(WARNING_THRESHOLD)
},
);
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(
measured_paths.into_inner(),
[std::env::current_dir().unwrap(), Path::new(".").into()]
);
}

View File

@@ -0,0 +1,385 @@
//! Checks literal sandbox grants without traversing directory trees or probing deny rules.
//!
//! Filesystem calls run in disposable copies of this executable: a blocked mount
//! must not occupy a Tokio blocking worker and delay doctor's runtime shutdown.
//! Budgets bound helper waits, not synchronous process launch; policy is unchanged.
//! Windows only lists paths: even local-looking paths can redirect to network shares.
//! Restricted-read policies also only list paths: lexical checks cannot constrain symlinks.
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::io;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use std::time::Instant;
use codex_config::ConfigPathContext;
use codex_config::format_config_layer_source;
use codex_config::permissions_toml::FilesystemPermissionToml;
use codex_core::config::Config;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
use codex_protocol::permissions::ReadDenyMatcher;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::PathUri;
use tokio::process::Command;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorIssue;
const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
const TOTAL_TIMEOUT: Duration = Duration::from_secs(8);
const SLOW_PROBE: Duration = Duration::from_secs(1);
const MAX_PATHS: usize = 32;
pub(super) async fn check(config: &Config) -> DoctorCheck {
let mut check = DoctorCheck::new(
"sandbox.filesystem_paths",
"sandbox",
CheckStatus::Ok,
"configured filesystem paths respond promptly",
);
// Resolve policy semantics lexically, without querying the configured paths.
let policy = config
.permissions
.permission_profile()
.file_system_sandbox_policy();
let cwd = PathUri::from_abs_path(&config.cwd);
let roots = config.effective_workspace_roots();
let home = AbsolutePathBufGuard::home_directory()
.and_then(|home| PathUri::from_host_native_path(home).ok());
let temporary_directories = std::env::var_os("TMPDIR")
.filter(|path| !path.is_empty())
.and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok())
.map(PathUri::from)
.into_iter()
.collect::<Vec<_>>();
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: &roots,
user_home_dir: home.as_ref(),
temporary_directories: Some(&temporary_directories),
};
let paths = literal_paths(&policy, &context);
if paths.is_empty() {
check.summary = "no explicit filesystem paths to probe".to_string();
return check;
}
let read_restricted = !policy.has_full_disk_read_access();
if read_restricted {
check.summary =
"configured filesystem paths listed; read restrictions prevent probes".to_string();
} else if cfg!(windows) {
check.summary =
"configured filesystem paths listed; probes disabled on Windows".to_string();
}
if let Some(profile) = config.permissions.active_permission_profile() {
check
.details
.push(format!("permission profile: {}", profile.id));
}
check
.details
.push("operation: resolve paths only; read/write access is not tested".to_string());
check
.details
.push("probe budgets: 2 seconds per path, 8 seconds total, at most 32 paths".to_string());
let started = Instant::now();
let mut checked = 0;
for (path, access) in paths.iter().take(MAX_PATHS) {
let remaining = TOTAL_TIMEOUT.saturating_sub(started.elapsed());
if remaining.is_zero() {
break;
}
let label = format!("path {}", checked + 1);
let probe_started = Instant::now();
let outcome = match path.to_abs_path() {
Ok(_) if read_restricted => ProbeResult::SkippedReadRestrictions,
Ok(_) if cfg!(windows) => ProbeResult::SkippedWindows,
Ok(native) => {
let executable = match std::env::current_exe() {
Ok(executable) => executable,
Err(_) => {
check.status = CheckStatus::Warning;
check.summary =
"filesystem path probes unavailable: cannot locate Codex executable"
.to_string();
return check;
}
};
let mut command = Command::new(&executable);
command
.arg("doctor")
.arg("--probe-filesystem-path")
.arg(native.as_path());
probe(&mut command, remaining.min(PROBE_TIMEOUT)).await
}
Err(_) => ProbeResult::Unsupported,
};
let slow = probe_started.elapsed() >= SLOW_PROBE;
checked += 1;
let access = access
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ");
check.details.push(format!(
"{label}: {} ({access}); {}",
path.inferred_native_path_string(),
outcome.description()
));
if slow {
check.details.push(format!(
"{label} latency: over 1 second (includes helper startup)"
));
}
check
.details
.push(format!("{label} source: {}", source(config, path)));
if !matches!(
outcome,
ProbeResult::Resolved
| ProbeResult::Missing
| ProbeResult::SkippedWindows
| ProbeResult::SkippedReadRestrictions
) || slow
{
check.status = CheckStatus::Warning;
check.summary =
"some configured filesystem paths are slow or could not be checked".to_string();
check.issues.push(
DoctorIssue::new(CheckStatus::Warning, format!("{label}: {}{}", outcome.description(), if slow { "; slow path probe" } else { "" }))
.field(label)
.remedy("Check this path's mount and host permissions. Ask your administrator whether the entry is needed on this machine; do not remove required restrictions."),
);
}
}
if checked < paths.len() {
check.status = CheckStatus::Warning;
check.summary = "filesystem path check is incomplete".to_string();
check.details.push(format!(
"unchecked paths: {} (probe budget exhausted)",
paths.len() - checked
));
}
check
.details
.push(format!("paths checked: {checked} of {}", paths.len()));
check
}
fn literal_paths(
policy: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Vec<(PathUri, BTreeSet<FileSystemAccessMode>)> {
let mut paths = HashMap::<_, BTreeSet<_>>::new();
let denials = ReadDenyMatcher::from_context(policy, context);
for entry in &policy.entries {
// Deny rules can contain private managed-policy paths. Doctor only
// reports their counts in the existing sandbox check.
if entry.access == FileSystemAccessMode::Deny {
continue;
}
match &entry.path {
FileSystemPath::Path { path } => {
if policy.can_read_path(path, context)
&& !denials
.as_ref()
.is_some_and(|matcher| matcher.is_read_denied_uri(path, context))
{
paths.entry(path.clone()).or_default().insert(entry.access);
}
}
FileSystemPath::GlobPattern { .. } | FileSystemPath::Special { .. } => {}
}
}
let mut paths = paths.into_iter().collect::<Vec<_>>();
paths.sort_by_cached_key(|(path, _)| path.to_string());
paths
}
fn source(config: &Config, path: &PathUri) -> String {
let active = config.permissions.active_permission_profile();
let context = ConfigPathContext::new(
PathConvention::native(),
Some(PathUri::from_abs_path(&config.cwd)),
AbsolutePathBufGuard::home_directory()
.and_then(|home| PathUri::from_host_native_path(home).ok()),
);
let effective = config.config_layer_stack.effective_config();
let managed = config
.config_layer_stack
.requirements_toml()
.permissions
.as_ref();
let matches_path = |base: &str, subpath: Option<&str>| {
let base = if subpath.is_none() {
base.strip_suffix("/**").unwrap_or(base)
} else {
base
};
let Ok(base) = context.resolve_path(base) else {
return false;
};
match subpath.map(|subpath| subpath.strip_suffix("/**").unwrap_or(subpath)) {
None | Some(".") => base == *path,
Some(subpath) => context
.resolve_against(subpath, &base)
.is_ok_and(|resolved| resolved == *path),
}
};
let mut profiles = Vec::new();
let mut next = active.as_ref().map(|profile| profile.id.as_str());
while let Some(profile) = next {
if profiles.contains(&profile) {
break;
}
profiles.push(profile);
next = effective
.get("permissions")
.and_then(|permissions| permissions.get(profile))
.and_then(|profile| profile.get("extends"))
.and_then(toml::Value::as_str)
.or_else(|| managed?.profiles.get(profile)?.extends.as_deref());
}
for profile in profiles {
// Managed grants have no config-layer origin and can shadow a parent's grant.
if managed
.and_then(|managed| managed.profiles.get(profile))
.and_then(|profile| profile.filesystem.as_ref())
.is_some_and(|filesystem| {
filesystem.entries.iter().any(|(base, entry)| match entry {
FilesystemPermissionToml::Access(access) => {
*access != FileSystemAccessMode::Deny
&& matches_path(base, /*subpath*/ None)
}
FilesystemPermissionToml::Scoped(entries) => {
entries.iter().any(|(subpath, access)| {
*access != FileSystemAccessMode::Deny
&& matches_path(base, Some(subpath))
})
}
})
})
{
break;
}
let origins = config
.config_layer_stack
.origins_with_path_filter(|segments| {
if segments.len() < 4 || segments[0] != "permissions" || segments[2] != "filesystem"
{
return false;
}
if profile != segments[1] {
return false;
}
// Origins can retain leaves removed by a table/scalar replacement.
if !matches!(
segments
.iter()
.try_fold(&effective, |value, segment| value.get(segment))
.and_then(toml::Value::as_str),
Some("read" | "write")
) {
return false;
}
matches_path(&segments[3], segments.get(4).map(String::as_str))
});
let sources = origins
.into_iter()
.map(|(key, origin)| {
format!(
"{key} in {}",
format_config_layer_source(&origin.name, codex_config::CONFIG_TOML_FILE)
)
})
.collect::<BTreeSet<_>>();
if !sources.is_empty() {
return sources.into_iter().collect::<Vec<_>>().join("; ");
}
}
// Compiled requirements, legacy config, and runtime-added entries do not
// retain per-entry provenance. Do not misattribute them to a config file.
"effective filesystem policy (entry provenance unavailable)".to_string()
}
#[derive(Debug, PartialEq, Eq)]
enum ProbeResult {
Resolved,
Missing,
Denied,
TimedOut,
Failed,
Unsupported,
SkippedWindows,
SkippedReadRestrictions,
}
impl ProbeResult {
fn description(&self) -> &'static str {
match self {
Self::Resolved => "path resolved (read/write access not tested)",
Self::Missing => "missing (may be intentional)",
Self::Denied => "access denied to doctor",
Self::TimedOut => "path probe timed out",
Self::Failed => "path probe failed",
Self::Unsupported => "path is not native to this host; not probed",
Self::SkippedWindows => "not probed on Windows (network authentication risk)",
Self::SkippedReadRestrictions => "not probed (filesystem read restrictions apply)",
}
}
}
async fn probe(command: &mut Command, budget: Duration) -> ProbeResult {
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(/*kill_on_drop*/ true);
let Ok(mut child) = command.spawn() else {
return ProbeResult::Failed;
};
match tokio::time::timeout(budget, child.wait()).await {
Ok(Ok(status)) => match status.code() {
Some(0) => ProbeResult::Resolved,
Some(2) => ProbeResult::Missing,
Some(3) => ProbeResult::Denied,
Some(5) => ProbeResult::SkippedWindows,
_ => ProbeResult::Failed,
},
Ok(Err(_)) => ProbeResult::Failed,
Err(_) => {
// Do not await termination: an uninterruptible filesystem syscall
// can delay even SIGKILL. Tokio reaps the child when it can exit.
let _ = child.start_kill();
ProbeResult::TimedOut
}
}
}
pub(super) fn probe_exit_code(path: &Path) -> i32 {
// Even drive-qualified paths can traverse reparse points to network shares.
// Do not initiate filesystem access on Windows from this unsandboxed helper.
if cfg!(windows) {
return 5;
}
match std::fs::canonicalize(path) {
Ok(_) => 0,
Err(error) => match error.kind() {
io::ErrorKind::NotFound => 2,
io::ErrorKind::PermissionDenied => 3,
_ => 4,
},
}
}
#[cfg(test)]
#[path = "filesystem_paths_tests.rs"]
mod tests;

View File

@@ -0,0 +1,286 @@
use std::collections::BTreeSet;
use std::time::Duration;
use std::time::Instant;
use codex_config::LoaderOverrides;
use codex_core::config::ConfigBuilder;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tokio::process::Command;
use super::ProbeResult;
use super::literal_paths;
use super::probe;
use super::source;
#[test]
fn deduplicates_literal_paths_without_expanding_globs_or_special_paths() {
let temp = tempfile::tempdir().unwrap();
let path = PathUri::from_host_native_path(temp.path()).unwrap();
let mut policy = FileSystemSandboxPolicy {
entries: vec![
FileSystemSandboxEntry {
path: path.clone().into(),
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: path.clone().into(),
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: PathUri::from_host_native_path(temp.path().join("private-policy-path"))
.unwrap()
.into(),
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: format!("{}/**/*.env", temp.path().display()),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
},
],
..Default::default()
};
// Equal-specificity denials, denied ancestors, and deny globs all override grants.
for suffix in [
"private-policy-path",
"private-policy-path/child",
"secret.env",
] {
policy.entries.push(FileSystemSandboxEntry {
path: PathUri::from_host_native_path(temp.path().join(suffix))
.unwrap()
.into(),
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
});
}
let context = FileSystemSandboxPolicyContext {
cwd: &path,
workspace_roots: std::slice::from_ref(&path),
user_home_dir: None,
temporary_directories: Some(&[]),
};
assert_eq!(
literal_paths(&policy, &context),
vec![(
path,
BTreeSet::from([FileSystemAccessMode::Read, FileSystemAccessMode::Write])
)]
);
}
#[tokio::test]
async fn attributes_paths_inherited_through_managed_profiles_to_their_config_layer() {
let home = tempfile::tempdir().unwrap();
let configured = home.path().join("unavailable");
let config_file = home.path().join("config.toml");
let base = toml::Value::String(configured.display().to_string());
std::fs::write(
&config_file,
format!(
r#"
default_permissions = "diagnostic"
[permissions.diagnostic]
extends = "middle"
[permissions.diagnostic.filesystem.{base}]
"." = "read"
[permissions.base]
extends = ":workspace"
[permissions.base.filesystem.{base}]
"." = "write"
".git" = "write"
"subtree/**" = "read"
"overridden" = "read"
"#
),
)
.unwrap();
let requirements_file = home.path().join("requirements.toml");
std::fs::write(
&requirements_file,
format!(
r#"
[permissions.middle]
extends = "base"
[permissions.middle.filesystem.{base}]
".git/**" = "deny"
"overridden" = "write"
"#
),
)
.unwrap();
let mut overrides = LoaderOverrides::without_managed_config_for_tests();
overrides.system_requirements_path = Some(requirements_file);
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.loader_overrides(overrides)
.build()
.await
.unwrap();
let path = PathUri::from_host_native_path(configured.join(".git")).unwrap();
assert_eq!(
source(&config, &path),
format!(
"permissions.base.filesystem.{}..git in user ({})",
configured.display(),
config_file.display()
)
);
let subtree = PathUri::from_host_native_path(configured.join("subtree")).unwrap();
assert_eq!(
source(&config, &subtree),
format!(
"permissions.base.filesystem.{}.subtree/** in user ({})",
configured.display(),
config_file.display()
)
);
let overridden = PathUri::from_host_native_path(configured.join("overridden")).unwrap();
assert_eq!(
source(&config, &overridden),
"effective filesystem policy (entry provenance unavailable)"
);
let base_path = PathUri::from_host_native_path(&configured).unwrap();
assert_eq!(
source(&config, &base_path),
format!(
"permissions.diagnostic.filesystem.{}.. in user ({})",
configured.display(),
config_file.display()
)
);
let mut check = super::check(&config).await;
for detail in &mut check.details {
*detail = detail
.replace(&home.path().display().to_string(), "FIXTURE")
.replace('\\', "/");
}
let report = super::super::DoctorReport {
schema_version: 1,
generated_at: "2026-01-01T00:00:00Z".to_string(),
overall_status: check.status,
codex_version: "test".to_string(),
checks: vec![check],
};
insta::assert_snapshot!(
"doctor_read_restricted_filesystem_paths",
super::super::render_human_report(
&report,
super::super::HumanOutputOptions {
show_details: true,
show_all: false,
ascii: true,
color_enabled: false,
},
)
);
}
#[tokio::test]
async fn returns_when_a_probe_process_does_not_exit() {
let mut command = Command::new(std::env::current_exe().unwrap());
command.args([
"--ignored",
"--exact",
"doctor::filesystem_paths::tests::blocked_probe_fixture",
]);
let started = Instant::now();
assert_eq!(
probe(&mut command, Duration::from_millis(/*millis*/ 150)).await,
ProbeResult::TimedOut
);
assert!(started.elapsed() < Duration::from_secs(/*secs*/ 5));
}
#[test]
#[ignore = "subprocess fixture for the bounded filesystem probe test"]
fn blocked_probe_fixture() {
std::thread::sleep(Duration::from_secs(/*secs*/ 30));
}
#[tokio::test]
async fn attributes_home_relative_subtree_paths_to_their_config_layer() {
let home = tempfile::tempdir().unwrap();
let config_file = home.path().join("config.toml");
std::fs::write(
&config_file,
r#"
default_permissions = "diagnostic"
[permissions.diagnostic]
extends = ":read-only"
[permissions.diagnostic.filesystem]
"~/doctor-provenance/**" = "read"
"#,
)
.unwrap();
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
let user_home = codex_utils_absolute_path::AbsolutePathBufGuard::home_directory().unwrap();
let path = PathUri::from_host_native_path(user_home.join("doctor-provenance")).unwrap();
assert_eq!(
source(&config, &path),
format!(
"permissions.diagnostic.filesystem.~/doctor-provenance/** in user ({})",
config_file.display()
)
);
}
#[tokio::test]
async fn excludes_scoped_origins_replaced_by_a_scalar_grant() {
let home = tempfile::tempdir().unwrap();
let configured = home.path().join("cache.v1");
let base = toml::Value::String(configured.display().to_string());
std::fs::write(
home.path().join("config.toml"),
format!(
r#"
default_permissions = "diagnostic"
[permissions.diagnostic]
extends = ":read-only"
[permissions.diagnostic.filesystem.{base}]
"." = "read"
"#
),
)
.unwrap();
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.cli_overrides(vec![(
"permissions.diagnostic.filesystem".to_string(),
format!("{{ {base} = \"write\" }}").parse().unwrap(),
)])
.build()
.await
.unwrap();
let path = PathUri::from_host_native_path(&configured).unwrap();
assert_eq!(
source(&config, &path),
format!(
"permissions.diagnostic.filesystem.{} in session-flags",
configured.display()
)
);
}

View File

@@ -0,0 +1,160 @@
//! Inspects Git executable locations and repository metadata without running Git.
use std::collections::BTreeSet;
use std::path::Path;
use std::path::PathBuf;
use codex_git_utils::get_git_repo_root;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorIssue;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct GitCheckInputs {
selected_git: Option<PathBuf>,
git_candidates: Vec<PathBuf>,
repo_root: Option<PathBuf>,
git_entry: Option<String>,
}
pub(super) fn git_check(cwd: &Path) -> DoctorCheck {
let selected_git = which::which("git").ok();
let git_candidates = git_candidates();
let repo_root = get_git_repo_root(cwd);
git_check_from_inputs(GitCheckInputs {
selected_git,
git_candidates,
git_entry: repo_root.as_deref().map(git_entry_summary),
repo_root,
})
}
fn git_check_from_inputs(inputs: GitCheckInputs) -> DoctorCheck {
let mut details = Vec::new();
match inputs.selected_git.as_deref() {
Some(path) => details.push(format!("selected git: {}", path.display())),
None => details.push("selected git: not found".to_string()),
}
details.push(format!("PATH git entries: {}", inputs.git_candidates.len()));
for (index, path) in inputs.git_candidates.iter().enumerate() {
details.push(format!("PATH git #{}: {}", index + 1, path.display()));
}
match inputs.repo_root.as_deref() {
Some(root) => {
details.push("repo detected: true".to_string());
details.push(format!("repo root: {}", root.display()));
}
None => details.push("repo detected: false".to_string()),
}
if let Some(entry) = inputs.git_entry.as_deref() {
details.push(format!(".git entry: {entry}"));
}
details.push("git execution: not inspected (PATH helpers are not executed)".to_string());
let mut check = DoctorCheck::new(
"git.environment",
"git",
CheckStatus::Ok,
if inputs.selected_git.is_some() {
"git executable found; execution not verified"
} else {
"git executable not found"
},
)
.details(details);
if inputs.selected_git.is_none() && inputs.repo_root.is_some() {
check.status = CheckStatus::Warning;
check.summary = "Git repository detected but git executable was not found".to_string();
check = check.issue(
DoctorIssue::new(
CheckStatus::Warning,
"Git repository detected but git executable was not found",
)
.expected("git available on PATH")
.remedy("Install Git or fix PATH so Codex can inspect repository metadata.")
.field("selected git"),
);
}
check
}
fn git_candidates() -> Vec<PathBuf> {
let Ok(candidates) = which::which_all("git") else {
return Vec::new();
};
let mut seen = BTreeSet::new();
candidates
.filter(|candidate| seen.insert(candidate.clone()))
.collect()
}
fn git_entry_summary(repo_root: &Path) -> String {
let entry = repo_root.join(".git");
match std::fs::metadata(&entry) {
Ok(metadata) if metadata.is_dir() => "directory".to_string(),
Ok(metadata) if metadata.is_file() => std::fs::read_to_string(&entry)
.ok()
.and_then(|contents| {
contents
.strip_prefix("gitdir:")
.map(str::trim)
.map(|path| format!("file -> {path}"))
})
.unwrap_or_else(|| "file".to_string()),
Ok(_) => "other".to_string(),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => "missing".to_string(),
Err(err) => format!("unreadable ({err})"),
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn warns_when_git_repo_has_no_git_executable() {
let check = git_check_from_inputs(GitCheckInputs {
repo_root: Some(PathBuf::from("/repo")),
..GitCheckInputs::default()
});
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(
check.summary,
"Git repository detected but git executable was not found"
);
}
#[test]
fn reports_git_candidates_and_repo_metadata() {
let check = git_check_from_inputs(GitCheckInputs {
selected_git: Some(PathBuf::from("/usr/bin/git")),
git_candidates: vec![PathBuf::from("/usr/bin/git"), PathBuf::from("/opt/bin/git")],
repo_root: Some(PathBuf::from("/repo")),
git_entry: Some("directory".to_string()),
});
let report = super::super::DoctorReport {
schema_version: 1,
generated_at: "2026-01-01T00:00:00Z".to_string(),
overall_status: check.status,
codex_version: "test".to_string(),
checks: vec![check],
};
insta::assert_snapshot!(super::super::render_human_report(
&report,
super::super::HumanOutputOptions {
show_details: true,
show_all: false,
ascii: true,
color_enabled: false,
},
));
}
}

View File

@@ -0,0 +1,224 @@
use std::env;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use codex_arg0::Arg0DispatchPaths;
use codex_core::config::Config;
#[cfg(target_os = "macos")]
use codex_http_client::MacosSystemProxyConfiguration;
use codex_http_client::RouteAwareClientPool;
use codex_http_client::RouteAwareRequestError;
use codex_http_client::RouteFailureClass;
#[cfg(target_os = "macos")]
use codex_http_client::macos_system_proxy_configuration;
use codex_login::default_client::create_client_without_request_logging;
use codex_tui::Cli as TuiCli;
use codex_utils_cli::CliConfigOverrides;
use http::HeaderMap;
use http::Method;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorProgress;
use super::push_proxy_env_details;
use super::read_probe_file;
pub(super) async fn checks(
overrides: CliConfigOverrides,
interactive: &TuiCli,
arg0_paths: &Arg0DispatchPaths,
progress: &Arc<dyn DoctorProgress>,
) -> Vec<DoctorCheck> {
progress.begin("config");
let config_started = Instant::now();
let config = match super::load_config(overrides, interactive, arg0_paths).await {
Ok(config) => config,
Err(error) => {
let check = super::config_load_failure(&error)
.detail("network diagnostics: effective network configuration is unavailable");
progress.finish("config", check.status);
return vec![check];
}
};
let config_duration = config_started.elapsed();
let mut config_check = super::config_check(&config).detail(format!(
"configuration load ms: {}",
config_duration.as_millis()
));
config_check.duration_ms = config_duration.as_millis().try_into().unwrap_or(u64::MAX);
progress.finish("config", config_check.status);
let auth_manager = codex_login::AuthManager::shared_from_config(
&config, /*enable_codex_api_key_env*/ true,
)
.await
.ok();
let plan = super::provider_reachability_plan(&config);
#[cfg(target_os = "macos")]
let url = plan.endpoints.first().map(|endpoint| endpoint.url.clone());
let (network, websocket, reachability) = tokio::join!(
async { super::run_sync_check("network", progress.clone(), || check(Some(&config))) },
super::run_async_check(
"websocket",
progress.clone(),
super::websocket_reachability_check(&config, auth_manager)
),
super::run_async_check(
"provider reachability",
progress.clone(),
super::provider_reachability_check(plan)
),
);
#[cfg(target_os = "macos")]
let reachability = with_system_proxy_remediation(reachability, &config, url.as_deref());
vec![config_check, network, websocket, reachability]
}
#[cfg(any(target_os = "macos", test))]
pub(super) const SYSTEM_PROXY_REMEDIATION: &str = "A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `codex features enable respect_system_proxy`. Restart Codex after changing this setting.";
pub(super) fn check(config: Option<&Config>) -> DoctorCheck {
let mut details = Vec::new();
push_proxy_env_details(&mut details);
#[cfg(target_os = "macos")]
{
let request_url = config
.and_then(|config| config.model_provider.base_url.as_deref())
.or_else(|| config.map(|config| config.chatgpt_base_url.as_str()))
.unwrap_or("https://chatgpt.com/backend-api/");
let configuration = match macos_system_proxy_configuration(request_url) {
MacosSystemProxyConfiguration::Automatic => "automatic (PAC)",
MacosSystemProxyConfiguration::Manual => "manual",
MacosSystemProxyConfiguration::Direct => "direct",
MacosSystemProxyConfiguration::Unavailable => "unavailable",
};
details.push(format!("system proxy: {configuration}"));
}
if let Some(config) = config {
let enabled = |value| if value { "enabled" } else { "disabled" };
details.push(format!(
"respect system proxy: {}",
enabled(config.respect_system_proxy)
));
if config.permissions.network.is_some() {
details.push("managed proxy: configured".to_string());
} else {
details.push("managed proxy: not configured".to_string());
}
}
let mut status = CheckStatus::Ok;
let mut summary = "network-related environment looks readable".to_string();
for name in ["CODEX_CA_CERTIFICATE", "SSL_CERT_FILE"] {
if let Some(raw) = env::var_os(name) {
let path = PathBuf::from(raw);
match std::fs::metadata(&path) {
Ok(metadata) if metadata.is_file() => {
if let Err(error) = read_probe_file(&path) {
status = CheckStatus::Warning;
summary = "custom CA env var points at an unreadable file".to_string();
details.push(format!("{name}: {} ({error})", path.display()));
} else {
details.push(format!("{name}: readable file {}", path.display()));
}
}
Ok(_) => {
status = CheckStatus::Warning;
summary = "custom CA env var does not point at a file".to_string();
details.push(format!("{name}: not a file {}", path.display()));
}
Err(error) => {
status = CheckStatus::Warning;
summary = "custom CA env var points at an unreadable path".to_string();
details.push(format!("{name}: {} ({error})", path.display()));
}
}
}
}
DoctorCheck::new("network.env", "network", status, summary).details(details)
}
#[cfg(target_os = "macos")]
pub(super) fn with_system_proxy_remediation(
mut check: DoctorCheck,
config: &Config,
request_url: Option<&str>,
) -> DoctorCheck {
if check.status == CheckStatus::Fail
&& !config.respect_system_proxy
&& config.permissions.network.is_none()
&& config
.config_layer_stack
.requirements()
.feature_requirements
.as_ref()
.and_then(|requirements| requirements.value.entries.get("respect_system_proxy"))
.is_none_or(|enabled| *enabled)
&& !super::PROXY_ENV_VARS
.iter()
.any(|name| !name.eq_ignore_ascii_case("NO_PROXY") && super::env_var_present(name))
&& request_url.is_some_and(|url| {
matches!(
macos_system_proxy_configuration(url),
MacosSystemProxyConfiguration::Automatic | MacosSystemProxyConfiguration::Manual
)
})
{
check.remediation = Some(SYSTEM_PROXY_REMEDIATION.to_string());
}
check
}
pub(super) async fn probe_status(
client: &RouteAwareClientPool,
url: &str,
method: Method,
headers: HeaderMap,
) -> Result<u16, String> {
let response = if env::var("CODEX_SANDBOX").as_deref() == Ok("seatbelt") {
create_client_without_request_logging()
.request(method, url)
.headers(headers)
.timeout(Duration::from_secs(8))
.send()
.await
} else {
client
.request(method, url)
.headers(headers)
// Allow five seconds for PAC resolution before the three-second HTTP budget.
.timeout(Duration::from_secs(8))
.send()
.await
}
.map_err(request_error)?;
let status = response.status().as_u16();
if status == 407 {
return Err("proxy authentication required (HTTP 407)".to_string());
}
Ok(status)
}
pub(super) fn request_error(error: RouteAwareRequestError) -> String {
match error.failure_class() {
Some(RouteFailureClass::TlsError) => "TLS handshake or certificate validation failed",
Some(RouteFailureClass::ProxyAuthenticationRequired) => "proxy authentication required",
Some(RouteFailureClass::InvalidProxyConfig) => "invalid proxy configuration",
Some(RouteFailureClass::ProxyResolutionUnavailable) => {
"system proxy configuration unavailable"
}
Some(RouteFailureClass::ConnectTimeout) => "request timed out",
Some(RouteFailureClass::UnsupportedProxyScheme) => "unsupported proxy configuration",
Some(RouteFailureClass::ResolverError) => "proxy resolution failed",
None if error.is_timeout() => "request timed out",
None if error.is_connect() => "connect failed",
None => "request failed",
}
.to_string()
}
#[cfg(test)]
#[path = "network_tests.rs"]
mod tests;

View File

@@ -0,0 +1,37 @@
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use super::super::CheckStatus;
use super::super::ProviderAuthReachabilityMode;
use super::super::provider_reachability_check;
use super::super::provider_reachability_plan_from_parts;
#[tokio::test]
async fn provider_reachability_rejects_proxy_authentication_challenges() {
let proxy = MockServer::start().await;
Mock::given(method("HEAD"))
.respond_with(ResponseTemplate::new(407))
.mount(&proxy)
.await;
let plan = provider_reachability_plan_from_parts(
ProviderAuthReachabilityMode::Chatgpt,
"openai",
"OpenAI",
/*provider_base_url*/ None,
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
&format!("{}/backend-api/", proxy.uri()),
);
let check = provider_reachability_check(plan).await;
assert_eq!(check.status, CheckStatus::Fail);
assert!(
check
.details
.join(" ")
.contains("proxy authentication required (HTTP 407)")
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,791 @@
//! Converts raw doctor detail strings into human-oriented rows.
//!
//! Checks intentionally store details as simple redacted `label: value` strings
//! so JSON serialization and human rendering share the same source data. This
//! module owns the presentation-only transformations: collapsing noisy booleans,
//! truncating long paths for terminal output, grouping repeated values, and
//! keeping the `--all` expansion behavior out of check construction.
use std::collections::BTreeSet;
use std::env;
use super::DoctorCheck;
use super::HumanOutputOptions;
use super::redact_detail;
const LIST_LIMIT: usize = 7;
const PATH_LIMIT: usize = 48;
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) enum HumanDetail {
Row {
label: String,
value: String,
expected: Option<String>,
},
Continuation(String),
Bullet(String),
Remedy(String),
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ParsedDetail {
label: String,
value: String,
}
pub(super) fn detail_lines(check: &DoctorCheck, options: HumanOutputOptions) -> Vec<HumanDetail> {
let parsed = parsed_details(check);
let details = match check.category.as_str() {
"system" => system_details(&parsed),
"runtime" => runtime_details(&parsed),
"install" => install_details(&parsed, options),
"git" => git_details(&parsed, options),
"title" => title_details(&parsed),
"config" => config_details(&parsed, options),
"state" => state_details(&parsed),
_ => generic_details(&parsed),
};
let mut details = details
.into_iter()
.map(|detail| attach_issue_metadata(detail, check))
.map(|detail| humanize_detail(detail, options))
.collect::<Vec<_>>();
details.extend(issue_remedies(check));
details
}
fn system_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "os", "os");
push_row_if_present(&mut out, parsed, "os language", "OS language");
push_row_if_present(&mut out, parsed, "LC_ALL", "LC_ALL");
push_row_if_present(&mut out, parsed, "LC_CTYPE", "LC_CTYPE");
push_row_if_present(&mut out, parsed, "LANG", "LANG");
push_row_if_present(&mut out, parsed, "VISUAL", "VISUAL");
push_row_if_present(&mut out, parsed, "EDITOR", "EDITOR");
push_row_if_present(&mut out, parsed, "PAGER", "PAGER");
push_row_if_present(&mut out, parsed, "GIT_PAGER", "GIT_PAGER");
push_row_if_present(&mut out, parsed, "GH_PAGER", "GH_PAGER");
push_row_if_present(&mut out, parsed, "LESS", "LESS");
push_remaining(
&mut out,
parsed,
&[
"os",
"os type",
"os version",
"os language",
"LC_ALL",
"LC_CTYPE",
"LANG",
"VISUAL",
"EDITOR",
"PAGER",
"GIT_PAGER",
"GH_PAGER",
"LESS",
],
&[],
);
out
}
pub(super) fn detail_value(check: &DoctorCheck, label: &str) -> Option<String> {
parsed_details(check)
.into_iter()
.find(|detail| detail.label == label)
.map(|detail| detail.value)
}
pub(super) fn rollout_summary(value: &str) -> Option<String> {
let (files, rest) = value.split_once(" files, ")?;
let (total_bytes, rest) = rest.split_once(" total bytes, ")?;
let (average_bytes, _) = rest.split_once(" average bytes")?;
let files = files.trim().parse::<u64>().ok()?;
let total_bytes = total_bytes.trim().parse::<u64>().ok()?;
let average_bytes = average_bytes.trim().parse::<u64>().ok()?;
Some(format!(
"{} files · {} (avg {})",
format_count(files),
format_bytes(total_bytes),
format_bytes(average_bytes)
))
}
pub(super) fn rollout_files_and_bytes(value: &str) -> Option<(u64, u64)> {
let (files, rest) = value.split_once(" files, ")?;
let (total_bytes, _) = rest.split_once(" total bytes, ")?;
Some((
files.trim().parse::<u64>().ok()?,
total_bytes.trim().parse::<u64>().ok()?,
))
}
pub(super) fn format_bytes(bytes: u64) -> String {
const KIB: f64 = 1024.0;
const MIB: f64 = KIB * 1024.0;
const GIB: f64 = MIB * 1024.0;
let bytes = bytes as f64;
if bytes >= GIB {
format!("{:.2} GB", bytes / GIB)
} else if bytes >= MIB {
format!("{:.2} MB", bytes / MIB)
} else if bytes >= KIB {
format!("{:.2} KB", bytes / KIB)
} else {
format!("{} B", bytes as u64)
}
}
pub(super) fn format_count(count: u64) -> String {
let mut digits = count.to_string();
let mut out = String::new();
while digits.len() > 3 {
let tail = digits.split_off(digits.len() - 3);
if out.is_empty() {
out = tail;
} else {
out = format!("{tail},{out}");
}
}
if out.is_empty() {
digits
} else {
format!("{digits},{out}")
}
}
fn parsed_details(check: &DoctorCheck) -> Vec<ParsedDetail> {
check
.details
.iter()
.map(|detail| redact_detail(detail))
.map(|detail| {
detail
.split_once(": ")
.map(|(label, value)| ParsedDetail {
label: label.to_string(),
value: value.to_string(),
})
.unwrap_or_else(|| ParsedDetail {
label: String::new(),
value: detail,
})
})
.collect()
}
fn runtime_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "version", "version");
push_row_if_present(&mut out, parsed, "install method", "install method");
push_row_if_present(&mut out, parsed, "commit", "commit");
push_row_if_present(&mut out, parsed, "current executable", "executable");
push_remaining(
&mut out,
parsed,
&[
"version",
"platform",
"install method",
"commit",
"current executable",
],
&[],
);
out
}
fn install_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "install context", "context");
if parsed.iter().any(|detail| {
detail.value == "ignored inherited package-manager launch env for cargo-built binary"
}) {
out.push(HumanDetail::Bullet(
"ignored inherited package-manager launch env for cargo-built binary".to_string(),
));
}
let managed_by_npm = value(parsed, "managed by npm").unwrap_or("false");
let managed_by_bun = value(parsed, "managed by bun").unwrap_or("false");
let managed_by_pnpm = value(parsed, "managed by pnpm").unwrap_or("false");
let managed_by_vite_plus = value(parsed, "managed by Vite+").unwrap_or("false");
let package_root = value(parsed, "managed package root").unwrap_or("not set");
out.push(HumanDetail::Row {
label: "managed by".to_string(),
value: format!(
"npm: {} · bun: {} · pnpm: {} · Vite+: {} · package root {}",
yes_no(managed_by_npm),
yes_no(managed_by_bun),
yes_no(managed_by_pnpm),
yes_no(managed_by_vite_plus),
if is_falsy(package_root) {
"—".to_string()
} else {
package_root.to_string()
}
),
expected: None,
});
let path_entries = numbered_values(parsed, "PATH codex #");
if !path_entries.is_empty() {
let total = path_entries.len();
let shown = if options.show_all {
total
} else {
total.min(3)
};
out.push(HumanDetail::Row {
label: format!("PATH entries ({total})"),
value: path_entries[0].clone(),
expected: None,
});
out.extend(
path_entries
.iter()
.skip(1)
.take(shown.saturating_sub(1))
.cloned()
.map(HumanDetail::Continuation),
);
if shown < total {
out.push(HumanDetail::Continuation(
"… (full list with --all)".to_string(),
));
}
}
push_remaining(
&mut out,
parsed,
&[
"current executable",
"install context",
"managed by npm",
"managed by bun",
"managed by pnpm",
"managed by Vite+",
"managed package root",
"PATH codex entries",
],
&["PATH codex #"],
);
out
}
fn git_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "selected git", "selected git");
push_row_if_present(&mut out, parsed, "git version", "version");
push_row_if_present(&mut out, parsed, "git exec path", "exec path");
push_row_if_present(&mut out, parsed, "repo detected", "repo detected");
push_row_if_present(&mut out, parsed, "repo root", "repo root");
push_row_if_present(&mut out, parsed, ".git entry", ".git entry");
push_row_if_present(&mut out, parsed, "git branch", "branch");
push_row_if_present(&mut out, parsed, "core.fsmonitor", "core.fsmonitor");
let path_entries = numbered_values(parsed, "PATH git #");
if !path_entries.is_empty() {
let total = path_entries.len();
let shown = if options.show_all {
total
} else {
total.min(3)
};
out.push(HumanDetail::Row {
label: format!("PATH entries ({total})"),
value: path_entries[0].clone(),
expected: None,
});
out.extend(
path_entries
.iter()
.skip(1)
.take(shown.saturating_sub(1))
.cloned()
.map(HumanDetail::Continuation),
);
if shown < total {
out.push(HumanDetail::Continuation(
"… (full list with --all)".to_string(),
));
}
}
push_remaining(
&mut out,
parsed,
&[
"selected git",
"PATH git entries",
"git version",
"git exec path",
"git build options",
"repo detected",
"repo root",
".git entry",
"git branch",
"core.fsmonitor",
],
&["PATH git #"],
);
out
}
fn title_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "terminal title source", "title source");
push_row_if_present(&mut out, parsed, "terminal title items", "title items");
push_row_if_present(&mut out, parsed, "terminal title activity", "activity item");
push_row_if_present(
&mut out,
parsed,
"terminal title project source",
"project source",
);
push_row_if_present(
&mut out,
parsed,
"terminal title project value",
"project value",
);
push_remaining(
&mut out,
parsed,
&[
"terminal title source",
"terminal title items",
"terminal title activity",
"terminal title project source",
"terminal title project value",
],
&[],
);
out
}
fn config_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
let mut out = Vec::new();
if let Some(model) = value(parsed, "model") {
let value = value(parsed, "model provider").map_or_else(
|| model.to_string(),
|provider| format!("{model} · {provider}"),
);
out.push(HumanDetail::Row {
label: "model".to_string(),
value,
expected: None,
});
}
push_row_if_present(&mut out, parsed, "cwd", "cwd");
push_row_if_present(&mut out, parsed, "config.toml", "config.toml");
push_row_if_present(&mut out, parsed, "config.toml parse", "config.toml parse");
push_row_if_present(&mut out, parsed, "config.toml read", "config.toml read");
push_row_if_present(&mut out, parsed, "mcp servers", "MCP servers");
push_feature_flags(&mut out, parsed, options);
for detail in parsed
.iter()
.filter(|detail| detail.label == "legacy feature flag")
{
out.push(HumanDetail::Row {
label: "legacy alias".to_string(),
value: detail.value.clone(),
expected: None,
});
}
push_remaining(
&mut out,
parsed,
&[
"CODEX_HOME",
"cwd",
"model",
"model provider",
"log dir",
"sqlite home",
"mcp servers",
"feature flags enabled",
"enabled feature flags",
"feature flag overrides",
"legacy feature flag",
"config.toml",
"config.toml parse",
"config.toml read",
],
&[],
);
out
}
fn state_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "CODEX_HOME", "CODEX_HOME");
push_row_if_present(&mut out, parsed, "log dir", "log dir");
push_row_if_present(&mut out, parsed, "sqlite home", "sqlite home");
push_database_row(&mut out, parsed, "state DB");
push_database_row(&mut out, parsed, "log DB");
push_database_row(&mut out, parsed, "goals DB");
push_database_row(&mut out, parsed, "memories DB");
for (source, label) in [
("active rollout files", "active rollouts"),
("archived rollout files", "archived rollouts"),
] {
if let Some(value) = value(parsed, source) {
out.push(HumanDetail::Row {
label: label.to_string(),
value: rollout_summary(value).unwrap_or_else(|| value.to_string()),
expected: None,
});
}
}
push_remaining(
&mut out,
parsed,
&[
"CODEX_HOME",
"log dir",
"sqlite home",
"state DB",
"log DB",
"goals DB",
"state DB integrity",
"log DB integrity",
"goals DB integrity",
"memories DB",
"memories DB integrity",
"active rollout files",
"archived rollout files",
],
&[],
);
out
}
fn generic_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
parsed
.iter()
.map(|detail| {
if detail.label.is_empty() {
HumanDetail::Bullet(detail.value.clone())
} else {
HumanDetail::Row {
label: display_label(&detail.label),
value: detail.value.clone(),
expected: None,
}
}
})
.collect()
}
fn push_feature_flags(
out: &mut Vec<HumanDetail>,
parsed: &[ParsedDetail],
options: HumanOutputOptions,
) {
let enabled_count = value(parsed, "feature flags enabled")
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or_default();
let overrides = list_items(value(parsed, "feature flag overrides").unwrap_or("none"));
let override_count = overrides.len();
let hint = if !options.show_all && enabled_count > 0 {
" (full list with --all)"
} else {
""
};
out.push(HumanDetail::Row {
label: "feature flags".to_string(),
value: format!("{enabled_count} enabled · {override_count} overridden{hint}"),
expected: None,
});
if !overrides.is_empty() {
push_list_row(out, "overrides", &override_names(&overrides), options);
}
if options.show_all {
let enabled = list_items(value(parsed, "enabled feature flags").unwrap_or("none"));
if !enabled.is_empty() {
push_list_row(out, "enabled flags", &enabled, options);
}
}
}
fn push_list_row(
out: &mut Vec<HumanDetail>,
label: &str,
items: &[String],
options: HumanOutputOptions,
) {
let limit = if options.show_all {
items.len()
} else {
items.len().min(LIST_LIMIT)
};
let mut value = items
.iter()
.take(limit)
.cloned()
.collect::<Vec<_>>()
.join(", ");
if limit < items.len() {
value.push_str(", … (full list with --all)");
}
out.push(HumanDetail::Row {
label: label.to_string(),
value,
expected: None,
});
}
fn push_database_row(out: &mut Vec<HumanDetail>, parsed: &[ParsedDetail], label: &str) {
let Some(path) = value(parsed, label) else {
return;
};
let integrity = value(parsed, &format!("{label} integrity"));
let value = integrity.map_or_else(
|| path.to_string(),
|integrity| format!("{path} · integrity {integrity}"),
);
out.push(HumanDetail::Row {
label: label.to_string(),
value,
expected: None,
});
}
fn push_row_if_present(
out: &mut Vec<HumanDetail>,
parsed: &[ParsedDetail],
source_label: &str,
display_label: &str,
) {
if let Some(value) = value(parsed, source_label) {
out.push(HumanDetail::Row {
label: display_label.to_string(),
value: value.to_string(),
expected: None,
});
}
}
fn push_remaining(
out: &mut Vec<HumanDetail>,
parsed: &[ParsedDetail],
consumed_labels: &[&str],
consumed_prefixes: &[&str],
) {
for detail in parsed {
if detail.value == "ignored inherited package-manager launch env for cargo-built binary" {
continue;
}
if consumed_labels.contains(&detail.label.as_str())
|| consumed_prefixes
.iter()
.any(|prefix| detail.label.starts_with(prefix))
{
continue;
}
if detail.label.is_empty() {
out.push(HumanDetail::Bullet(detail.value.clone()));
} else {
out.push(HumanDetail::Row {
label: display_label(&detail.label),
value: detail.value.clone(),
expected: None,
});
}
}
}
fn humanize_detail(detail: HumanDetail, options: HumanOutputOptions) -> HumanDetail {
match detail {
HumanDetail::Row {
label,
value,
expected,
} => HumanDetail::Row {
label,
value: humanize_value(&value, options),
expected,
},
HumanDetail::Continuation(value) => {
HumanDetail::Continuation(humanize_value(&value, options))
}
HumanDetail::Bullet(value) => HumanDetail::Bullet(humanize_value(&value, options)),
HumanDetail::Remedy(value) => HumanDetail::Remedy(value),
}
}
fn attach_issue_metadata(detail: HumanDetail, check: &DoctorCheck) -> HumanDetail {
let HumanDetail::Row {
label,
value,
expected,
} = detail
else {
return detail;
};
let expected = expected.or_else(|| issue_expected_for_label(check, &label));
HumanDetail::Row {
label,
value,
expected,
}
}
fn issue_expected_for_label(check: &DoctorCheck, label: &str) -> Option<String> {
check
.issues
.iter()
.find(|issue| {
issue
.fields
.iter()
.any(|field| display_label(field) == label || field == label)
})
.and_then(|issue| issue.expected.clone())
}
fn issue_remedies(check: &DoctorCheck) -> Vec<HumanDetail> {
let mut seen = BTreeSet::new();
check
.issues
.iter()
.filter_map(|issue| issue.remedy.as_ref())
.filter(|remedy| seen.insert((*remedy).clone()))
.cloned()
.map(HumanDetail::Remedy)
.collect()
}
fn humanize_value(value: &str, _options: HumanOutputOptions) -> String {
if looks_like_path(value) {
return shorten_path_prefix(value);
}
if let Some(timestamp) = humanize_timestamp(value) {
return timestamp;
}
value.to_string()
}
fn humanize_timestamp(value: &str) -> Option<String> {
if value.len() < 17 || !value.ends_with('Z') {
return None;
}
let (date, time) = value.split_once('T')?;
let hour_minute = time.get(..5)?;
Some(format!("{date} {hour_minute} UTC"))
}
fn shorten_path_prefix(value: &str) -> String {
let (path, suffix) = value.split_once(" (").map_or_else(
|| (value, String::new()),
|(path, suffix)| (path, format!(" ({suffix}")),
);
let home_shortened = home_shortened_path(path);
let shortened = middle_truncate(&home_shortened, PATH_LIMIT);
format!("{shortened}{suffix}")
}
fn home_shortened_path(path: &str) -> String {
let Some(home) = env::var_os("HOME").and_then(|home| home.into_string().ok()) else {
return path.to_string();
};
if path == home {
"~".to_string()
} else {
path.strip_prefix(&format!("{home}/"))
.map_or_else(|| path.to_string(), |tail| format!("~/{tail}"))
}
}
fn middle_truncate(value: &str, max_chars: usize) -> String {
let char_count = value.chars().count();
if char_count <= max_chars {
return value.to_string();
}
let head_len = max_chars / 2;
let tail_len = max_chars.saturating_sub(head_len + 1);
let head = value.chars().take(head_len).collect::<String>();
let tail = value
.chars()
.rev()
.take(tail_len)
.collect::<String>()
.chars()
.rev()
.collect::<String>();
format!("{head}…{tail}")
}
fn looks_like_path(value: &str) -> bool {
value.starts_with('/')
|| value.starts_with("~/")
|| value.starts_with("./")
|| value.starts_with("../")
}
fn numbered_values(parsed: &[ParsedDetail], prefix: &str) -> Vec<String> {
parsed
.iter()
.filter(|detail| detail.label.starts_with(prefix))
.map(|detail| detail.value.clone())
.collect()
}
fn value<'a>(parsed: &'a [ParsedDetail], label: &str) -> Option<&'a str> {
parsed
.iter()
.find(|detail| detail.label == label)
.map(|detail| detail.value.as_str())
}
fn display_label(label: &str) -> String {
match label {
"auth file" => "auth.json path (file backend/fallback)",
"codex-linux-sandbox helper" => "linux helper",
"optional reachability failed" => "optional reachability",
"check for update on startup" => "startup update check",
other => other,
}
.to_string()
}
fn list_items(value: &str) -> Vec<String> {
if is_falsy(value) {
return Vec::new();
}
value
.split(',')
.map(str::trim)
.filter(|item| !item.is_empty())
.map(str::to_string)
.collect()
}
fn override_names(items: &[String]) -> Vec<String> {
items
.iter()
.map(|item| item.split_once('=').map_or(item.as_str(), |(name, _)| name))
.map(str::to_string)
.collect()
}
fn yes_no(value: &str) -> &'static str {
if value == "true" { "yes" } else { "no" }
}
pub(super) fn is_falsy(value: &str) -> bool {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"" | "false" | "none" | "not set" | "unknown" | "missing" | "absent" | "no" | "—" | "-"
)
}

View File

@@ -0,0 +1,139 @@
use std::io;
use std::io::IsTerminal;
use std::io::Write;
use std::sync::Mutex;
use std::time::Duration;
use super::CheckStatus;
/// Receives check lifecycle events while doctor builds the final report.
///
/// Progress implementations must not write to stdout. The final report owns
/// stdout so JSON and redirected human reports stay clean.
pub(super) trait DoctorProgress: Send + Sync {
fn begin(&self, label: &'static str);
fn heartbeat(&self, label: &'static str, elapsed: Duration);
fn finish(&self, label: &'static str, status: CheckStatus);
fn settle(&self);
}
/// Selects the progress implementation for the current output mode.
///
/// JSON output is always quiet so stdout remains valid JSON. Human output uses a
/// transient stderr line only for interactive terminals, then clears it before
/// the final report is printed.
pub(super) fn doctor_progress(json: bool) -> std::sync::Arc<dyn DoctorProgress> {
if should_show_progress(
json,
std::env::var("TERM").ok().as_deref(),
io::stderr().is_terminal(),
) {
std::sync::Arc::new(StderrProgress::default())
} else {
std::sync::Arc::new(QuietProgress)
}
}
fn should_show_progress(json: bool, term: Option<&str>, stderr_is_tty: bool) -> bool {
!json && stderr_is_tty && term != Some("dumb")
}
struct QuietProgress;
impl DoctorProgress for QuietProgress {
fn begin(&self, _label: &'static str) {}
fn heartbeat(&self, _label: &'static str, _elapsed: Duration) {}
fn finish(&self, _label: &'static str, _status: CheckStatus) {}
fn settle(&self) {}
}
#[derive(Default)]
struct StderrProgress {
state: Mutex<StderrProgressState>,
}
#[derive(Default)]
struct StderrProgressState {
wrote_line: bool,
}
impl StderrProgress {
fn render(&self, message: String) {
let Ok(mut state) = self.state.lock() else {
return;
};
let mut stderr = io::stderr().lock();
let _ = write!(stderr, "\r\x1b[2K{message}");
let _ = stderr.flush();
state.wrote_line = true;
}
}
impl DoctorProgress for StderrProgress {
fn begin(&self, label: &'static str) {
self.render(format!("Checking {label}..."));
}
fn heartbeat(&self, label: &'static str, elapsed: Duration) {
self.render(format!("Still checking {label}... {}s", elapsed.as_secs()));
}
fn finish(&self, _label: &'static str, _status: CheckStatus) {}
fn settle(&self) {
let Ok(mut state) = self.state.lock() else {
return;
};
if !state.wrote_line {
return;
}
let mut stderr = io::stderr().lock();
let _ = write!(stderr, "\r\x1b[2K");
let _ = stderr.flush();
state.wrote_line = false;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn progress_is_quiet_for_json() {
assert!(!should_show_progress(
/*json*/ true,
Some("xterm-256color"),
/*stderr_is_tty*/ true,
));
}
#[test]
fn progress_is_quiet_for_non_tty() {
assert!(!should_show_progress(
/*json*/ false,
Some("xterm-256color"),
/*stderr_is_tty*/ false,
));
}
#[test]
fn progress_is_quiet_for_dumb_terminal() {
assert!(!should_show_progress(
/*json*/ false,
Some("dumb"),
/*stderr_is_tty*/ true,
));
}
#[test]
fn progress_is_shown_for_human_tty_output() {
assert!(should_show_progress(
/*json*/ false,
Some("xterm-256color"),
/*stderr_is_tty*/ true,
));
}
}

View File

@@ -0,0 +1,145 @@
//! Captures how this Codex process was launched.
//!
//! Runtime diagnostics answer provenance questions that are hard to infer from
//! user reports: which binary is running, which install channel it resembles,
//! which platform it targets, and whether the search command comes from bundled
//! package files or from PATH.
use std::env;
use codex_install_context::InstallContext;
use codex_install_context::InstallMethod;
use super::CheckStatus;
use super::DoctorCheck;
use super::describe_install_context;
use super::doctor_install_context;
use super::push_path_detail;
/// Builds the process provenance row for the current Codex executable.
///
/// This check is informational and should not fail on its own; inconsistent
/// install state is reported by the installation and update checks instead.
pub(super) fn runtime_check() -> DoctorCheck {
let current_exe = env::current_exe().ok();
let install_context = doctor_install_context(current_exe.as_deref());
let os = env::consts::OS;
let arch = env::consts::ARCH;
let platform = format!("{os}-{arch}");
let install_method = install_method_name(&install_context);
let mut details = vec![
format!("version: {}", env!("CARGO_PKG_VERSION")),
format!("platform: {platform}"),
format!(
"install method: {}",
describe_install_context(&install_context)
),
format!("commit: {}", build_commit()),
];
push_path_detail(&mut details, "current executable", current_exe.as_deref());
DoctorCheck::new(
"runtime.provenance",
"runtime",
CheckStatus::Ok,
format!("running {install_method} on {platform}"),
)
.details(details)
}
/// Inspects the search command selected by the install context without executing it.
///
/// Package-layout installs should point at a bundled ripgrep binary, while local
/// installs without that layout usually resolve rg from PATH. A warning here
/// means features that depend on file search may degrade even when the CLI
/// launches.
pub(super) fn search_check() -> DoctorCheck {
let current_exe = env::current_exe().ok();
let install_context = doctor_install_context(current_exe.as_deref());
let rg_command = install_context.rg_command();
let provider = search_provider(&install_context);
let mut details = vec![
format!("search command: {}", rg_command.display()),
format!("search provider: {provider}"),
];
let status = if rg_command.components().count() > 1 {
match std::fs::metadata(&rg_command) {
Ok(metadata) if metadata.is_file() => {
details.push("search command readiness: file exists".to_string());
CheckStatus::Ok
}
Ok(_) => {
details.push("search command readiness: path is not a file".to_string());
CheckStatus::Warning
}
Err(err) => {
details.push(format!("search command readiness: {err}"));
CheckStatus::Warning
}
}
} else {
match which::which(&rg_command) {
Ok(path) => {
details.push(format!("search command path: {}", path.display()));
details.push("search command readiness: found; execution not verified".to_string());
CheckStatus::Ok
}
Err(err) => {
details.push(format!("search command readiness: {err}"));
CheckStatus::Warning
}
}
};
let summary = match status {
CheckStatus::Ok => format!("search command found ({provider}); execution not verified"),
CheckStatus::Warning => "search command could not be verified".to_string(),
CheckStatus::Fail => unreachable!(),
};
let mut check = DoctorCheck::new("runtime.search", "search", status, summary).details(details);
if status != CheckStatus::Ok {
check = check.remediation("Install ripgrep or repair the bundled Codex package.");
}
check
}
fn install_method_name(context: &InstallContext) -> &'static str {
match &context.method {
InstallMethod::Standalone { .. } => "standalone",
InstallMethod::Npm => "npm",
InstallMethod::Bun => "bun",
InstallMethod::VitePlus => "vite+",
InstallMethod::Pnpm => "pnpm",
InstallMethod::Brew => "brew",
InstallMethod::Other => "local build",
}
}
fn search_provider(context: &InstallContext) -> &'static str {
let rg_command = context.rg_command();
let from_package_layout = context
.package_layout
.as_ref()
.and_then(|package_layout| package_layout.path_dir.as_ref())
.is_some_and(|path_dir| rg_command.starts_with(path_dir));
let from_legacy_standalone = matches!(
&context.method,
InstallMethod::Standalone {
resources_dir: Some(resources_dir),
..
} if rg_command.starts_with(resources_dir)
);
if from_package_layout || from_legacy_standalone {
"bundled"
} else {
"system"
}
}
fn build_commit() -> &'static str {
option_env!("CODEX_BUILD_COMMIT")
.or(option_env!("GIT_COMMIT"))
.unwrap_or("unknown")
}

View File

@@ -0,0 +1,357 @@
#[cfg(target_os = "windows")]
use std::fs;
#[cfg(target_os = "windows")]
use std::io;
use codex_arg0::Arg0DispatchPaths;
use codex_config::RequirementSource;
use codex_core::config::Config;
#[cfg(target_os = "windows")]
use codex_core::windows_sandbox::WindowsSandboxLevelExt;
#[cfg(target_os = "windows")]
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
#[cfg(target_os = "windows")]
use codex_sandboxing::windows_sandbox_uses_elevated_backend;
#[cfg(target_os = "windows")]
use codex_windows_sandbox::SetupErrorCode;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::NERR_Success as NERR_SUCCESS;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::NERR_UserNotFound as NERR_USER_NOT_FOUND;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::NetApiBufferFree;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::NetUserGetInfo;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::UF_LOCKOUT;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::UF_PASSWORD_EXPIRED;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::USER_INFO_23;
use super::CheckStatus;
use super::DoctorCheck;
#[cfg(target_os = "windows")]
use super::DoctorIssue;
use super::push_path_detail;
#[cfg(target_os = "windows")]
const WINDOWS_SETUP_REMEDIATION: &str = "run codex sandbox setup --elevated --user <end-user> --codex-home <authoritative-home> from an elevated shell";
pub(super) fn sandbox_check(config: &Config, arg0_paths: &Arg0DispatchPaths) -> DoctorCheck {
let mut details = Vec::new();
details.push(format!(
"approval policy: {:?}",
config.permissions.approval_policy.value()
));
let file_system_sandbox = config.permissions.file_system_sandbox_policy();
details.push(format!("filesystem sandbox: {}", file_system_sandbox.kind));
let denied_entries = file_system_sandbox
.entries
.iter()
.filter(|entry| entry.access == FileSystemAccessMode::Deny);
details.push(format!(
"denied-read rules: {}",
denied_entries.clone().count()
));
details.push(format!(
"denied-read glob rules: {}",
denied_entries
.filter(|entry| matches!(entry.path, FileSystemPath::GlobPattern { .. }))
.count()
));
details.push(format!(
"glob scan max depth: {}",
file_system_sandbox
.glob_scan_max_depth
.map_or_else(|| "unbounded".to_string(), |depth| depth.to_string())
));
details.push(format!(
"managed filesystem source: {}",
match config
.config_layer_stack
.requirements()
.filesystem
.as_ref()
.map(|value| &value.source)
{
None => "none",
Some(RequirementSource::Unknown) => "unknown",
Some(RequirementSource::EnterpriseManaged { .. }) => "cloud",
Some(RequirementSource::Composite { .. }) => "multiple layers",
Some(RequirementSource::MdmManagedPreferences { .. }) => "MDM",
Some(RequirementSource::SystemRequirementsToml { .. }) => "system",
Some(RequirementSource::LegacyManagedConfigTomlFromFile { .. }) => "legacy file",
Some(RequirementSource::LegacyManagedConfigTomlFromMdm) => "legacy MDM",
}
));
details.push(format!(
"network sandbox: {}",
config.permissions.network_sandbox_policy()
));
push_path_detail(
&mut details,
"codex-linux-sandbox helper",
arg0_paths.codex_linux_sandbox_exe.as_deref(),
);
let mut status = CheckStatus::Ok;
let mut summary = "sandbox configuration is readable".to_string();
if let Some(helper) = arg0_paths.codex_linux_sandbox_exe.as_deref()
&& !helper.exists()
{
status = CheckStatus::Warning;
summary = "Linux sandbox helper path does not exist".to_string();
}
let check = DoctorCheck::new("sandbox.helpers", "sandbox", status, summary).details(details);
#[cfg(target_os = "windows")]
let mut check = check;
#[cfg(target_os = "windows")]
{
let configured_level = WindowsSandboxLevel::from_config(config);
let mxc = config.effective_local_windows_sandbox_type()
== codex_protocol::sandbox::SandboxType::WindowsMxc;
let elevated = !mxc
&& configured_level != WindowsSandboxLevel::Disabled
&& windows_sandbox_uses_elevated_backend(configured_level);
let backend = if mxc {
"mxc".to_string()
} else if elevated {
WindowsSandboxLevel::Elevated.to_string()
} else {
configured_level.to_string()
};
let denied = !file_system_sandbox.has_full_disk_read_access();
check.details.push(format!("sandbox backend: {backend}"));
check
.details
.push(format!("denied-read restrictions: {denied}"));
if denied && !elevated && !mxc {
check.issues.push(
DoctorIssue::new(
CheckStatus::Fail,
"managed denied-read requirements need the elevated Windows sandbox backend",
)
.measured(format!("{backend} backend"))
.expected("elevated backend")
.remedy("enable the elevated Windows sandbox backend permitted by managed policy")
.field("sandbox backend")
.field("denied-read restrictions"),
);
}
if elevated {
let home = config.codex_home.as_path();
let path = codex_windows_sandbox::setup_error_path(home);
let report = match fs::metadata(&path) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Ok(metadata) if metadata.is_file() && metadata.len() <= 64 * 1024 => {
codex_windows_sandbox::read_setup_error_report(home)
.map_err(|error| error.to_string())
}
Ok(metadata) if !metadata.is_file() => Err("not a regular file".to_string()),
Ok(_) => Err("larger than 64 KiB".to_string()),
Err(error) => Err(error.to_string()),
};
let report = match report {
Ok(report) => report,
Err(error) => {
check
.details
.push("setup failure report: unreadable".to_string());
check.issues.push(
DoctorIssue::new(
CheckStatus::Warning,
"Windows sandbox setup failure report could not be read",
)
.measured(error)
.expected("readable setup failure report no larger than 64 KiB")
.remedy(WINDOWS_SETUP_REMEDIATION)
.field("setup failure report"),
);
None
}
};
if report.is_none() && codex_windows_sandbox::sandbox_setup_is_complete(home) {
check
.details
.push("sandbox provisioning: complete".to_string());
for username in [
codex_windows_sandbox::OFFLINE_USERNAME,
codex_windows_sandbox::ONLINE_USERNAME,
] {
let username_wide = username.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
let mut buffer = std::ptr::null_mut();
let status = unsafe {
NetUserGetInfo(
std::ptr::null(),
username_wide.as_ptr(),
/*level*/ 23,
&mut buffer,
)
};
let flags = if status == NERR_SUCCESS && !buffer.is_null() {
Some(unsafe { (*(buffer as *const USER_INFO_23)).usri23_flags })
} else {
None
};
if !buffer.is_null() {
unsafe { NetApiBufferFree(buffer.cast()) };
}
let (severity, cause, remediation) = match (status, flags) {
(NERR_USER_NOT_FOUND, _) => (
CheckStatus::Fail,
"a Windows sandbox account is missing",
WINDOWS_SETUP_REMEDIATION,
),
(NERR_SUCCESS, Some(flags)) if flags & UF_LOCKOUT != 0 => (
CheckStatus::Fail,
"a Windows sandbox account is locked",
"stop sandbox retries and ask IT to unlock the account",
),
(NERR_SUCCESS, Some(flags)) if flags & UF_ACCOUNTDISABLE != 0 => (
CheckStatus::Fail,
"a Windows sandbox account is disabled",
"ask IT to enable the sandbox account before rerunning setup",
),
(NERR_SUCCESS, Some(flags)) if flags & UF_PASSWORD_EXPIRED != 0 => (
CheckStatus::Fail,
"a Windows sandbox account password has expired",
WINDOWS_SETUP_REMEDIATION,
),
(NERR_SUCCESS, Some(_)) => continue,
(ERROR_ACCESS_DENIED, _) => (
CheckStatus::Warning,
"Windows sandbox account status could not be inspected",
"ask IT to inspect access to the local sandbox accounts",
),
_ => (
CheckStatus::Warning,
"Windows sandbox account status could not be inspected",
"ask IT to inspect the local sandbox accounts",
),
};
check.details.push(format!("sandbox account: {username}"));
if !matches!(
status,
NERR_SUCCESS | NERR_USER_NOT_FOUND | ERROR_ACCESS_DENIED
) {
check
.details
.push(format!("account query status: {status}"));
}
check.issues.push(
DoctorIssue::new(severity, cause)
.measured(username)
.expected("enabled, unlocked local sandbox account")
.remedy(remediation)
.field("sandbox account"),
);
}
} else {
check.details.push(if report.is_some() {
"sandbox provisioning: failed".to_string()
} else {
"sandbox provisioning: incomplete".to_string()
});
if let Some(report) = report {
let remediation = match report.code {
SetupErrorCode::OrchestratorElevationCheckFailed
| SetupErrorCode::OrchestratorElevationRequired
| SetupErrorCode::OrchestratorHelperLaunchCanceled => {
"use an elevated shell or your organization's approved elevation workflow"
}
SetupErrorCode::OrchestratorHelperLaunchFailed
| SetupErrorCode::OrchestratorHelperExitNonzero
| SetupErrorCode::OrchestratorHelperReportReadFailed
| SetupErrorCode::OrchestratorHelperIncomplete
| SetupErrorCode::HelperReadAclHelperSpawnFailed => {
"repair the installed Codex helpers or ask IT to allow their execution"
}
SetupErrorCode::HelperUserProvisionFailed
| SetupErrorCode::HelperUsersGroupCreateFailed
| SetupErrorCode::HelperUserCreateOrUpdateFailed
| SetupErrorCode::HelperSidResolveFailed
| SetupErrorCode::HelperCapabilitySidFailed => {
"ask IT to allow the managed local sandbox accounts and group"
}
SetupErrorCode::OrchestratorSandboxDirCreateFailed
| SetupErrorCode::HelperSandboxDirCreateFailed
| SetupErrorCode::HelperLogFailed
| SetupErrorCode::HelperDpapiProtectFailed
| SetupErrorCode::HelperUsersFileWriteFailed
| SetupErrorCode::HelperSetupMarkerWriteFailed
| SetupErrorCode::HelperSandboxLockFailed => {
"rerun elevated setup for the authoritative Codex home or ask IT"
}
SetupErrorCode::HelperFirewallComInitFailed
| SetupErrorCode::HelperFirewallPolicyAccessFailed
| SetupErrorCode::HelperFirewallPolicyIneffective
| SetupErrorCode::HelperFirewallRuleCreateOrAddFailed
| SetupErrorCode::HelperFirewallRuleVerifyFailed => {
"ask IT to allow Codex sandbox rules in managed Windows Firewall policy"
}
SetupErrorCode::OrchestratorPayloadSerializeFailed
| SetupErrorCode::HelperRequestArgsFailed
| SetupErrorCode::HelperUnknownError => {
"repair or reinstall the Codex CLI from an approved distribution"
}
};
check
.details
.push(format!("error code: {}", report.code.as_str()));
check.issues.push(
DoctorIssue::new(
CheckStatus::Fail,
"elevated Windows sandbox provisioning recorded a structured failure",
)
.measured(report.code.as_str())
.remedy(remediation)
.field("error code"),
);
} else {
check.issues.push(
DoctorIssue::new(
CheckStatus::Warning,
"elevated Windows sandbox provisioning is incomplete or outdated",
)
.remedy(WINDOWS_SETUP_REMEDIATION)
.field("sandbox provisioning"),
);
}
}
}
if let Some(severity) = check.issues.iter().map(|issue| issue.severity).max() {
check.status = check.status.max(severity);
check.summary = if check.issues.len() == 1 {
check.issues[0].cause.clone()
} else {
"Windows sandbox has multiple configuration or provisioning issues".to_string()
};
if check.remediation.is_none() {
check.remediation = check.issues.iter().find_map(|issue| issue.remedy.clone());
}
}
}
check
}
#[cfg(test)]
#[path = "sandbox_tests.rs"]
mod tests;

View File

@@ -0,0 +1,160 @@
use codex_arg0::Arg0DispatchPaths;
use codex_core::config::ConfigBuilder;
use pretty_assertions::assert_eq;
use super::CheckStatus;
use super::sandbox_check;
#[tokio::test]
async fn reports_missing_linux_sandbox_helper() {
let home = tempfile::tempdir().expect("create Codex home");
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.expect("load sandbox config");
let arg0_paths = Arg0DispatchPaths {
codex_linux_sandbox_exe: Some(home.path().join("missing-linux-helper")),
..Default::default()
};
let check = sandbox_check(&config, &arg0_paths);
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(check.summary, "Linux sandbox helper path does not exist");
}
#[cfg(target_os = "windows")]
#[tokio::test]
async fn reports_refresh_failure_after_setup_completed() {
let home = tempfile::tempdir().expect("create Codex home");
let version = codex_windows_sandbox::SETUP_VERSION;
for (path, contents) in [
(
".sandbox/setup_marker.json",
serde_json::json!({
"version": version,
"offline_username": codex_windows_sandbox::OFFLINE_USERNAME,
"online_username": codex_windows_sandbox::ONLINE_USERNAME,
}),
),
(
".sandbox-secrets/sandbox_users.json",
serde_json::json!({
"version": version,
"offline": {
"username": codex_windows_sandbox::OFFLINE_USERNAME,
"password": "",
},
"online": {
"username": codex_windows_sandbox::ONLINE_USERNAME,
"password": "",
},
}),
),
] {
let path = home.path().join(path);
std::fs::create_dir_all(path.parent().expect("fixture parent"))
.expect("create fixture directory");
std::fs::write(path, contents.to_string()).expect("write sandbox fixture");
}
assert!(codex_windows_sandbox::sandbox_setup_is_complete(
home.path()
));
codex_windows_sandbox::write_setup_error_report(
home.path(),
&codex_windows_sandbox::SetupErrorReport {
code: codex_windows_sandbox::SetupErrorCode::HelperFirewallPolicyIneffective,
message: "firewall policy rejected the refresh".to_string(),
},
)
.expect("write refresh failure");
std::fs::write(
home.path().join("config.toml"),
"[windows]\nsandbox = \"elevated\"\n",
)
.expect("write elevated sandbox config");
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.expect("load sandbox config");
let check = sandbox_check(&config, &Arg0DispatchPaths::default());
assert_eq!(check.status, CheckStatus::Fail);
assert_eq!(
check.issues[0].measured.as_deref(),
Some("helper_firewall_policy_ineffective")
);
}
#[cfg(target_os = "windows")]
#[tokio::test]
async fn rejects_oversized_setup_failure_reports() {
let home = tempfile::tempdir().expect("create Codex home");
codex_windows_sandbox::write_setup_error_report(
home.path(),
&codex_windows_sandbox::SetupErrorReport {
code: codex_windows_sandbox::SetupErrorCode::HelperFirewallPolicyIneffective,
message: "x".repeat(64 * 1024),
},
)
.expect("write oversized setup failure");
std::fs::write(
home.path().join("config.toml"),
"[windows]\nsandbox = \"elevated\"\n",
)
.expect("write elevated sandbox config");
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.expect("load sandbox config");
let check = sandbox_check(&config, &Arg0DispatchPaths::default());
assert_eq!(check.status, CheckStatus::Warning);
assert!(
check
.details
.contains(&"setup failure report: unreadable".to_string())
);
assert_eq!(
check.issues[0].cause,
"Windows sandbox setup failure report could not be read"
);
assert_eq!(
check.issues[0].measured.as_deref(),
Some("larger than 64 KiB")
);
}
#[cfg(target_os = "windows")]
#[tokio::test]
async fn reports_malformed_setup_failure_reports() {
let home = tempfile::tempdir().expect("create Codex home");
let path = codex_windows_sandbox::setup_error_path(home.path());
std::fs::create_dir_all(path.parent().expect("setup failure report parent"))
.expect("create sandbox directory");
std::fs::write(path, "{").expect("write malformed setup failure report");
std::fs::write(
home.path().join("config.toml"),
"[windows]\nsandbox = \"elevated\"\n",
)
.expect("write elevated sandbox config");
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.expect("load sandbox config");
let check = sandbox_check(&config, &Arg0DispatchPaths::default());
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(
check.issues[0].cause,
"Windows sandbox setup failure report could not be read"
);
assert!(check.issues[0].measured.is_some());
}

View File

@@ -0,0 +1,254 @@
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::ffi::OsStr;
#[cfg(target_os = "windows")]
use std::path::PathBuf;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::process::Output;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::process::Stdio;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::time::Duration;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use tokio::process::Command;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use tokio::time::timeout;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorIssue;
#[cfg(any(target_os = "macos", target_os = "windows"))]
const PRODUCT_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(any(target_os = "macos", target_os = "windows"))]
const MAX_PRODUCT_OUTPUT_BYTES: usize = 64 * 1024;
pub(super) enum EndpointInspection {
Complete(Vec<&'static str>),
#[cfg(any(target_os = "windows", test))]
Partial(Vec<&'static str>),
#[cfg(any(target_os = "macos", target_os = "windows", test))]
Unavailable,
}
pub(super) async fn check() -> DoctorCheck {
endpoint_check(endpoint_products().await)
}
pub(super) fn endpoint_check(inspection: EndpointInspection) -> DoctorCheck {
let (products, visibility_incomplete) = match inspection {
EndpointInspection::Complete(products) => (products, false),
#[cfg(any(target_os = "windows", test))]
EndpointInspection::Partial(products) => (products, true),
#[cfg(any(target_os = "macos", target_os = "windows", test))]
EndpointInspection::Unavailable => {
return DoctorCheck::new(
"security.endpoint",
"security",
CheckStatus::Warning,
"endpoint protection inspection unavailable",
)
.detail("endpoint products: unavailable");
}
};
if products.is_empty() {
let (summary, detail) = if cfg!(any(target_os = "macos", target_os = "windows")) {
("no supported endpoint protection detected", "none detected")
} else {
(
"endpoint protection is not inspected on this platform",
"not inspected on this platform",
)
};
return DoctorCheck::new("security.endpoint", "security", CheckStatus::Ok, summary)
.detail(format!("endpoint products: {detail}"));
}
let targets = if cfg!(target_os = "windows") {
"signed Codex app; codex.exe; codex-windows-sandbox-setup.exe; codex-command-runner.exe; codex-code-mode-host.exe"
} else if cfg!(target_os = "macos") {
"signing team 2DC432GLL2 plus the installed Codex app identity, signed codex agent, and required helpers"
} else {
"verified Codex app, codex agent, and required helpers"
};
let mut check = DoctorCheck::new(
"security.endpoint",
"security",
CheckStatus::Warning,
"endpoint protection detected; Codex exclusions are unverified",
)
.detail(format!("endpoint products: {}", products.join(", ")))
.detail(format!("exclusion targets: {targets}"))
.detail("Codex exclusions: not verified")
.remediation(
"ask your security administrator to verify Codex exclusions and required helper allowances",
);
if visibility_incomplete {
check = check.detail("additional endpoint products: unavailable");
}
for product in products {
let remedy = match product {
"CrowdStrike Falcon" => {
"CrowdStrike Falcon: Add a certificate or IOA exclusion for Codex. If sensor overhead continues, exclude the Codex agent from sensor visibility. Keep monitoring descendant processes."
}
"BeyondTrust Privilege Management" => {
"BeyondTrust: Remove Codex from application blocking rules. Add allow rules for Codex helper executables. Do not grant administrator privileges."
}
"Microsoft Defender" => {
"Microsoft Defender: Add a certificate or executable-path exclusion for Codex and its helpers. If Attack Surface Reduction blocks Codex, add a rule exclusion. If Controlled Folder Access blocks Codex, allow the app."
}
"SentinelOne" => {
"SentinelOne: Add a signer, file-hash, or executable-path exclusion for Codex and its helpers."
}
"Jamf Protect" => {
"Jamf Protect: Add an Override Threat Prevention exception for Codex app and helper signing identities. If analytics cause delays, add an Ignore System Events for Analytics exception."
}
_ => {
"Add an exclusion for Codex and its helpers. Use the endpoint product instructions."
}
};
check = check.issue(
DoctorIssue::new(
CheckStatus::Warning,
format!("{product} can interfere with Codex. Verify Codex exclusions."),
)
.measured("not verified")
.expected("Codex application and helper exclusions")
.remedy(remedy)
.field("Codex exclusions"),
);
}
check
}
async fn endpoint_products() -> EndpointInspection {
#[cfg(target_os = "windows")]
{
let system32 = std::env::var_os("SystemRoot")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(r"C:\Windows"))
.join("System32");
let service = system32.join("sc.exe");
let (crowdstrike, beyondtrust, defender, sentinelone) = tokio::join!(
product_command(&service, &["query", "CSFalconService"]),
product_command(&service, &["query", "DefendpointService"]),
product_command(&service, &["query", "WinDefend"]),
product_command(&service, &["query", "SentinelAgent"]),
);
let mut products = Vec::new();
let mut visibility_incomplete = false;
for (product, output) in [
("CrowdStrike Falcon", crowdstrike),
("BeyondTrust Privilege Management", beyondtrust),
("Microsoft Defender", defender),
("SentinelOne", sentinelone),
] {
match output {
Some(output) if output.status.success() => {
if product != "Microsoft Defender"
|| String::from_utf8_lossy(&output.stdout).lines().any(|line| {
line.split_once(':').is_some_and(|(_, value)| {
value.split_whitespace().next() == Some("4")
})
})
{
products.push(product);
}
}
Some(output) if output.status.code() == Some(1060) => {}
Some(_) | None => visibility_incomplete = true,
}
}
if visibility_incomplete {
if products.is_empty() {
EndpointInspection::Unavailable
} else {
EndpointInspection::Partial(products)
}
} else {
EndpointInspection::Complete(products)
}
}
#[cfg(target_os = "macos")]
{
const PRODUCTS: &[(&str, &str, &str)] = &[
(
"CrowdStrike Falcon",
"X9E956P446",
"com.crowdstrike.falcon.Agent",
),
(
"BeyondTrust Privilege Management",
"2ZS8T6NYB8",
"com.beyondtrust.endpointsecurity",
),
(
"Microsoft Defender",
"UBF8T346G9",
"com.microsoft.wdav.epsext",
),
(
"SentinelOne",
"4AYE5J54KN",
"com.sentinelone.network-monitoring",
),
(
"Jamf Protect",
"483DWKW443",
"com.jamf.protect.security-extension",
),
];
let Some(output) = product_command("/usr/bin/systemextensionsctl", &["list"])
.await
.filter(|output| output.status.success())
else {
return EndpointInspection::Unavailable;
};
EndpointInspection::Complete(
String::from_utf8_lossy(&output.stdout)
.lines()
.filter_map(|line| {
let mut columns = line.split_whitespace();
if columns.next() != Some("*") || columns.next() != Some("*") {
return None;
}
let team = columns.next()?;
let bundle = columns.next()?;
PRODUCTS.iter().find_map(|&(name, signer, identifier)| {
(team == signer && bundle == identifier).then_some(name)
})
})
.collect(),
)
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
EndpointInspection::Complete(Vec::new())
}
}
#[cfg(any(target_os = "macos", target_os = "windows"))]
async fn product_command(program: impl AsRef<OsStr>, args: &[&str]) -> Option<Output> {
let mut command = Command::from(codex_utils_process::background_command(program));
command
.args(args)
.stdin(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
timeout(PRODUCT_QUERY_TIMEOUT, command.output())
.await
.ok()?
.ok()
.filter(|output| output.stdout.len() <= MAX_PRODUCT_OUTPUT_BYTES)
}
#[cfg(test)]
#[path = "security_tests.rs"]
mod tests;

View File

@@ -0,0 +1,184 @@
use pretty_assertions::assert_eq;
use super::super::redacted_json_check;
use super::CheckStatus;
use super::EndpointInspection;
use super::endpoint_check;
#[test]
fn no_endpoint_products_require_no_remediation() {
let check = endpoint_check(EndpointInspection::Complete(Vec::new()));
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(check.remediation, None);
assert!(check.issues.is_empty());
}
#[test]
fn unavailable_endpoint_inspection_does_not_require_remediation() {
let check = endpoint_check(EndpointInspection::Unavailable);
assert_eq!(check.status, CheckStatus::Warning);
assert!(check.summary.to_ascii_lowercase().contains("unavailable"));
assert_eq!(check.details, vec!["endpoint products: unavailable"]);
assert_eq!(check.remediation, None);
assert!(check.issues.is_empty());
}
#[test]
fn each_endpoint_product_requires_vendor_specific_app_exclusions() {
let cases: [(&str, &[&str]); 5] = [
("CrowdStrike Falcon", &["certificate", "ioa"]),
("BeyondTrust Privilege Management", &["application"]),
("Microsoft Defender", &["executable", "path", "certificate"]),
("SentinelOne", &["signer", "hash", "path"]),
("Jamf Protect", &["threat prevention"]),
];
for (product, strategies) in cases {
let check = endpoint_check(EndpointInspection::Complete(vec![product]));
assert_eq!(check.status, CheckStatus::Warning, "{product}");
assert!(
check
.details
.iter()
.any(|detail| detail.starts_with("exclusion targets: ")),
"{product}: {:?}",
check.details
);
let remediation = check
.remediation
.as_deref()
.expect("detected endpoint protection should require remediation")
.to_ascii_lowercase();
assert_eq!(
remediation,
"ask your security administrator to verify codex exclusions and required helper allowances",
"{product}"
);
assert!(
!serde_json::to_string(&redacted_json_check(&check))
.expect("serialize endpoint check")
.to_ascii_lowercase()
.contains("chatgpt"),
"{product}: endpoint diagnostics should only refer to Codex"
);
assert_eq!(check.issues.len(), 1, "{product}");
let issue = &check.issues[0];
assert_eq!(issue.severity, CheckStatus::Warning, "{product}");
assert!(
issue
.cause
.to_ascii_lowercase()
.contains(&product.to_ascii_lowercase()),
"{product}: {}",
issue.cause
);
assert!(
issue.cause.contains("Verify Codex exclusions."),
"{product}: {}",
issue.cause
);
let remedy = issue
.remedy
.as_deref()
.expect("endpoint product should have vendor-specific guidance")
.to_ascii_lowercase();
assert!(
strategies.iter().any(|strategy| remedy.contains(strategy)),
"{product}: {remedy}"
);
assert!(!remedy.contains("administrator-approved"), "{product}");
assert!(!remedy.contains(';'), "{product}");
for sentence in remedy.split('.') {
assert!(
sentence.split_whitespace().count() <= 20,
"{product}: {sentence}"
);
}
if product == "BeyondTrust Privilege Management" {
assert!(remedy.contains("rule"), "{product}: {remedy}");
assert!(remedy.contains("blocking"), "{product}: {remedy}");
assert!(
remedy.contains("do not grant administrator privileges"),
"{product}: {remedy}"
);
}
if product == "Microsoft Defender" {
assert!(
remedy.contains("attack surface reduction"),
"{product}: {remedy}"
);
assert!(
remedy.contains("controlled folder access"),
"{product}: {remedy}"
);
}
if product == "CrowdStrike Falcon" {
assert!(remedy.contains("sensor visibility"), "{product}: {remedy}");
assert!(remedy.contains("descendant"), "{product}: {remedy}");
}
if product == "Jamf Protect" {
assert!(remedy.contains("exception"), "{product}: {remedy}");
assert!(remedy.contains("signing"), "{product}: {remedy}");
}
}
}
#[test]
fn multiple_endpoint_products_each_get_distinct_guidance() {
let products = ["CrowdStrike Falcon", "Microsoft Defender"];
let check = endpoint_check(EndpointInspection::Complete(products.to_vec()));
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(check.issues.len(), products.len());
for product in products {
let matching_issues = check
.issues
.iter()
.filter(|issue| {
issue
.cause
.to_ascii_lowercase()
.contains(&product.to_ascii_lowercase())
})
.count();
assert_eq!(matching_issues, 1, "{product}");
}
}
#[test]
fn endpoint_product_guidance_preserves_structured_json_contract() {
let check = endpoint_check(EndpointInspection::Complete(vec!["Microsoft Defender"]));
let json = serde_json::to_value(redacted_json_check(&check)).expect("serialize endpoint check");
assert_eq!(json["id"], "security.endpoint");
assert_eq!(json["category"], "security");
assert_eq!(json["status"], "warning");
assert_eq!(json["details"]["endpoint products"], "Microsoft Defender");
assert!(json["details"]["exclusion targets"].is_string());
assert_eq!(json["issues"].as_array().map(Vec::len), Some(1));
assert!(json["issues"][0]["remedy"].is_string());
}
#[test]
fn detected_products_preserve_partial_inspection_visibility() {
let check = endpoint_check(EndpointInspection::Partial(vec!["Microsoft Defender"]));
assert_eq!(check.status, CheckStatus::Warning);
assert!(
check
.details
.contains(&"additional endpoint products: unavailable".to_string())
);
assert_eq!(check.issues.len(), 1);
}

View File

@@ -0,0 +1,9 @@
---
source: cli/src/doctor/background.rs
expression: details
---
update-loop pid file: CODEX_HOME/app-server-daemon/app-server-updater.pid (missing)
dedicated pid file: CODEX_HOME/app-server-daemon/daemon.pid (missing)
dedicated update-loop pid file: CODEX_HOME/app-server-daemon/daemon-updater.pid (missing)
automatic updates: disabled (configured)
update interval: 90 minutes (configured)

View File

@@ -0,0 +1,26 @@
---
source: cli/src/doctor/filesystem_paths_tests.rs
expression: "super::super::render_human_report(&report, super::super::HumanOutputOptions\n{ show_details: true, show_all: false, ascii: true, color_enabled: false, },)"
---
Codex Doctor vtest
Configuration
[ok] sandbox configured filesystem paths listed; read restrictions prevent probes
permission profile diagnostic
operation resolve paths only; read/write access is not tested
probe budgets 2 seconds per path, 8 seconds total, at most 32 paths
path 1 FIXTURE/unavailable (read); not probed (filesystem read restrictions apply)
path 1 source permissions.diagnostic.filesystem.FIXTURE/unavailable.. in user (FIXTURE/config.toml)
path 2 FIXTURE/unavailable/.git (write); not probed (filesystem read restrictions apply)
path 2 source permissions.base.filesystem.FIXTURE/unavailable..git in user (FIXTURE/config.toml)
path 3 FIXTURE/unavailable/overridden (write); not probed (filesystem read restrictions apply)
path 3 source effective filesystem policy (entry provenance unavailable)
path 4 FIXTURE/unavailable/subtree (read); not probed (filesystem read restrictions apply)
path 4 source permissions.base.filesystem.FIXTURE/unavailable.subtree/** in user (FIXTURE/config.toml)
paths checked 4 of 4
-------------------------------------------------------------
1 ok | 0 warn | 0 fail ok
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,22 @@
---
source: cli/src/doctor/git.rs
assertion_line: 150
expression: "super::super::render_human_report(&report, super::super::HumanOutputOptions\n{ show_details: true, show_all: false, ascii: true, color_enabled: false, },)"
---
Codex Doctor vtest
Environment
[ok] git git executable found; execution not verified
selected git /usr/bin/git
repo detected true
repo root /repo
.git entry directory
PATH entries (2) /usr/bin/git
/opt/bin/git
git execution not inspected (PATH helpers are not executed)
-------------------------------------------------------------
1 ok | 0 warn | 0 fail ok
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,10 @@
---
source: cli/src/doctor/output.rs
expression: "rendered.replace('\\u{1b}', \"<ESC>\")"
---
<ESC>[38;5;10m✓<ESC>[39m state <ESC>[2m<ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m<ESC>[0m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. C:\logs, D:/goals. c:\logs, \\server\share\logs, \\?\C:\logs, \\?\UNC\server\share\logs, \\.\pipe\codex, \??\C:\logs, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
<ESC>[38;5;214m⚠<ESC>[39m state <ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. C:\logs, D:/goals. c:\logs, \\server\share\logs, \\?\C:\logs, \\?\UNC\server\share\logs, \\.\pipe\codex, \??\C:\logs, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
<ESC>[38;5;196m✗<ESC>[39m state <ESC>[38;5;196m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;196m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;196m./logs<ESC>[39m, <ESC>[38;5;196m../goals<ESC>[39m. C:\logs, D:/goals. c:\logs, \\server\share\logs, \\?\C:\logs, \\?\UNC\server\share\logs, \\.\pipe\codex, \??\C:\logs, \DosDevices\C:\logs, \rooted. <ESC>[38;5;196mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;196mhttps://example.com<ESC>[39m; <ESC>[38;5;196mwss://example.com<ESC>[39m) and <ESC>[38;5;196m/tmp/my data/logs_2.sqlite<ESC>[39m

View File

@@ -0,0 +1,10 @@
---
source: cli/src/doctor/output.rs
expression: "rendered.replace('\\u{1b}', \"<ESC>\")"
---
<ESC>[38;5;10m✓<ESC>[39m state <ESC>[2m<ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m<ESC>[0m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. <ESC>[38;5;117mC:\logs<ESC>[39m, <ESC>[38;5;117mD:/goals<ESC>[39m. <ESC>[38;5;117mc:\logs<ESC>[39m, <ESC>[38;5;117m\\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\?\C:\logs<ESC>[39m, <ESC>[38;5;117m\\?\UNC\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\.\pipe\codex<ESC>[39m, <ESC>[38;5;117m\??\C:\logs<ESC>[39m, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
<ESC>[38;5;214m⚠<ESC>[39m state <ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. <ESC>[38;5;117mC:\logs<ESC>[39m, <ESC>[38;5;117mD:/goals<ESC>[39m. <ESC>[38;5;117mc:\logs<ESC>[39m, <ESC>[38;5;117m\\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\?\C:\logs<ESC>[39m, <ESC>[38;5;117m\\?\UNC\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\.\pipe\codex<ESC>[39m, <ESC>[38;5;117m\??\C:\logs<ESC>[39m, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
<ESC>[38;5;196m✗<ESC>[39m state <ESC>[38;5;196m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;196m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;196m./logs<ESC>[39m, <ESC>[38;5;196m../goals<ESC>[39m. <ESC>[38;5;196mC:\logs<ESC>[39m, <ESC>[38;5;196mD:/goals<ESC>[39m. <ESC>[38;5;196mc:\logs<ESC>[39m, <ESC>[38;5;196m\\server\share\logs<ESC>[39m, <ESC>[38;5;196m\\?\C:\logs<ESC>[39m, <ESC>[38;5;196m\\?\UNC\server\share\logs<ESC>[39m, <ESC>[38;5;196m\\.\pipe\codex<ESC>[39m, <ESC>[38;5;196m\??\C:\logs<ESC>[39m, \DosDevices\C:\logs, \rooted. <ESC>[38;5;196mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;196mhttps://example.com<ESC>[39m; <ESC>[38;5;196mwss://example.com<ESC>[39m) and <ESC>[38;5;196m/tmp/my data/logs_2.sqlite<ESC>[39m

View File

@@ -0,0 +1,80 @@
---
source: cli/src/doctor/output.rs
expression: "render_human_report(&report, detailed_no_color_unicode_options())"
---
Codex Doctor v0.0.0
Notes
↑ desktop build 123 available (ready to install)
⚠ terminal narrow terminal
✗ auth token expired - Run `codex login`.
✗ network provider is unreachable - A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `codex features enable respect_system_proxy`. Restart Codex after changing this setting.
⚠ git this worktree is not on a Windows Dev Drive - create a trusted Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/
⚠ security Microsoft Defender can interfere with Codex. Verify Codex exclusions.
─────────────────────────────────────────────────────────────
Environment
✓ system en-US
os macOS 15.0
OS language en-US
VISUAL code --wait
EDITOR vim
PAGER less -R
GIT_PAGER delta
GH_PAGER less
LESS -FRX
✓ disk sufficient free disk space (42.0 GiB)
⚠ security Microsoft Defender can interfere with Codex. Verify Codex exclusions.
endpoint products Microsoft Defender
exclusion targets verified Codex app and required helpers
▸ Codex exclusions not verified (expected Codex application and helper exclusions)
→ Microsoft Defender: Add a certificate or executable-path exclusion for Codex and its helpers. If Attack Surface Reduction blocks Codex, add a rule exclusion. If Controlled Folder Access blocks Codex, allow the app.
✓ runtime running local build on darwin-arm64
✓ install consistent
managed by npm: no · bun: no · pnpm: no · Vite+: no · package root —
✓ search search is OK (bundled)
✓ git git version 2.54.0
selected git /usr/bin/git
version git version 2.54.0
repo detected true
⚠ git this worktree is not on a Windows Dev Drive — create a trusted Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/
⚠ terminal narrow terminal
✓ title default · project codex
title source default
title items activity, project-name
project value codex
✓ state state paths inspectable
Configuration
✓ config loaded
feature flags 0 enabled · 0 overridden
configured TUI mode fullscreen
✗ auth token expired — Run `codex login`.
OPENAI_API_KEY present
Desktop App
✓ desktop the desktop application is installed
version 1.2.3
running true
log directory $HOME/Library/Logs/com.openai.codex
✓ desktop the desktop app-server initialized successfully
Updates
✓ updates update configuration is locally consistent
desktop update status ready to install
desktop latest build 123
Connectivity
✓ network network environment readable
✗ network provider is unreachable — A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `codex features enable respect_system_proxy`. Restart Codex after changing this setting.
✓ websocket Responses WebSocket handshake succeeded
✓ reachability active provider endpoints are reachable over HTTP
Background Server
✓ app-server background server is not running
─────────────────────────────────────────────────────────────
16 ok · 6 notes · 3 warn · 2 fail failed
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,23 @@
---
source: cli/src/doctor/output.rs
expression: "render_human_report(&report, detailed_all_no_color_unicode_options())"
---
Codex Doctor v0.0.0
Notes
⚠ mcp missing inputs
─────────────────────────────────────────────────────────────
Configuration
⚠ mcp missing inputs
demo bearer token env var DOCS_TOKEN is not set
DEMO header env var DOCS_SECRET is not set
stdio env var DOCS_TOKEN is not set
npm:@modelcontextprotocol/server-sequential.thinking env var DOCS_TOKEN is not set
typo bearer token env var <redacted> is not set
─────────────────────────────────────────────────────────────
0 ok · 1 notes · 1 warn · 0 fail degraded
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,182 @@
use std::collections::BTreeMap;
use std::env;
use super::DoctorCheck;
use super::LOCALE_ENV_VARS;
const EDITOR_ENV_VARS: &[&str] = &["VISUAL", "EDITOR"];
const PAGER_ENV_VARS: &[&str] = &["PAGER", "GIT_PAGER", "GH_PAGER", "LESS"];
#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct SystemCheckInputs {
os: String,
os_type: String,
os_version: String,
os_language: Option<String>,
locale_env: BTreeMap<String, String>,
editor_env: BTreeMap<String, String>,
pager_env: BTreeMap<String, String>,
}
impl SystemCheckInputs {
fn detect() -> Self {
let info = os_info::get();
let locale_env = LOCALE_ENV_VARS
.iter()
.filter_map(|name| {
env::var(name)
.ok()
.map(|value| ((*name).to_string(), value))
})
.collect();
let editor_env = EDITOR_ENV_VARS
.iter()
.map(|name| {
let value = env::var_os(name)
.map(|value| value.to_string_lossy().into_owned())
.unwrap_or_else(|| "not set".to_string());
((*name).to_string(), value)
})
.collect();
let pager_env = PAGER_ENV_VARS
.iter()
.filter_map(|name| {
env::var_os(name)
.map(|value| ((*name).to_string(), value.to_string_lossy().into_owned()))
})
.collect();
Self {
os: info.to_string(),
os_type: info.os_type().to_string(),
os_version: info.version().to_string(),
os_language: sys_locale::get_locale(),
locale_env,
editor_env,
pager_env,
}
}
}
pub(super) fn system_check() -> DoctorCheck {
system_check_from_inputs(SystemCheckInputs::detect())
}
fn system_check_from_inputs(inputs: SystemCheckInputs) -> DoctorCheck {
let mut details = vec![
format!("os: {}", inputs.os),
format!("os type: {}", inputs.os_type),
format!("os version: {}", inputs.os_version),
];
if let Some(language) = inputs.os_language.as_deref() {
details.push(format!("os language: {language}"));
} else {
details.push("os language: unavailable".to_string());
}
for name in LOCALE_ENV_VARS {
if let Some(value) = inputs.locale_env.get(*name) {
details.push(format!("{name}: {value}"));
}
}
for name in EDITOR_ENV_VARS {
if let Some(value) = inputs.editor_env.get(*name) {
details.push(format!("{name}: {value}"));
}
}
for name in PAGER_ENV_VARS {
if let Some(value) = inputs.pager_env.get(*name) {
details.push(format!("{name}: {value}"));
}
}
let summary = inputs
.os_language
.as_deref()
.map(|language| format!("OS language {language}"))
.unwrap_or_else(|| "OS language unavailable".to_string());
DoctorCheck::new(
"system.environment",
"system",
super::CheckStatus::Ok,
summary,
)
.details(details)
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn system_check_reports_os_language_locale_editor_and_pager_env() {
let mut locale_env = BTreeMap::new();
locale_env.insert("LANG".to_string(), "en_US.UTF-8".to_string());
let editor_env = BTreeMap::from([
("EDITOR".to_string(), "vim".to_string()),
("VISUAL".to_string(), "code --wait".to_string()),
]);
let pager_env = BTreeMap::from([
("GH_PAGER".to_string(), "less".to_string()),
("GIT_PAGER".to_string(), "delta".to_string()),
("LESS".to_string(), "-FRX".to_string()),
("PAGER".to_string(), "less -R".to_string()),
]);
let check = system_check_from_inputs(SystemCheckInputs {
os: "macOS 15.0".to_string(),
os_type: "macos".to_string(),
os_version: "15.0".to_string(),
os_language: Some("en-US".to_string()),
locale_env,
editor_env,
pager_env,
});
assert_eq!(check.summary, "OS language en-US");
assert_eq!(
check.details,
vec![
"os: macOS 15.0",
"os type: macos",
"os version: 15.0",
"os language: en-US",
"LANG: en_US.UTF-8",
"VISUAL: code --wait",
"EDITOR: vim",
"PAGER: less -R",
"GIT_PAGER: delta",
"GH_PAGER: less",
"LESS: -FRX",
]
);
}
#[test]
fn system_check_handles_missing_os_language() {
let check = system_check_from_inputs(SystemCheckInputs {
os: "Linux".to_string(),
os_type: "linux".to_string(),
os_version: "unknown".to_string(),
os_language: None,
locale_env: BTreeMap::new(),
editor_env: BTreeMap::from([
("EDITOR".to_string(), "not set".to_string()),
("VISUAL".to_string(), "not set".to_string()),
]),
pager_env: BTreeMap::new(),
});
assert_eq!(check.summary, "OS language unavailable");
assert_eq!(
check.details,
vec![
"os: Linux",
"os type: linux",
"os version: unknown",
"os language: unavailable",
"VISUAL: not set",
"EDITOR: not set",
]
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,424 @@
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use codex_config::ConfigLayerSource;
use codex_core::config::Config;
use codex_git_utils::get_git_repo_root;
use unicode_segmentation::UnicodeSegmentation;
use super::CheckStatus;
use super::DoctorCheck;
const DEFAULT_TERMINAL_TITLE_ITEMS: &[&str] = &["activity", "project-name"];
const PROJECT_TITLE_MAX_CHARS: usize = 24;
#[derive(Clone, Debug, Eq, PartialEq)]
struct TerminalTitleInputs {
configured_items: Option<Vec<String>>,
cwd: PathBuf,
project_root: Option<ProjectTitleRoot>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ProjectTitleRoot {
source: &'static str,
path: PathBuf,
}
pub(super) fn terminal_title_check(config: &Config) -> DoctorCheck {
terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: config.tui_terminal_title.clone(),
cwd: config.cwd.to_path_buf(),
project_root: terminal_title_project_root(config, &config.cwd),
})
}
fn terminal_title_check_from_inputs(inputs: TerminalTitleInputs) -> DoctorCheck {
let (source, items, invalid_items) = match inputs.configured_items {
Some(items) if items.is_empty() => ("disabled", Vec::new(), Vec::new()),
Some(items) => {
let (items, invalid_items) = parse_terminal_title_items(items);
("configured", items, invalid_items)
}
None => (
"default",
DEFAULT_TERMINAL_TITLE_ITEMS
.iter()
.map(ToString::to_string)
.collect(),
Vec::new(),
),
};
let mut details = vec![
format!("terminal title source: {source}"),
format!(
"terminal title items: {}",
if items.is_empty() {
"none".to_string()
} else {
items.join(", ")
}
),
format!("terminal title activity: {}", activity_enabled(&items)),
];
if !invalid_items.is_empty() {
details.push(format!(
"terminal title invalid items: {}",
invalid_items.join(", ")
));
}
if project_title_selected(&items) {
let (project_source, project_value) =
project_title_candidate(inputs.project_root, &inputs.cwd);
details.push(format!("terminal title project source: {project_source}"));
if let Some(project_value) = project_value {
details.push(format!("terminal title project value: {project_value}"));
}
}
let status = if invalid_items.is_empty() {
CheckStatus::Ok
} else {
CheckStatus::Warning
};
let summary = if invalid_items.is_empty() {
format!("terminal title {source}")
} else {
format!("terminal title {source} with invalid items")
};
let mut check = DoctorCheck::new("terminal.title", "title", status, summary).details(details);
if !invalid_items.is_empty() {
check = check.issue(
super::DoctorIssue::new(
CheckStatus::Warning,
"terminal title configuration contains unknown item identifiers",
)
.measured(invalid_items.join(", "))
.expected("known terminal title item identifiers")
.remedy("Remove or replace the unknown entries in [tui].terminal_title.")
.field("terminal title invalid items"),
);
}
check
}
fn parse_terminal_title_items(items: Vec<String>) -> (Vec<String>, Vec<String>) {
let mut invalid = Vec::new();
let mut invalid_seen = HashSet::new();
let mut parsed = Vec::new();
for item in items {
match terminal_title_item_id(&item) {
Some(id) => parsed.push(id.to_string()),
None => {
if invalid_seen.insert(item.clone()) {
invalid.push(format!(r#""{item}""#));
}
}
}
}
(parsed, invalid)
}
fn terminal_title_item_id(item: &str) -> Option<&'static str> {
match item {
"app-name" => Some("app-name"),
"project-name" | "project" => Some("project-name"),
"current-dir" => Some("current-dir"),
"activity" | "spinner" => Some("activity"),
"run-state" | "status" => Some("run-state"),
"thread-title" | "thread" => Some("thread-title"),
"git-branch" => Some("git-branch"),
"context-remaining" => Some("context-remaining"),
"context-used" | "context-usage" => Some("context-used"),
"five-hour-limit" => Some("five-hour-limit"),
"weekly-limit" => Some("weekly-limit"),
"thread-credits" => Some("thread-credits"),
"estimated-thread-cost" => Some("estimated-thread-cost"),
"codex-version" => Some("codex-version"),
"used-tokens" => Some("used-tokens"),
"total-input-tokens" => Some("total-input-tokens"),
"total-output-tokens" => Some("total-output-tokens"),
"thread-id" | "session-id" => Some("thread-id"),
"fast-mode" => Some("fast-mode"),
"daybreak" => Some("daybreak"),
"model" | "model-name" => Some("model"),
"model-with-reasoning" => Some("model-with-reasoning"),
"reasoning" => Some("reasoning"),
"task-progress" => Some("task-progress"),
_ => None,
}
}
fn activity_enabled(items: &[String]) -> bool {
items
.iter()
.any(|item| item == "activity" || item == "spinner")
}
fn project_title_selected(items: &[String]) -> bool {
items
.iter()
.any(|item| item == "project-name" || item == "project")
}
fn terminal_title_project_root(config: &Config, cwd: &Path) -> Option<ProjectTitleRoot> {
if let Some(repo_root) = get_git_repo_root(cwd) {
return Some(ProjectTitleRoot {
source: "git repo root",
path: repo_root,
});
}
config
.config_layer_stack
.all_layers_low_to_high()
.find_map(|layer| match &layer.name {
ConfigLayerSource::Project { dot_codex_folder } => dot_codex_folder
.as_path()
.parent()
.map(|root| ProjectTitleRoot {
source: "project config",
path: root.to_path_buf(),
}),
_ => None,
})
}
fn project_title_candidate(
project_root: Option<ProjectTitleRoot>,
cwd: &Path,
) -> (&'static str, Option<String>) {
if let Some(project_root) = project_root {
return (
project_root.source,
Some(truncate_title_part(path_display_name(&project_root.path))),
);
}
("cwd", Some(truncate_title_part(path_display_name(cwd))))
}
fn path_display_name(path: &Path) -> String {
path.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| path.display().to_string())
}
fn truncate_title_part(value: String) -> String {
let mut graphemes = value.graphemes(true);
let head = graphemes
.by_ref()
.take(PROJECT_TITLE_MAX_CHARS)
.collect::<String>();
if graphemes.next().is_none() || PROJECT_TITLE_MAX_CHARS <= 3 {
return head;
}
let mut truncated = head
.graphemes(true)
.take(PROJECT_TITLE_MAX_CHARS - 3)
.collect::<String>();
truncated.push_str("...");
truncated
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn terminal_title_reports_default_items_and_git_project_name() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: None,
cwd: PathBuf::from("/repo/subdir"),
project_root: Some(ProjectTitleRoot {
source: "git repo root",
path: PathBuf::from("/repo"),
}),
});
assert_eq!(check.summary, "terminal title default");
assert!(
check
.details
.contains(&"terminal title items: activity, project-name".to_string())
);
assert!(
check
.details
.contains(&"terminal title project source: git repo root".to_string())
);
assert!(
check
.details
.contains(&"terminal title project value: repo".to_string())
);
}
#[test]
fn terminal_title_reports_disabled_configuration() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(Vec::new()),
cwd: PathBuf::from("/workspace"),
project_root: None,
});
assert_eq!(check.summary, "terminal title disabled");
assert!(
check
.details
.contains(&"terminal title items: none".to_string())
);
assert!(
check
.details
.contains(&"terminal title activity: false".to_string())
);
assert!(
!check
.details
.iter()
.any(|detail| detail.starts_with("terminal title project "))
);
}
#[test]
fn terminal_title_reports_project_config_fallback() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec!["project".to_string()]),
cwd: PathBuf::from("/workspace/project/subdir"),
project_root: Some(ProjectTitleRoot {
source: "project config",
path: PathBuf::from("/workspace/project"),
}),
});
assert_eq!(check.summary, "terminal title configured");
assert!(
check
.details
.contains(&"terminal title project source: project config".to_string())
);
assert!(
check
.details
.contains(&"terminal title project value: project".to_string())
);
}
#[test]
fn terminal_title_accepts_configured_items() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec![
"thread-credits".to_string(),
"estimated-thread-cost".to_string(),
"daybreak".to_string(),
]),
cwd: PathBuf::from("/workspace/project"),
project_root: None,
});
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(check.summary, "terminal title configured");
assert!(check.details.contains(
&"terminal title items: thread-credits, estimated-thread-cost, daybreak".to_string()
));
assert!(check.issues.is_empty());
}
#[test]
fn terminal_title_omits_project_when_project_item_is_not_selected() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec!["model".to_string()]),
cwd: PathBuf::from("/workspace/project"),
project_root: Some(ProjectTitleRoot {
source: "project config",
path: PathBuf::from("/workspace/project"),
}),
});
assert_eq!(check.summary, "terminal title configured");
assert!(
!check
.details
.iter()
.any(|detail| detail.starts_with("terminal title project "))
);
}
#[test]
fn terminal_title_warns_for_invalid_configured_items() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec![
"project".to_string(),
"bogus".to_string(),
"activity".to_string(),
"bogus".to_string(),
]),
cwd: PathBuf::from("/workspace/project"),
project_root: Some(ProjectTitleRoot {
source: "project config",
path: PathBuf::from("/workspace/project"),
}),
});
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(
check.summary,
"terminal title configured with invalid items"
);
assert!(
check
.details
.contains(&"terminal title items: project-name, activity".to_string())
);
assert!(
check
.details
.contains(&r#"terminal title invalid items: "bogus""#.to_string())
);
assert_eq!(check.issues.len(), 1);
}
#[test]
fn terminal_title_warns_when_all_configured_items_are_invalid() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec!["bogus".to_string()]),
cwd: PathBuf::from("/workspace/project"),
project_root: None,
});
assert_eq!(check.status, CheckStatus::Warning);
assert!(
check
.details
.contains(&"terminal title items: none".to_string())
);
assert!(
check
.details
.contains(&r#"terminal title invalid items: "bogus""#.to_string())
);
}
#[test]
fn terminal_title_project_value_uses_tui_truncation_shape() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec!["project".to_string()]),
cwd: PathBuf::from("/workspace/abcdefghijklmnopqrstuvwxyz"),
project_root: Some(ProjectTitleRoot {
source: "project config",
path: PathBuf::from("/workspace/abcdefghijklmnopqrstuvwxyz"),
}),
});
assert!(
check
.details
.contains(&"terminal title project value: abcdefghijklmnopqrstu...".to_string())
);
}
}

View File

@@ -0,0 +1,711 @@
//! Diagnoses whether Codex update paths target the running installation.
//!
//! Update diagnostics combine cached version metadata, install-channel hints,
//! and bounded latest-version HTTP probes. It never executes package managers or
//! other helpers selected by PATH; npm update targets are not verified.
use std::path::Path;
#[cfg(target_os = "macos")]
use std::path::PathBuf;
use std::time::Duration;
use codex_core::config::Config;
use codex_http_client::ClientRouteClass;
use codex_http_client::RouteAwareClientPool;
use codex_install_context::InstallContext;
use codex_install_context::InstallMethod;
use http::Method;
use serde::Deserialize;
#[cfg(target_os = "macos")]
use url::Url;
use super::CheckStatus;
use super::DoctorCheck;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use super::DoctorIssue;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use super::desktop::platform::InstalledApp;
use super::doctor_install_context;
use super::doctor_managed_by_npm;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use super::network;
const MAX_VERSION_RESPONSE_BYTES: usize = 1024 * 1024;
const VERSION_FILE_NAME: &str = "version.json";
const GITHUB_LATEST_RELEASE_URL: &str = "https://api.github.com/repos/openai/codex/releases/latest";
const HOMEBREW_CASK_API_URL: &str = "https://formulae.brew.sh/api/cask/codex.json";
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
const DESKTOP_UPDATE_URL: &str = "https://persistent.oaistatic.com/codex-app-prod/appcast-x64.xml";
#[cfg(all(target_os = "macos", not(target_arch = "x86_64")))]
const DESKTOP_UPDATE_URL: &str = "https://persistent.oaistatic.com/codex-app-prod/appcast.xml";
#[cfg(target_os = "macos")]
const BACKEND_DESKTOP_UPDATE_URL: &str = "https://chatgpt.com/backend-api/wham/app/appcast";
#[cfg(target_os = "windows")]
const DESKTOP_UPDATE_URL: &str =
"https://persistent.oaistatic.com/codex-app-prod/windows-store-update.json";
/// Builds the update-health row for the current installation.
///
/// Network failures while fetching latest-version metadata degrade the row to a
/// warning instead of failing doctor outright; update freshness is useful
/// support context but should not mask more direct install/config failures.
pub(super) async fn updates_check(config: &Config) -> DoctorCheck {
let current_exe = std::env::current_exe().ok();
let install_context = doctor_install_context(current_exe.as_deref());
let mut details = vec![
format!(
"check for update on startup: {}",
config.check_for_update_on_startup
),
format!("update action: {}", update_action_label(&install_context)),
];
let version_file = config.codex_home.join(VERSION_FILE_NAME);
push_cached_version_details(&mut details, &version_file);
let mut status = CheckStatus::Ok;
let summary = "update configuration is locally consistent".to_string();
if doctor_managed_by_npm(current_exe.as_deref()) {
details
.push("npm update target: not inspected (PATH helpers are not executed)".to_string());
}
let client = RouteAwareClientPool::new_without_request_logging(
config.http_client_factory(),
ClientRouteClass::Other,
);
match fetch_latest_version(&client, &install_context).await {
Ok(latest_version) => {
details.push(format!("latest version: {latest_version}"));
if is_newer(&latest_version, env!("CARGO_PKG_VERSION")) == Some(true) {
details.push("latest version status: newer version is available".to_string());
} else {
details.push("latest version status: current version is not older".to_string());
}
}
Err(err) => {
status = status.max(CheckStatus::Warning);
details.push(format!("latest version probe: {err}"));
}
}
DoctorCheck::new("updates.status", "updates", status, summary).details(details)
}
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(super) async fn append_desktop_update(
checks: &mut [DoctorCheck],
config: Option<&Config>,
application: &InstalledApp,
) {
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
#[cfg(target_os = "macos")]
if let Some(home) = std::env::var_os("HOME").map(PathBuf::from)
&& let Some(build) = latest_macos_staged_build(
&home
.join("Library/Caches")
.join(application.identity)
.join("org.sparkle-project.Sparkle/Installation"),
application.build,
)
.await
&& let Some(update) = checks.iter_mut().find(|check| check.id == "updates.status")
{
update.details.extend([
"desktop update status: ready to install".to_string(),
format!("desktop latest build: {build}"),
format!("desktop application: {}", application.identity),
]);
}
let Some(config) = config else {
return;
};
let Some(reachability_index) = checks
.iter()
.position(|check| check.id == "network.provider_reachability")
else {
return;
};
#[cfg(target_os = "macos")]
let desktop_update_url = std::env::var_os("HOME")
.map(PathBuf::from)
.map(|home| {
macos_desktop_update_url(&home, application, &os_info::get().version().to_string())
})
.unwrap_or_else(|| DESKTOP_UPDATE_URL.to_string());
#[cfg(target_os = "windows")]
let desktop_update_url = DESKTOP_UPDATE_URL;
#[cfg(target_os = "macos")]
let desktop_update_url = desktop_update_url.as_str();
let desktop_update_display_url = desktop_update_url
.split_once('?')
.map_or(desktop_update_url, |(endpoint, _)| endpoint);
let client = RouteAwareClientPool::new_without_request_logging(
config.http_client_factory(),
ClientRouteClass::Other,
);
let outcome = match client
.request(Method::GET, desktop_update_url)
.timeout(deadline.saturating_duration_since(tokio::time::Instant::now()))
.send()
.await
{
Ok(response) => {
let status = response.status().as_u16();
#[cfg(target_os = "windows")]
if status == 404 && response.url().scheme() == "https" {
checks[reachability_index].details.push(format!(
"desktop assets CDN: {desktop_update_display_url} reachable (HTTP 404; no update available)"
));
return;
}
if cfg!(target_os = "windows") && response.url().scheme() != "https" {
Err("update manifest redirected to a non-HTTPS URL".to_string())
} else if status == 407 {
Err("proxy authentication required (HTTP 407)".to_string())
} else if !(200..=299).contains(&status) {
Err(format!("HTTP {status}"))
} else {
checks[reachability_index].details.push(format!(
"desktop assets CDN: {desktop_update_display_url} reachable (HTTP {status})"
));
#[cfg(target_os = "windows")]
if let Some(update) = checks.iter_mut().find(|check| check.id == "updates.status") {
match response.bytes().await {
Ok(body) => match windows_store_update(&body, &application.version) {
Ok(Some(build)) => update.details.extend([
"desktop update status: available".to_string(),
format!("desktop latest build: {build}"),
format!("desktop application: {}", application.identity),
]),
Ok(None) => {}
Err(error) => {
update.status = update.status.max(CheckStatus::Warning);
update
.details
.push(format!("desktop update manifest: {error}"));
}
},
Err(_) => {
update.status = update.status.max(CheckStatus::Warning);
update
.details
.push("desktop update manifest: response could not be read".into());
}
}
}
Ok(())
}
}
Err(error) => Err(network::request_error(error)),
};
if let Err(error) = outcome {
let reachability = &mut checks[reachability_index];
reachability.details.push(format!(
"desktop assets CDN: {desktop_update_display_url} {error} (optional)"
));
if reachability.status == CheckStatus::Ok {
reachability.status = CheckStatus::Warning;
reachability.summary = "desktop update and runtime CDN is unreachable".to_string();
}
reachability.issues.push(
DoctorIssue::new(
CheckStatus::Warning,
"desktop update and runtime CDN is unreachable",
)
.measured(format!("{desktop_update_display_url} {error}"))
.expected("desktop update and runtime CDN reachable over HTTPS")
.remedy(
if desktop_update_display_url.starts_with("https://chatgpt.com/") {
"check proxy, firewall, DNS, and certificate access to chatgpt.com"
} else {
"check proxy, firewall, DNS, and certificate access to persistent.oaistatic.com"
},
)
.field("desktop assets CDN"),
);
}
}
#[cfg(target_os = "macos")]
fn macos_desktop_update_url(home: &Path, application: &InstalledApp, os_version: &str) -> String {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProductionAppcastState {
#[serde(default)]
backend_appcast_enabled: bool,
installation_id: Option<String>,
}
let state_path = home
.join("Library/Application Support")
.join(application.identity)
.join("production-appcast-bootstrap.json");
let Some(state) = std::fs::read(state_path)
.ok()
.and_then(|contents| serde_json::from_slice::<ProductionAppcastState>(&contents).ok())
else {
return DESKTOP_UPDATE_URL.to_string();
};
let Some(installation_id) = state
.backend_appcast_enabled
.then_some(state.installation_id)
.flatten()
else {
return DESKTOP_UPDATE_URL.to_string();
};
let Ok(mut url) = Url::parse(BACKEND_DESKTOP_UPDATE_URL) else {
return DESKTOP_UPDATE_URL.to_string();
};
url.query_pairs_mut().extend_pairs([
("installation_id", installation_id.as_str()),
(
"arch",
if cfg!(target_arch = "x86_64") {
"x64"
} else {
"arm64"
},
),
("app_version", application.version.as_str()),
("beta", "false"),
("os-version", os_version),
("plan_type", "unknown"),
]);
url.to_string()
}
#[cfg(any(target_os = "windows", test))]
fn windows_store_update(
manifest: &[u8],
installed_version: &str,
) -> Result<Option<String>, &'static str> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct StoreManifest {
schema_version: u64,
build_version: String,
store_product_id: String,
package_identity: String,
}
let manifest: StoreManifest =
serde_json::from_slice(manifest).map_err(|_| "invalid Windows Store update manifest")?;
if manifest.schema_version == 0
|| manifest.store_product_id != "9PLM9XGG6VKS"
|| manifest.package_identity != "OpenAI.Codex"
{
return Err("Windows Store update manifest does not target the production application");
}
let version = |value: &str| -> Option<[u64; 4]> {
value
.split('.')
.map(str::parse::<u64>)
.collect::<Result<Vec<_>, _>>()
.ok()?
.try_into()
.ok()
};
let latest = version(&manifest.build_version)
.ok_or("Windows Store update manifest contains an invalid build version")?;
let installed =
version(installed_version).ok_or("installed Windows application has an invalid version")?;
Ok((latest > installed).then_some(manifest.build_version))
}
#[cfg(target_os = "macos")]
async fn latest_macos_staged_build(root: &Path, installed_build: u64) -> Option<u64> {
const MAX_STAGED_BUNDLES: usize = 64;
if !std::fs::symlink_metadata(root).ok()?.is_dir() {
return None;
}
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
let mut inspected = 0;
let mut latest = None;
for entry in std::fs::read_dir(root).ok()? {
if inspected == MAX_STAGED_BUNDLES || tokio::time::Instant::now() >= deadline {
break;
}
let Ok(entry) = entry else {
continue;
};
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
continue;
}
let extracted = entry.path().join("extracted");
if !std::fs::symlink_metadata(&extracted).is_ok_and(|metadata| metadata.is_dir()) {
continue;
}
let bundle = extracted.join("ChatGPT.app");
if !std::fs::symlink_metadata(&bundle).is_ok_and(|metadata| metadata.is_dir()) {
continue;
}
inspected += 1;
let Ok(result) = tokio::time::timeout_at(
deadline,
super::desktop::platform::inspect_macos_bundle(&bundle),
)
.await
else {
break;
};
if let Ok(Some(application)) = result
&& application.build > installed_build
{
latest = Some(latest.map_or(application.build, |latest: u64| {
latest.max(application.build)
}));
}
}
latest
}
fn push_cached_version_details(details: &mut Vec<String>, version_file: &Path) {
details.push(format!("version cache: {}", version_file.display()));
match std::fs::read_to_string(version_file) {
Ok(contents) => match serde_json::from_str::<VersionInfo>(&contents) {
Ok(info) => {
details.push(format!("cached latest version: {}", info.latest_version));
if let Some(last_checked_at) = info.last_checked_at {
details.push(format!("last checked at: {last_checked_at}"));
}
if let Some(dismissed_version) = info.dismissed_version {
details.push(format!("dismissed version: {dismissed_version}"));
}
}
Err(err) => details.push(format!("version cache parse: {err}")),
},
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
details.push("version cache: missing".to_string());
}
Err(err) => details.push(format!("version cache read: {err}")),
}
}
fn update_action_label(context: &InstallContext) -> &'static str {
match &context.method {
InstallMethod::Npm => "npm install -g @openai/codex",
InstallMethod::Bun => "bun install -g @openai/codex",
InstallMethod::VitePlus => "vp install -g @openai/codex",
InstallMethod::Pnpm => "pnpm add -g @openai/codex",
InstallMethod::Brew => "brew upgrade --cask codex",
InstallMethod::Standalone { .. } => "standalone installer",
InstallMethod::Other => "manual or unknown",
}
}
async fn fetch_latest_version(
client: &RouteAwareClientPool,
context: &InstallContext,
) -> Result<String, String> {
match &context.method {
InstallMethod::Brew => fetch_homebrew_cask_version(client).await,
InstallMethod::Npm
| InstallMethod::Bun
| InstallMethod::VitePlus
| InstallMethod::Pnpm
| InstallMethod::Standalone { .. }
| InstallMethod::Other => fetch_latest_github_release_version(client).await,
}
}
async fn fetch_latest_github_release_version(
client: &RouteAwareClientPool,
) -> Result<String, String> {
#[derive(Deserialize)]
struct ReleaseInfo {
tag_name: String,
}
let info = http_get_json::<ReleaseInfo>(client, GITHUB_LATEST_RELEASE_URL).await?;
info.tag_name
.strip_prefix("rust-v")
.map(str::to_string)
.ok_or_else(|| format!("failed to parse latest tag {}", info.tag_name))
}
async fn fetch_homebrew_cask_version(client: &RouteAwareClientPool) -> Result<String, String> {
#[derive(Deserialize)]
struct HomebrewCaskInfo {
version: String,
}
http_get_json::<HomebrewCaskInfo>(client, HOMEBREW_CASK_API_URL)
.await
.map(|info| info.version)
}
async fn http_get_json<T>(client: &RouteAwareClientPool, url: &str) -> Result<T, String>
where
T: for<'de> Deserialize<'de>,
{
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
let mut response = client
.request(Method::GET, url)
.header(
http::header::USER_AGENT,
concat!("codex-doctor/", env!("CARGO_PKG_VERSION")),
)
.send()
.await
.map_err(|err| err.to_string())?;
if !response.status().is_success() {
return Err(format!("HTTP {}", response.status()));
}
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|err| err.to_string())? {
if chunk.len() > MAX_VERSION_RESPONSE_BYTES.saturating_sub(body.len()) {
return Err("version response exceeds size limit".to_string());
}
body.extend_from_slice(&chunk);
}
serde_json::from_slice(&body).map_err(|err| err.to_string())
})
.await
.map_err(|_| "version request timed out".to_string())?
}
fn is_newer(latest: &str, current: &str) -> Option<bool> {
match (parse_version(latest), parse_version(current)) {
(Some(latest), Some(current)) => Some(latest > current),
(Some(_), None) | (None, Some(_)) | (None, None) => None,
}
}
fn parse_version(value: &str) -> Option<(u64, u64, u64)> {
let mut parts = value.trim().split('.');
let major = parts.next()?.parse::<u64>().ok()?;
let minor = parts.next()?.parse::<u64>().ok()?;
let patch = parts.next()?.parse::<u64>().ok()?;
Some((major, minor, patch))
}
#[derive(Deserialize)]
struct VersionInfo {
latest_version: String,
#[serde(default)]
last_checked_at: Option<String>,
#[serde(default)]
dismissed_version: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn version_http_probe_decodes_json_and_rejects_invalid_responses() {
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
let server = MockServer::start().await;
let client = RouteAwareClientPool::new_without_request_logging(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Other,
);
for (endpoint, response) in [
(
"valid",
ResponseTemplate::new(/*s*/ 200)
.set_body_json(serde_json::json!({"version": "1.2.3"})),
),
(
"invalid",
ResponseTemplate::new(/*s*/ 200).set_body_string("not JSON"),
),
("unavailable", ResponseTemplate::new(/*s*/ 503)),
("proxy_auth_required", ResponseTemplate::new(/*s*/ 407)),
(
"redirect",
ResponseTemplate::new(/*s*/ 302)
.insert_header("Location", format!("{}/valid", server.uri())),
),
(
"timeout",
ResponseTemplate::new(/*s*/ 200).set_delay(Duration::from_secs(/*secs*/ 6)),
),
(
"oversized",
ResponseTemplate::new(/*s*/ 200)
.set_body_bytes(vec![b' '; MAX_VERSION_RESPONSE_BYTES + 1]),
),
] {
Mock::given(method("GET"))
.and(path(format!("/{endpoint}")))
.respond_with(response)
.mount(&server)
.await;
let result = http_get_json::<serde_json::Value>(
&client,
&format!("{}/{endpoint}", server.uri()),
)
.await;
if matches!(endpoint, "valid" | "redirect") {
assert_eq!(result, Ok(serde_json::json!({"version": "1.2.3"})));
} else if endpoint == "timeout" {
assert_eq!(result, Err("version request timed out".to_string()));
} else if endpoint == "proxy_auth_required" {
assert_eq!(
result,
Err("HTTP 407 Proxy Authentication Required".to_string())
);
} else {
assert!(result.is_err(), "{endpoint} must not be accepted");
}
}
}
#[cfg(target_os = "macos")]
#[test]
fn macos_update_probe_uses_the_persisted_production_appcast_feed() {
let home = tempfile::tempdir().expect("temporary home should be created");
let application = InstalledApp {
identity: "com.openai.codex",
version: "26.623.10000".to_string(),
bundle: PathBuf::new(),
build: 6139,
};
assert_eq!(
macos_desktop_update_url(home.path(), &application, "26.6.0"),
DESKTOP_UPDATE_URL
);
let state_directory = home
.path()
.join("Library/Application Support/com.openai.codex");
std::fs::create_dir_all(&state_directory)
.expect("production appcast state directory should be created");
std::fs::write(
state_directory.join("production-appcast-bootstrap.json"),
r#"{"backendAppcastEnabled":true,"installationId":"028e90f8-5f2a-47db-a05c-6a48f548d728"}"#,
)
.expect("production appcast state should be created");
let arch = if cfg!(target_arch = "x86_64") {
"x64"
} else {
"arm64"
};
assert_eq!(
macos_desktop_update_url(home.path(), &application, "26.6.0"),
format!(
"{BACKEND_DESKTOP_UPDATE_URL}?installation_id=028e90f8-5f2a-47db-a05c-6a48f548d728&arch={arch}&app_version=26.623.10000&beta=false&os-version=26.6.0&plan_type=unknown"
)
);
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn macos_staged_updates_require_a_newer_matching_extracted_bundle() {
let root = tempfile::tempdir().expect("temporary Sparkle cache should be created");
for index in 0..320 {
std::fs::create_dir(root.path().join(format!("unrelated-{index}")))
.expect("unrelated Sparkle cache directory should be created");
}
for (name, identity, build) in [
("newest", "com.openai.codex", "6268"),
("newer", "com.openai.codex", "6168"),
("older", "com.openai.codex", "6138"),
("different", "com.example.other", "9999"),
("invalid", "com.openai.codex", "invalid"),
] {
let bundle = root.path().join(name).join("extracted/ChatGPT.app");
write_macos_bundle(&bundle, identity, build);
}
let outside = tempfile::tempdir().expect("external fixture should be created");
let linked = outside.path().join("ChatGPT.app");
write_macos_bundle(&linked, "com.openai.codex", "9999");
std::os::unix::fs::symlink(&linked, root.path().join("ChatGPT.app"))
.expect("symlinked staged app fixture should be created");
assert_eq!(
latest_macos_staged_build(root.path(), /*installed_build*/ 6139).await,
Some(6268)
);
assert_eq!(
latest_macos_staged_build(root.path(), /*installed_build*/ 6268).await,
None
);
}
#[test]
fn windows_store_updates_compare_all_four_production_build_components() {
let mut manifest = serde_json::json!({
"schemaVersion": 1,
"buildVersion": "26.803.5235.1",
"storeProductId": "9PLM9XGG6VKS",
"packageIdentity": "OpenAI.Codex",
});
assert_eq!(
windows_store_update(&serde_json::to_vec(&manifest).unwrap(), "26.803.5235.0"),
Ok(Some("26.803.5235.1".to_string()))
);
assert_eq!(
windows_store_update(&serde_json::to_vec(&manifest).unwrap(), "26.803.5235.1"),
Ok(None)
);
manifest["storeProductId"] = "other".into();
assert!(
windows_store_update(&serde_json::to_vec(&manifest).unwrap(), "26.803.5235.0").is_err()
);
}
#[cfg(target_os = "macos")]
fn write_macos_bundle(path: &Path, identity: &str, build: &str) {
let contents = path.join("Contents");
std::fs::create_dir_all(&contents).expect("staged app fixture should be created");
std::fs::write(
contents.join("Info.plist"),
format!(
"<?xml version=\"1.0\"?><plist version=\"1.0\"><dict>\
<key>CFBundleIdentifier</key><string>{identity}</string>\
<key>CFBundleVersion</key><string>{build}</string>\
</dict></plist>"
),
)
.expect("staged app metadata should be created");
}
#[test]
fn is_newer_compares_plain_semver() {
assert_eq!(is_newer("1.2.4", "1.2.3"), Some(true));
assert_eq!(is_newer("1.2.3", "1.2.4"), Some(false));
assert_eq!(is_newer("1.2.3-beta.1", "1.2.2"), None);
}
#[test]
fn update_action_labels_install_contexts() {
assert_eq!(
update_action_label(&InstallContext {
method: InstallMethod::Npm,
package_layout: None,
}),
"npm install -g @openai/codex"
);
assert_eq!(
update_action_label(&InstallContext {
method: InstallMethod::Pnpm,
package_layout: None,
}),
"pnpm add -g @openai/codex"
);
assert_eq!(
update_action_label(&InstallContext {
method: InstallMethod::Other,
package_layout: None,
}),
"manual or unknown"
);
}
}

View File

@@ -0,0 +1,160 @@
use std::ffi::OsString;
use std::fs::OpenOptions;
use std::io;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::ffi::OsStringExt;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use codex_git_utils::get_git_repo_root;
use os_info::Version;
use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
use windows_sys::Win32::Storage::FileSystem::GetVolumePathNameW;
use windows_sys::Win32::System::IO::DeviceIoControl;
use windows_sys::Win32::System::WindowsProgramming::DRIVE_FIXED;
use windows_sys::Win32::System::WindowsProgramming::DRIVE_NO_ROOT_DIR;
use windows_sys::Win32::System::WindowsProgramming::DRIVE_UNKNOWN;
use super::CheckStatus;
use super::DoctorCheck;
const ID: &str = "git.worktree.dev_drive";
const DEV_VOLUME: u32 = 0x0000_2000;
const TRUSTED_VOLUME: u32 = 0x0000_4000;
const QUERY_PERSISTENT_VOLUME_STATE: u32 = 0x0009_023c;
#[repr(C)]
struct PersistentVolumeState {
flags: u32,
mask: u32,
version: u32,
reserved: u32,
}
pub(super) fn check(cwd: &Path) -> DoctorCheck {
let Some(worktree) = get_git_repo_root(cwd) else {
return DoctorCheck::new(ID, "git", CheckStatus::Ok, "no Git worktree is active");
};
if matches!(
os_info::get().version(),
Version::Semantic(_, _, build) if *build < 22_621
) {
return DoctorCheck::new(
ID,
"git",
CheckStatus::Ok,
"Windows Dev Drives are unavailable on this Windows version",
);
}
match volume_flags(&worktree) {
Ok(flags) if flags & DEV_VOLUME == 0 => DoctorCheck::new(
ID,
"git",
CheckStatus::Warning,
"this worktree is not on a Windows Dev Drive; moving it to a trusted Dev Drive can significantly improve repository and filesystem performance",
)
.remediation(
"create a trusted Windows Dev Drive for source repositories: https://learn.microsoft.com/en-us/windows/dev-drive/",
),
Ok(flags) if flags & TRUSTED_VOLUME == 0 => DoctorCheck::new(
ID,
"git",
CheckStatus::Warning,
"the active Git worktree is on an untrusted Windows Dev Drive",
)
.remediation(
"ask your administrator to trust the Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/#how-do-i-designate-a-dev-drive-as-trusted",
),
Ok(_) => DoctorCheck::new(
ID,
"git",
CheckStatus::Ok,
"the active Git worktree is on a trusted Windows Dev Drive",
),
Err(error) => DoctorCheck::new(
ID,
"git",
CheckStatus::Warning,
"the active Git worktree's Windows Dev Drive state could not be inspected",
)
.detail(format!("filesystem error: {:?}", error.kind()))
.remediation("check access to the Git worktree and its Windows storage volume"),
}
}
fn volume_flags(path: &Path) -> io::Result<u32> {
let path = path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect::<Vec<_>>();
let mut volume = vec![0_u16; path.len().max(261)];
if unsafe { GetVolumePathNameW(path.as_ptr(), volume.as_mut_ptr(), volume.len() as u32) } == 0 {
return Err(io::Error::last_os_error());
}
match unsafe { GetDriveTypeW(volume.as_ptr()) } {
DRIVE_UNKNOWN | DRIVE_NO_ROOT_DIR => {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"the Windows storage volume could not be determined",
));
}
DRIVE_FIXED => {}
_ => return Ok(0),
}
let length = volume
.iter()
.position(|character| *character == 0)
.unwrap_or(volume.len());
let root = PathBuf::from(OsString::from_wide(&volume[..length]));
let handle = OpenOptions::new()
.access_mode(FILE_READ_ATTRIBUTES)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(root)?;
let mut state = PersistentVolumeState {
flags: 0,
mask: DEV_VOLUME | TRUSTED_VOLUME,
version: 1,
reserved: 0,
};
let state_size = std::mem::size_of::<PersistentVolumeState>() as u32;
let state_ptr = ptr::from_mut(&mut state);
let mut bytes_returned = 0;
if unsafe {
DeviceIoControl(
handle.as_raw_handle(),
QUERY_PERSISTENT_VOLUME_STATE,
state_ptr.cast_const().cast(),
state_size,
state_ptr.cast(),
state_size,
&mut bytes_returned,
ptr::null_mut(),
)
} == 0
{
let error = io::Error::last_os_error();
return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
Ok(0)
} else {
Err(error)
};
}
Ok(state.flags)
}
#[cfg(test)]
#[path = "windows_dev_drive_tests.rs"]
mod tests;

View File

@@ -0,0 +1,16 @@
use std::path::PathBuf;
use pretty_assertions::assert_eq;
use super::DEV_VOLUME;
use super::volume_flags;
#[test]
fn the_windows_system_volume_is_not_a_dev_drive() {
let system_root = std::env::var_os("SystemRoot")
.map(PathBuf::from)
.expect("Windows exposes its system directory");
let flags = volume_flags(&system_root).expect("the system volume can be inspected");
assert_eq!(flags & DEV_VOLUME, 0);
}

View File

@@ -0,0 +1,30 @@
//! Snapshot coverage for the public exec command's argument help.
use super::MultitoolCli;
use clap::CommandFactory;
use pretty_assertions::assert_eq;
#[test]
fn exec_help_documents_cyber_access_program() {
let help = MultitoolCli::command()
.term_width(80)
.try_get_matches_from(["codex", "exec", "--help"])
.expect_err("help should short-circuit");
assert_eq!(help.kind(), clap::error::ErrorKind::DisplayHelp);
let program_help = help
.to_string()
.lines()
.skip_while(|line| !line.contains("--cyber-access-program"))
.take_while(|line| !line.is_empty())
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(program_help.trim(), @r"
--cyber-access-program <PROGRAM>
Request an experimental Cyber access program for this turn (OpenAI
provider only). Omit to use server defaults. Not supported with
review; fork requires a prompt
[possible values: standard, daybreak_blue, daybreak_red]
");
}

View File

@@ -0,0 +1,29 @@
#![cfg(test)]
use super::*;
use clap::error::ErrorKind;
use pretty_assertions::assert_eq;
#[test]
fn exec_server_help_documents_remote_options() {
let command = MultitoolCli::command()
.term_width(80)
.mut_subcommand("exec-server", |command| {
command
.mut_arg("exit_on_stdin_close", |arg| arg.hide_env_values(true))
.mut_arg("proxy_private_ips_via_upstream", |arg| {
arg.hide_env_values(true)
})
});
let help = command
.try_get_matches_from(["codex", "exec-server", "--help"])
.expect_err("help should exit before running the executor");
assert_eq!(help.kind(), ErrorKind::DisplayHelp);
let help_text = help
.to_string()
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(help_text);
}

View File

@@ -0,0 +1,23 @@
#[cfg(unix)]
pub(crate) fn handle_exit_status(status: std::process::ExitStatus) -> ! {
use std::os::unix::process::ExitStatusExt;
// Use ExitStatus to derive the exit code.
if let Some(code) = status.code() {
std::process::exit(code);
} else if let Some(signal) = status.signal() {
std::process::exit(128 + signal);
} else {
std::process::exit(1);
}
}
#[cfg(windows)]
pub(crate) fn handle_exit_status(status: std::process::ExitStatus) -> ! {
if let Some(code) = status.code() {
std::process::exit(code);
} else {
// Rare on Windows, but if it happens: use fallback code.
std::process::exit(1);
}
}

191
codex-rs/cli/src/lib.rs Normal file
View File

@@ -0,0 +1,191 @@
pub mod cloud_config;
pub(crate) mod debug_sandbox;
mod exit_status;
pub(crate) mod login;
use clap::Args;
use clap::Parser;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_cli::CliConfigOverrides;
use codex_utils_cli::ProfileV2Name;
use std::path::PathBuf;
pub use debug_sandbox::run_command_under_landlock;
pub use debug_sandbox::run_command_under_seatbelt;
pub use debug_sandbox::run_command_under_windows_sandbox;
pub use login::read_access_token_from_stdin;
pub use login::read_api_key_from_stdin;
pub use login::run_login_status;
pub use login::run_login_with_access_token;
pub use login::run_login_with_api_key;
pub use login::run_login_with_browser;
pub use login::run_login_with_device_code;
pub use login::run_login_with_device_code_fallback_to_browser;
pub use login::run_logout;
#[derive(Debug, Default, Args)]
pub struct SandboxStateArgs {
/// Opaque JSON value from `codex/sandbox-state` to apply directly.
#[arg(
long = "sandbox-state-json",
value_name = "JSON",
conflicts_with_all = ["permissions_profile", "cwd", "include_managed_config"]
)]
pub sandbox_state_json: Option<String>,
/// Add a readable root to the supplied sandbox state. Repeat for multiple roots.
#[arg(
long,
requires = "sandbox_state_json",
value_parser = parse_absolute_path
)]
pub sandbox_state_readable_root: Vec<AbsolutePathBuf>,
/// Disable direct network access in the supplied sandbox state.
#[arg(long, requires = "sandbox_state_json", default_value_t = false)]
pub sandbox_state_disable_network: bool,
}
// These command structs share common sandbox options, but remain separate
// because each host backend has a slightly different option surface.
#[derive(Debug, Parser)]
pub struct SeatbeltCommand {
#[command(flatten)]
pub sandbox_state: SandboxStateArgs,
/// Named permissions profile to apply from the active configuration stack.
#[arg(
long = "permission-profile",
alias = "permissions-profile",
short = 'P',
value_name = "NAME"
)]
pub permissions_profile: Option<String>,
/// Layer $CODEX_HOME/<name>.config.toml on top of the base user config.
#[arg(long = "profile", short = 'p')]
pub config_profile: Option<ProfileV2Name>,
/// Working directory used for profile resolution and command execution.
#[arg(
short = 'C',
long = "cd",
value_name = "DIR",
requires = "permissions_profile"
)]
pub cwd: Option<PathBuf>,
/// Include managed requirements while resolving an explicit permissions profile.
#[arg(
long = "include-managed-config",
default_value_t = false,
requires = "permissions_profile"
)]
pub include_managed_config: bool,
/// Allow the sandboxed command to bind/connect AF_UNIX sockets rooted at this path. Relative paths are resolved against the current directory. Repeat to allow multiple paths.
#[arg(long = "allow-unix-socket", value_parser = parse_absolute_path)]
pub allow_unix_sockets: Vec<AbsolutePathBuf>,
/// While the command runs, capture macOS sandbox denials via `log stream` and print them after exit
#[arg(long = "log-denials", default_value_t = false)]
pub log_denials: bool,
#[clap(skip)]
pub config_overrides: CliConfigOverrides,
/// Full command args to run under seatbelt.
#[arg(trailing_var_arg = true)]
pub command: Vec<String>,
}
fn parse_absolute_path(raw: &str) -> Result<AbsolutePathBuf, String> {
AbsolutePathBuf::relative_to_current_dir(raw)
.map_err(|err| format!("invalid path {raw}: {err}"))
}
#[derive(Debug, Parser)]
pub struct LandlockCommand {
#[command(flatten)]
pub sandbox_state: SandboxStateArgs,
/// Named permissions profile to apply from the active configuration stack.
#[arg(
long = "permission-profile",
alias = "permissions-profile",
short = 'P',
value_name = "NAME"
)]
pub permissions_profile: Option<String>,
/// Layer $CODEX_HOME/<name>.config.toml on top of the base user config.
#[arg(long = "profile", short = 'p')]
pub config_profile: Option<ProfileV2Name>,
/// Working directory used for profile resolution and command execution.
#[arg(
short = 'C',
long = "cd",
value_name = "DIR",
requires = "permissions_profile"
)]
pub cwd: Option<PathBuf>,
/// Include managed requirements while resolving an explicit permissions profile.
#[arg(
long = "include-managed-config",
default_value_t = false,
requires = "permissions_profile"
)]
pub include_managed_config: bool,
#[clap(skip)]
pub config_overrides: CliConfigOverrides,
/// Full command args to run under the Linux sandbox.
#[arg(trailing_var_arg = true)]
pub command: Vec<String>,
}
#[derive(Debug, Parser)]
pub struct WindowsCommand {
#[command(flatten)]
pub sandbox_state: SandboxStateArgs,
/// Named permissions profile to apply from the active configuration stack.
#[arg(
long = "permission-profile",
alias = "permissions-profile",
short = 'P',
value_name = "NAME"
)]
pub permissions_profile: Option<String>,
/// Layer $CODEX_HOME/<name>.config.toml on top of the base user config.
#[arg(long = "profile", short = 'p')]
pub config_profile: Option<ProfileV2Name>,
/// Working directory used for profile resolution and command execution.
#[arg(
short = 'C',
long = "cd",
value_name = "DIR",
requires = "permissions_profile"
)]
pub cwd: Option<PathBuf>,
/// Include managed requirements while resolving an explicit permissions profile.
#[arg(
long = "include-managed-config",
default_value_t = false,
requires = "permissions_profile"
)]
pub include_managed_config: bool,
#[clap(skip)]
pub config_overrides: CliConfigOverrides,
/// Full command args to run under Windows restricted token sandbox.
#[arg(trailing_var_arg = true)]
pub command: Vec<String>,
}

761
codex-rs/cli/src/login.rs Normal file
View File

@@ -0,0 +1,761 @@
//! CLI login commands and their direct-user observability surfaces.
//!
//! The TUI path already installs a broader tracing stack with feedback, OpenTelemetry, and other
//! interactive-session layers. Direct `codex login` intentionally does less: it preserves the
//! existing stderr/browser UX and adds only a small file-backed tracing layer for login-specific
//! targets. Keeping that setup local avoids pulling the TUI's session-oriented logging machinery
//! into a one-shot CLI command while still producing a durable `codex-login.log` artifact that
//! support can request from users.
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::Config;
use codex_core::config::edit::ConfigEdit;
use codex_core::config::edit::ConfigEditsBuilder;
use codex_login::AuthKeyringBackendKind;
use codex_login::AuthManager;
use codex_login::AuthRouteConfig;
use codex_login::CLIENT_ID;
use codex_login::ServerOptions;
use codex_login::is_workload_identity_selected;
use codex_login::login_with_access_token;
use codex_login::login_with_api_key;
use codex_login::logout_with_revoke;
use codex_login::run_device_code_login;
use codex_login::run_login_server;
use codex_mcp::ema_auth_scope;
use codex_protocol::auth::AuthMode;
use codex_protocol::config_types::ForcedLoginMethod;
use codex_rmcp_client::EnterpriseOAuthCredentialGuard;
use codex_utils_cli::CliConfigOverrides;
use std::fs::OpenOptions;
use std::io::IsTerminal;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
use tracing_appender::non_blocking;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
const CHATGPT_LOGIN_DISABLED_MESSAGE: &str =
"ChatGPT login is disabled. Use API key login instead.";
const API_KEY_LOGIN_DISABLED_MESSAGE: &str =
"API key login is disabled. Use ChatGPT login instead.";
const ACCESS_TOKEN_LOGIN_DISABLED_MESSAGE: &str =
"Access token login is disabled. Use API key login instead.";
const LOGIN_SUCCESS_MESSAGE: &str = "Successfully logged in";
const API_KEY_AUTHENTICATION_NOTICE: &str = "Authentication is checked when you send a request.";
const DEFAULT_LOGIN_LOG_FILTER: &str =
"codex_cli=info,codex_core=info,codex_login=info,codex_otel::auth_storage=warn";
/// Installs a small file-backed tracing layer for direct `codex login` flows.
///
/// This deliberately duplicates a narrow slice of the TUI logging setup instead of reusing it
/// wholesale. The TUI stack includes session-oriented layers that are valuable for interactive
/// runs but unnecessary for a one-shot login command. Keeping the direct CLI path local lets this
/// command produce a durable `codex-login.log` artifact without coupling it to the TUI's broader
/// telemetry and feedback initialization.
fn init_login_file_logging(config: &Config) -> Option<WorkerGuard> {
let log_dir = match codex_core::config::log_dir(config) {
Ok(log_dir) => log_dir,
Err(err) => {
eprintln!("Warning: failed to resolve login log directory: {err}");
return None;
}
};
if let Err(err) = std::fs::create_dir_all(&log_dir) {
eprintln!(
"Warning: failed to create login log directory {}: {err}",
log_dir.display()
);
return None;
}
let mut log_file_opts = OpenOptions::new();
log_file_opts.create(true).append(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
log_file_opts.mode(0o600);
}
let log_path = log_dir.join("codex-login.log");
let log_file = match log_file_opts.open(&log_path) {
Ok(log_file) => log_file,
Err(err) => {
eprintln!(
"Warning: failed to open login log file {}: {err}",
log_path.display()
);
return None;
}
};
let (non_blocking, guard) = non_blocking(log_file);
let env_filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOGIN_LOG_FILTER));
let file_layer = tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_target(true)
.with_ansi(false)
.with_filter(env_filter);
// Direct `codex login` otherwise relies on ephemeral stderr and browser output.
// Persist the same login targets to a file so support can inspect auth failures
// without reproducing them through TUI or app-server.
if let Err(err) = tracing_subscriber::registry().with(file_layer).try_init() {
eprintln!(
"Warning: failed to initialize login log file {}: {err}",
log_path.display()
);
return None;
}
Some(guard)
}
fn print_login_server_start(actual_port: u16, auth_url: &str) {
eprintln!(
"Starting local login server on http://localhost:{actual_port}.\nIf your browser did not open, navigate to this URL to authenticate:\n\n{auth_url}\n\nOn a remote or headless machine? Use `codex login --device-auth` instead."
);
}
async fn clear_existing_auth_before_login(
codex_home: &Path,
auth_credentials_store_mode: AuthCredentialsStoreMode,
auth_keyring_backend_kind: AuthKeyringBackendKind,
auth_route_config: &AuthRouteConfig,
) {
if let Err(err) = logout_with_revoke(
codex_home,
auth_credentials_store_mode,
auth_keyring_backend_kind,
auth_route_config,
)
.await
{
tracing::warn!("failed to clear existing auth before login: {err}");
}
}
pub async fn login_with_chatgpt(
codex_home: PathBuf,
forced_chatgpt_workspace_id: Option<Vec<String>>,
cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
auth_keyring_backend_kind: AuthKeyringBackendKind,
auth_route_config: AuthRouteConfig,
) -> std::io::Result<()> {
clear_existing_auth_before_login(
&codex_home,
cli_auth_credentials_store_mode,
auth_keyring_backend_kind,
&auth_route_config,
)
.await;
let opts = ServerOptions::new(
codex_home,
CLIENT_ID.to_string(),
forced_chatgpt_workspace_id,
cli_auth_credentials_store_mode,
auth_keyring_backend_kind,
auth_route_config,
);
let server = run_login_server(opts)?;
print_login_server_start(server.actual_port, &server.auth_url);
server.block_until_done().await
}
/// Signs into the config server if needed, then reloads configuration.
async fn sign_in_to_config_server_and_reload_config(
config: &mut Config,
cli_config_overrides: &CliConfigOverrides,
) -> std::io::Result<()> {
let requirements = config.config_layer_stack.requirements_toml();
let network = codex_app_server::in_process::EmbeddedNetworkPolicy::load(
&codex_config::LoaderOverrides::default(),
)
.await;
let bootstrap_auth = network.bind_bootstrap_auth(config.auth_config());
let auth_route_config = bootstrap_auth.auth_route_config.clone();
codex_cloud_config::ensure_config_server_login(bootstrap_auth, requirements).await?;
*config = crate::cloud_config::load_config(cli_config_overrides, Default::default())
.await
.map_err(|error| std::io::Error::other(format!("{error:#}")))?;
network.activate(config);
config.application_auth_route_config = Some(auth_route_config);
Ok(())
}
fn finish_login(result: std::io::Result<()>) -> ! {
match result {
Ok(_) => {
eprintln!("{LOGIN_SUCCESS_MESSAGE}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Error logging in: {e}");
std::process::exit(1);
}
}
}
async fn run_interactive_login<F>(
cli_config_overrides: CliConfigOverrides,
chatgpt_login: impl FnOnce(Config) -> F,
) -> !
where
F: std::future::Future<Output = std::io::Result<()>>,
{
let mut config = load_config_or_exit(cli_config_overrides.clone()).await;
if !config
.config_layer_stack
.requirements_toml()
.requires_remote_config()
{
let _login_log_guard = init_login_file_logging(&config);
finish_login(chatgpt_login(config).await);
}
let result =
sign_in_to_config_server_and_reload_config(&mut config, &cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
finish_login(result)
}
pub async fn run_login_with_browser(cli_config_overrides: CliConfigOverrides) -> ! {
run_interactive_login(cli_config_overrides, |config| async move {
tracing::info!("starting browser login flow");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
eprintln!("{CHATGPT_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let effective_chatgpt_workspaces = config.auth_config().effective_chatgpt_workspaces();
login_with_chatgpt(
config.codex_home.to_path_buf(),
effective_chatgpt_workspaces,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
config.auth_route_config(),
)
.await
})
.await
}
pub async fn run_login_with_api_key(
cli_config_overrides: CliConfigOverrides,
api_key: String,
) -> ! {
let config = load_managed_login_config_or_exit(cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
tracing::info!("starting api key login flow");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Api)
{
eprintln!("{API_KEY_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
match login_with_api_key(
&config.codex_home,
&api_key,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
) {
Ok(_) => {
eprintln!("API key saved. {API_KEY_AUTHENTICATION_NOTICE}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Error logging in: {e}");
std::process::exit(1);
}
}
}
pub async fn run_login_with_access_token(
cli_config_overrides: CliConfigOverrides,
access_token: String,
) -> ! {
let config = load_managed_login_config_or_exit(cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
tracing::info!("starting access token login flow");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
eprintln!("{ACCESS_TOKEN_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let auth_route_config = config.auth_route_config();
let effective_chatgpt_workspaces = config.auth_config().effective_chatgpt_workspaces();
match login_with_access_token(
&config.codex_home,
&access_token,
config.cli_auth_credentials_store_mode,
effective_chatgpt_workspaces.as_deref(),
Some(&config.chatgpt_base_url),
config.auth_keyring_backend_kind(),
&auth_route_config,
)
.await
{
Ok(_) => {
eprintln!("{LOGIN_SUCCESS_MESSAGE}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Error logging in with access token: {e}");
std::process::exit(1);
}
}
}
pub fn read_api_key_from_stdin() -> String {
read_stdin_secret(
"--with-api-key expects the API key on stdin. Try piping it, e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`.",
"Reading API key from stdin...",
"No API key provided via stdin.",
)
}
pub fn read_access_token_from_stdin() -> String {
read_stdin_secret(
"--with-access-token expects the access token on stdin. Try piping it, e.g. `printenv CODEX_ACCESS_TOKEN | codex login --with-access-token`.",
"Reading access token from stdin...",
"No access token provided via stdin.",
)
}
fn read_stdin_secret(terminal_message: &str, reading_message: &str, empty_message: &str) -> String {
let mut stdin = std::io::stdin();
if stdin.is_terminal() {
eprintln!("{terminal_message}");
std::process::exit(1);
}
eprintln!("{reading_message}");
let mut buffer = String::new();
if let Err(err) = stdin.read_to_string(&mut buffer) {
eprintln!("Failed to read stdin: {err}");
std::process::exit(1);
}
let secret = buffer.trim().to_string();
if secret.is_empty() {
eprintln!("{empty_message}");
std::process::exit(1);
}
secret
}
/// Login using the OAuth device code flow.
pub async fn run_login_with_device_code(
cli_config_overrides: CliConfigOverrides,
issuer_base_url: Option<String>,
client_id: Option<String>,
) -> ! {
run_interactive_login(cli_config_overrides, |config| async move {
tracing::info!("starting device code login flow");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
eprintln!("{CHATGPT_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let auth_route_config = config.auth_route_config();
clear_existing_auth_before_login(
&config.codex_home,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
&auth_route_config,
)
.await;
let effective_chatgpt_workspaces = config.auth_config().effective_chatgpt_workspaces();
let mut opts = ServerOptions::new(
config.codex_home.to_path_buf(),
client_id.unwrap_or(CLIENT_ID.to_string()),
effective_chatgpt_workspaces,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
auth_route_config,
);
if let Some(iss) = issuer_base_url {
opts.issuer = iss;
}
run_device_code_login(opts).await
})
.await
}
/// Prefers device-code login (with `open_browser = false`) when headless environment is detected, but keeps
/// `codex login` working in environments where device-code may be disabled/feature-gated.
/// If `run_device_code_login` returns `ErrorKind::NotFound` ("device-code unsupported"), this
/// falls back to starting the local browser login server.
pub async fn run_login_with_device_code_fallback_to_browser(
cli_config_overrides: CliConfigOverrides,
issuer_base_url: Option<String>,
client_id: Option<String>,
) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
tracing::info!("starting login flow with device code fallback");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
eprintln!("{CHATGPT_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let auth_route_config = config.auth_route_config();
clear_existing_auth_before_login(
&config.codex_home,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
&auth_route_config,
)
.await;
let effective_chatgpt_workspaces = config.auth_config().effective_chatgpt_workspaces();
let mut opts = ServerOptions::new(
config.codex_home.to_path_buf(),
client_id.unwrap_or(CLIENT_ID.to_string()),
effective_chatgpt_workspaces,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
auth_route_config,
);
if let Some(iss) = issuer_base_url {
opts.issuer = iss;
}
opts.open_browser = false;
match run_device_code_login(opts.clone()).await {
Ok(()) => {
eprintln!("{LOGIN_SUCCESS_MESSAGE}");
std::process::exit(0);
}
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
eprintln!("Device code login is not enabled; falling back to browser login.");
match run_login_server(opts) {
Ok(server) => {
print_login_server_start(server.actual_port, &server.auth_url);
match server.block_until_done().await {
Ok(()) => {
eprintln!("{LOGIN_SUCCESS_MESSAGE}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Error logging in: {e}");
std::process::exit(1);
}
}
}
Err(e) => {
eprintln!("Error logging in: {e}");
std::process::exit(1);
}
}
} else {
eprintln!("Error logging in with device code: {e}");
std::process::exit(1);
}
}
}
}
pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
if is_workload_identity_selected() {
match AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await {
Ok(_) => {
eprintln!("Logged in using workload identity");
std::process::exit(0);
}
Err(err) => {
eprintln!("Error checking login status: {err}");
std::process::exit(1);
}
}
}
let auth_config = config.auth_config();
match auth_config
.load_auth(/*enable_codex_api_key_env*/ false)
.await
{
Ok(Some(auth)) => match auth.auth_mode() {
AuthMode::ApiKey => match auth.get_token() {
Ok(api_key) => {
eprintln!("API key configured - {}", safe_format_key(&api_key));
eprintln!("{API_KEY_AUTHENTICATION_NOTICE}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Unexpected error retrieving API key: {e}");
std::process::exit(1);
}
},
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens => {
eprintln!("Logged in using ChatGPT");
std::process::exit(0);
}
AuthMode::Headers => {
unreachable!("header auth cannot be loaded from auth storage")
}
AuthMode::AgentIdentity => {
eprintln!("Logged in using access token");
std::process::exit(0);
}
AuthMode::PersonalAccessToken => {
eprintln!("Logged in using personal access token");
std::process::exit(0);
}
AuthMode::BedrockApiKey => {
eprintln!("Logged in using Amazon Bedrock API key");
std::process::exit(0);
}
AuthMode::BedrockAccessKeys => {
eprintln!("Logged in using Amazon Bedrock AWS access keys");
std::process::exit(0);
}
},
Ok(None) => {
eprintln!("Not logged in");
std::process::exit(1);
}
Err(err) => {
eprintln!("Error checking login status: {err}");
std::process::exit(1);
}
}
}
async fn logout_config_server(config: &Config) -> std::io::Result<bool> {
match codex_cloud_config::managed_config_auth_manager(
config.auth_config(),
config.config_layer_stack.requirements_toml(),
)? {
Some(manager) => manager.logout().await,
None => Ok(false),
}
}
pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let auth_route_config = config.auth_route_config();
let config_server_logout = if config
.config_layer_stack
.requirements_toml()
.requires_remote_config()
{
logout_config_server(&config).await
} else {
Ok(false)
};
// Cleanup is independent of the current feature gate. Retain the grant lock
// through account removal so another process cannot commit a late login.
let enterprise_guard = async {
let Some(profile) = &config.mcp_enterprise_managed_auth else {
return Ok::<_, anyhow::Error>(None);
};
let auth = config
.auth_config()
.load_auth(/*enable_codex_api_key_env*/ false)
.await?;
let Some(scope) = ema_auth_scope(auth.as_ref()) else {
return Ok(None);
};
EnterpriseOAuthCredentialGuard::acquire(
&profile.idp.credential_name(&scope),
&profile.idp.issuer,
config.auth_keyring_backend_kind(),
)
.await
.map(Some)
}
.await;
let cleanup_failed = match &enterprise_guard {
Ok(Some(guard)) => guard.delete_tokens().is_err(),
Ok(None) => false,
Err(_) => true,
};
if cleanup_failed {
eprintln!("Warning: failed to remove enterprise authorization; continuing account logout");
}
let logged_out = match logout_with_revoke(
&config.codex_home,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
&auth_route_config,
)
.await
{
Ok(logged_out) => logged_out,
Err(err) => {
eprintln!("Error logging out: {err}");
std::process::exit(1);
}
};
drop(enterprise_guard);
let cleared_bedrock_config =
if let Some(paths) = ConfigEditsBuilder::bedrock_provider_config_paths_to_clear(&config) {
let edits = paths
.into_iter()
.map(|segments| ConfigEdit::ClearPath { segments });
if let Err(err) = ConfigEditsBuilder::for_config(&config)
.with_edits(edits)
.apply()
.await
{
eprintln!("Error clearing Amazon Bedrock configuration after logout: {err}");
std::process::exit(1);
}
true
} else {
false
};
let config_server_logged_out = match config_server_logout {
Ok(removed) => removed,
Err(error) => {
eprintln!("Error logging out: {error}");
std::process::exit(1);
}
};
if logged_out || config_server_logged_out || cleared_bedrock_config {
eprintln!("Successfully logged out");
} else {
eprintln!("Not logged in");
}
std::process::exit(0);
}
async fn load_managed_login_config_or_exit(cli_config_overrides: CliConfigOverrides) -> Config {
let mut config = load_config_or_exit(cli_config_overrides.clone()).await;
if config
.config_layer_stack
.requirements_toml()
.requires_remote_config()
&& let Err(error) =
sign_in_to_config_server_and_reload_config(&mut config, &cli_config_overrides).await
{
finish_login(Err(error));
}
config
}
async fn load_config_or_exit(cli_config_overrides: CliConfigOverrides) -> Config {
let cli_overrides = match cli_config_overrides.parse_overrides() {
Ok(v) => v,
Err(e) => {
eprintln!("Error parsing -c overrides: {e}");
std::process::exit(1);
}
};
match Config::load_with_cli_overrides(cli_overrides).await {
Ok(config) => match config.auth_config().validate() {
Ok(()) => config,
Err(e) => {
eprintln!("Error loading configuration: {e}");
std::process::exit(1);
}
},
Err(e) => {
eprintln!("Error loading configuration: {e}");
std::process::exit(1);
}
}
}
fn safe_format_key(key: &str) -> String {
if key.len() <= 13 {
return "***".to_string();
}
let prefix = &key[..8];
let suffix = &key[key.len() - 5..];
format!("{prefix}***{suffix}")
}
#[cfg(test)]
#[path = "login_storage_tests.rs"]
mod storage_tests;
#[cfg(test)]
mod tests {
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::load_auth_dot_json;
use codex_login::login_with_api_key;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use super::clear_existing_auth_before_login;
use super::safe_format_key;
#[tokio::test]
async fn clears_existing_auth_before_login() {
let codex_home = tempdir().expect("create temporary Codex home");
login_with_api_key(
codex_home.path(),
"sk-existing",
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)
.expect("save existing auth");
clear_existing_auth_before_login(
codex_home.path(),
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
&codex_login::test_support::transport_default_auth_route_config(),
)
.await;
let auth = load_auth_dot_json(
codex_home.path(),
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)
.expect("load auth after cleanup");
assert_eq!(auth, None);
}
#[test]
fn formats_long_key() {
let key = "sk-proj-1234567890ABCDE";
assert_eq!(safe_format_key(key), "sk-proj-***ABCDE");
}
#[test]
fn short_key_returns_stars() {
let key = "sk-proj-12345";
assert_eq!(safe_format_key(key), "***");
}
}

View File

@@ -0,0 +1,87 @@
//! Verifies storage failures remain visible in direct login diagnostics.
use super::DEFAULT_LOGIN_LOG_FILTER;
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::login_with_api_key;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use tracing_subscriber::EnvFilter;
#[test]
fn login_default_filter_records_sanitized_storage_fallback() -> anyhow::Result<()> {
let home = tempdir()?;
// Fail before accessing the real keyring, then allow the plaintext fallback to succeed.
std::fs::write(home.path().join("secrets"), "not a directory")?;
let log_path = home.path().join("login.log");
let subscriber = tracing_subscriber::fmt()
.without_time()
.with_ansi(false)
.with_env_filter(EnvFilter::new(DEFAULT_LOGIN_LOG_FILTER))
.with_writer(std::fs::File::create(&log_path)?)
.finish();
tracing::subscriber::with_default(subscriber, || {
login_with_api_key(
home.path(),
"private-api-key",
AuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Secrets,
)
})?;
let logs = std::fs::read_to_string(log_path)?;
assert_eq!(logs.lines().count(), 2);
let failure = logs.lines().next().unwrap();
assert!(
failure.contains("failed to save auth to keyring, falling back to file storage"),
"{logs}"
);
assert!(failure.contains("failed to create secrets dir"), "{logs}");
assert!(
logs.contains("credential storage file fallback completed"),
"{logs}"
);
assert!(logs.contains("fallback_reason=\"secure_error\""), "{logs}");
assert!(logs.contains("outcome=\"success\""), "{logs}");
assert!(!logs.contains("private-api-key"));
let completion = logs.lines().last().unwrap();
assert!(!completion.contains(home.path().to_str().unwrap()));
let cause = std::fs::create_dir_all(home.path().join("secrets"))
.unwrap_err()
.to_string();
insta::assert_snapshot!(
logs.replace(
home.path().join("secrets").to_str().unwrap(),
"[SECRETS_PATH]"
)
.replace(&cause, "[OS_ERROR]")
);
Ok(())
}
#[test]
fn login_storage_error_displays_context_and_cause() -> anyhow::Result<()> {
let home = tempdir()?;
let secrets_path = home.path().join("secrets");
std::fs::write(&secrets_path, "not a directory")?;
let cause = std::fs::create_dir_all(&secrets_path)
.unwrap_err()
.to_string();
let error = login_with_api_key(
home.path(),
"private-api-key",
AuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Secrets,
)
.unwrap_err();
let message = error.to_string();
assert!(message.contains(&cause), "{message}");
assert!(!message.contains("private-api-key"));
// The temporary path and native filesystem error differ across platforms.
insta::assert_snapshot!(
message
.replace(secrets_path.to_str().unwrap(), "[SECRETS_PATH]")
.replace(&cause, "[OS_ERROR]")
);
Ok(())
}

5044
codex-rs/cli/src/main.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,587 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use clap::Parser;
use codex_core::config::Config;
use codex_core::config::ConfigOverrides;
use codex_core::config::LoaderOverrides;
use codex_core::plugins_manager_for_config;
use codex_core_plugins::PluginMarketplaceUpgradeOutcome;
use codex_core_plugins::PluginsConfigInput;
use codex_core_plugins::installed_marketplaces::marketplace_install_root;
use codex_core_plugins::installed_marketplaces::resolve_configured_marketplace_root;
use codex_core_plugins::marketplace::marketplace_root_dir;
use codex_core_plugins::marketplace_add::MarketplaceAddOutcome;
use codex_core_plugins::marketplace_add::MarketplaceAddRequest;
use codex_core_plugins::marketplace_add::add_marketplace;
use codex_core_plugins::marketplace_remove::MarketplaceRemoveOutcome;
use codex_core_plugins::marketplace_remove::MarketplaceRemoveRequest;
use codex_core_plugins::marketplace_remove::remove_marketplace;
use codex_utils_cli::CliConfigOverrides;
use serde::Serialize;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use crate::cloud_config;
use crate::plugin_cmd::JsonMarketplaceSource;
use crate::plugin_cmd::configured_marketplace_snapshot_issues;
use crate::plugin_cmd::configured_marketplace_sources;
use crate::plugin_cmd::load_cli_auth_manager;
#[derive(Debug, Parser)]
#[command(bin_name = "codex plugin marketplace")]
pub struct MarketplaceCli {
#[clap(flatten)]
pub config_overrides: CliConfigOverrides,
#[command(subcommand)]
subcommand: MarketplaceSubcommand,
}
#[derive(Debug, clap::Subcommand)]
enum MarketplaceSubcommand {
/// Add a local or Git marketplace to the configured marketplace sources.
Add(AddMarketplaceArgs),
/// List plugin marketplaces Codex is currently considering and their roots.
List(ListMarketplaceArgs),
/// Refresh configured Git marketplace snapshots.
///
/// Omit MARKETPLACE_NAME to upgrade all configured Git marketplaces.
Upgrade(UpgradeMarketplaceArgs),
/// Remove a configured marketplace source by name.
Remove(RemoveMarketplaceArgs),
}
#[derive(Debug, Parser)]
#[command(
bin_name = "codex plugin marketplace add",
after_help = "Examples:\n codex plugin marketplace add ./path/to/marketplace\n codex plugin marketplace add owner/repo --ref main\n codex plugin marketplace add https://github.com/owner/repo --sparse plugins/foo"
)]
struct AddMarketplaceArgs {
/// Marketplace source: a local path, owner/repo[@ref], HTTPS Git URL, or SSH Git URL.
#[arg(value_name = "SOURCE")]
source: String,
/// Git ref to fetch for Git marketplace sources.
#[arg(long = "ref", value_name = "REF")]
ref_name: Option<String>,
/// Sparse checkout path for Git marketplace sources. Can be repeated.
#[arg(
long = "sparse",
value_name = "PATH",
action = clap::ArgAction::Append
)]
sparse_paths: Vec<String>,
/// Output add result as JSON.
#[arg(long = "json")]
json: bool,
}
#[derive(Debug, Parser)]
#[command(bin_name = "codex plugin marketplace list")]
struct ListMarketplaceArgs {
/// Output marketplace list as JSON.
#[arg(long = "json")]
json: bool,
}
#[derive(Debug, Parser)]
#[command(
bin_name = "codex plugin marketplace upgrade",
after_help = "Examples:\n codex plugin marketplace upgrade\n codex plugin marketplace upgrade debug"
)]
struct UpgradeMarketplaceArgs {
/// Optional configured marketplace name to upgrade. Omit to upgrade all Git marketplaces.
#[arg(value_name = "MARKETPLACE_NAME")]
marketplace_name: Option<String>,
/// Output upgrade result as JSON.
#[arg(long = "json")]
json: bool,
}
#[derive(Debug, Parser)]
#[command(
bin_name = "codex plugin marketplace remove",
after_help = "Example:\n codex plugin marketplace remove debug"
)]
struct RemoveMarketplaceArgs {
/// Configured marketplace name to remove.
#[arg(value_name = "MARKETPLACE_NAME")]
marketplace_name: String,
/// Output remove result as JSON.
#[arg(long = "json")]
json: bool,
}
impl MarketplaceCli {
pub async fn run(self) -> Result<()> {
let MarketplaceCli {
config_overrides,
subcommand,
} = self;
let builder = cloud_config::config_builder(
&config_overrides,
LoaderOverrides::default(),
ConfigOverrides::default(),
)
.await?;
let config = builder.clone().build().await?;
match subcommand {
MarketplaceSubcommand::Add(args) => run_add(config, args).await?,
MarketplaceSubcommand::List(args) => run_list(config, args).await?,
MarketplaceSubcommand::Upgrade(args) => run_upgrade(config, args, builder).await?,
MarketplaceSubcommand::Remove(args) => run_remove(config, args).await?,
}
Ok(())
}
}
async fn run_add(config: Config, args: AddMarketplaceArgs) -> Result<()> {
let AddMarketplaceArgs {
source,
ref_name,
sparse_paths,
json,
} = args;
let outcome = add_marketplace(
config.codex_home.to_path_buf(),
config.config_layer_stack.requirements().clone(),
MarketplaceAddRequest {
source,
ref_name,
sparse_paths,
},
)
.await?;
if json {
let output = JsonMarketplaceAddOutput::from_outcome(outcome);
println!("{}", serde_json::to_string_pretty(&output)?);
return Ok(());
}
if outcome.already_added {
println!(
"Marketplace `{}` is already added from {}.",
outcome.marketplace_name, outcome.source_display
);
} else {
println!(
"Added marketplace `{}` from {}.",
outcome.marketplace_name, outcome.source_display
);
}
println!(
"Installed marketplace root: {}",
outcome.installed_root.as_path().display()
);
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceAddOutput {
marketplace_name: String,
installed_root: String,
already_added: bool,
}
impl JsonMarketplaceAddOutput {
fn from_outcome(outcome: MarketplaceAddOutcome) -> Self {
Self {
marketplace_name: outcome.marketplace_name,
installed_root: outcome.installed_root.as_path().display().to_string(),
already_added: outcome.already_added,
}
}
}
async fn run_list(config: Config, args: ListMarketplaceArgs) -> Result<()> {
let manager = plugins_manager_for_config(&config, load_cli_auth_manager(&config).await?);
let plugins_input = config.plugins_config_input();
let marketplace_listing = manager
.discover_marketplaces_for_config(&plugins_input, &[])
.context("failed to list plugin marketplaces")?;
let mut load_issues = configured_marketplace_snapshot_issues(
config.codex_home.as_path(),
&plugins_input,
&marketplace_listing.errors,
/*marketplace_name*/ None,
);
let mut issue_paths = load_issues
.iter()
.map(|issue| issue.path.clone())
.collect::<HashSet<_>>();
for error in &marketplace_listing.errors {
if issue_paths.insert(error.path.to_path_buf()) {
load_issues.push(crate::plugin_cmd::ConfiguredMarketplaceSnapshotIssue {
marketplace_name: error.path.display().to_string(),
path: error.path.to_path_buf(),
message: error.message.clone(),
});
}
}
if !load_issues.is_empty() {
let issue_lines = load_issues
.iter()
.map(|issue| {
format!(
"- `{}` at {}: {}",
issue.marketplace_name,
issue.path.display(),
issue.message
)
})
.collect::<Vec<_>>()
.join("\n");
bail!("failed to load marketplace(s):\n{issue_lines}");
}
let marketplaces = marketplace_listing.marketplaces;
if args.json {
let marketplace_sources =
configured_marketplace_sources_by_root(config.codex_home.as_path(), &plugins_input);
let output =
JsonMarketplaceListOutput::from_marketplaces(marketplaces, &marketplace_sources);
println!("{}", serde_json::to_string_pretty(&output)?);
return Ok(());
}
if marketplaces.is_empty() {
println!("No plugin marketplaces in scope.");
return Ok(());
}
let mut seen_roots = HashSet::new();
let mut rows = Vec::new();
for marketplace in marketplaces {
let Ok(root) = marketplace_root_dir(&marketplace.path) else {
continue;
};
if !seen_roots.insert(root.clone()) {
continue;
}
rows.push((marketplace.name, root));
}
let marketplace_width = rows
.iter()
.map(|(name, _)| name.len())
.max()
.unwrap_or("MARKETPLACE".len())
.max("MARKETPLACE".len());
println!("{:<marketplace_width$} ROOT", "MARKETPLACE");
for (marketplace_name, root) in rows {
println!(
"{:<marketplace_width$} {}",
marketplace_name,
root.display()
);
}
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceListOutput {
marketplaces: Vec<JsonMarketplaceListEntry>,
}
impl JsonMarketplaceListOutput {
fn from_marketplaces(
marketplaces: Vec<codex_core_plugins::marketplace::Marketplace>,
marketplace_sources: &HashMap<PathBuf, JsonMarketplaceSource>,
) -> Self {
let mut seen_roots = HashSet::new();
let marketplaces = marketplaces
.into_iter()
.filter_map(|marketplace| {
let root = marketplace_root_dir(&marketplace.path).ok()?;
if !seen_roots.insert(root.clone()) {
return None;
}
Some(JsonMarketplaceListEntry {
marketplace_source: marketplace_sources.get(root.as_path()).cloned(),
name: marketplace.name,
root: root.display().to_string(),
})
})
.collect();
Self { marketplaces }
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceListEntry {
name: String,
root: String,
#[serde(skip_serializing_if = "Option::is_none")]
marketplace_source: Option<JsonMarketplaceSource>,
}
fn configured_marketplace_sources_by_root(
codex_home: &Path,
plugins_input: &PluginsConfigInput,
) -> HashMap<PathBuf, JsonMarketplaceSource> {
let marketplace_sources = configured_marketplace_sources(plugins_input, codex_home);
let effective_config = plugins_input.config_layer_stack.effective_config();
let Some(marketplaces) = effective_config
.get("marketplaces")
.and_then(toml::Value::as_table)
else {
return HashMap::new();
};
let default_install_root = marketplace_install_root(codex_home);
marketplaces
.iter()
.filter_map(|(marketplace_name, marketplace)| {
let marketplace_source = marketplace_sources.get(marketplace_name)?;
let root = resolve_configured_marketplace_root(
marketplace_name,
marketplace,
&default_install_root,
)?;
Some((root, marketplace_source.clone()))
})
.collect()
}
async fn run_upgrade(
config: Config,
args: UpgradeMarketplaceArgs,
builder: codex_core::config::ConfigBuilder,
) -> Result<()> {
let UpgradeMarketplaceArgs {
marketplace_name,
json,
} = args;
let manager = plugins_manager_for_config(&config, load_cli_auth_manager(&config).await?);
let plugins_input = config.plugins_config_input();
let runtime = tokio::runtime::Handle::current();
let reload_config: codex_core_plugins::ConfigLayerReload = std::sync::Arc::new(move || {
runtime
.block_on(builder.clone().build())
.map(|config| config.config_layer_stack)
});
let requested_name = marketplace_name.clone();
let outcome = tokio::task::spawn_blocking(move || {
manager.upgrade_configured_marketplaces_for_config(
&plugins_input,
requested_name.as_deref(),
&reload_config,
)
})
.await?
.map_err(anyhow::Error::msg)?;
if json {
print_upgrade_outcome_json(&outcome)
} else {
print_upgrade_outcome(&outcome, marketplace_name.as_deref())
}
}
async fn run_remove(config: Config, args: RemoveMarketplaceArgs) -> Result<()> {
let RemoveMarketplaceArgs {
marketplace_name,
json,
} = args;
let outcome = remove_marketplace(
config.codex_home.to_path_buf(),
config.config_layer_stack,
MarketplaceRemoveRequest { marketplace_name },
)
.await?;
if json {
let output = JsonMarketplaceRemoveOutput::from_outcome(outcome);
println!("{}", serde_json::to_string_pretty(&output)?);
return Ok(());
}
println!("Removed marketplace `{}`.", outcome.marketplace_name);
if let Some(installed_root) = outcome.removed_installed_root {
println!(
"Removed installed marketplace root: {}",
installed_root.as_path().display()
);
}
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceRemoveOutput {
marketplace_name: String,
installed_root: Option<String>,
}
impl JsonMarketplaceRemoveOutput {
fn from_outcome(outcome: MarketplaceRemoveOutcome) -> Self {
Self {
marketplace_name: outcome.marketplace_name,
installed_root: outcome
.removed_installed_root
.map(|root| root.as_path().display().to_string()),
}
}
}
fn print_upgrade_outcome_json(outcome: &PluginMarketplaceUpgradeOutcome) -> Result<()> {
for error in &outcome.errors {
eprintln!(
"Failed to upgrade marketplace `{}`: {}",
error.marketplace_name, error.message
);
}
if !outcome.all_succeeded() {
bail!("{} upgrade failure(s) occurred.", outcome.errors.len());
}
let output = JsonMarketplaceUpgradeOutput::from_outcome(outcome);
println!("{}", serde_json::to_string_pretty(&output)?);
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceUpgradeOutput {
selected_marketplaces: Vec<String>,
upgraded_roots: Vec<String>,
errors: Vec<JsonMarketplaceUpgradeError>,
}
impl JsonMarketplaceUpgradeOutput {
fn from_outcome(outcome: &PluginMarketplaceUpgradeOutcome) -> Self {
Self {
selected_marketplaces: outcome.selected_marketplaces.clone(),
upgraded_roots: outcome
.upgraded_roots
.iter()
.map(|root| root.display().to_string())
.collect(),
errors: outcome
.errors
.iter()
.map(|error| JsonMarketplaceUpgradeError {
marketplace_name: error.marketplace_name.clone(),
message: error.message.clone(),
})
.collect(),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceUpgradeError {
marketplace_name: String,
message: String,
}
fn print_upgrade_outcome(
outcome: &PluginMarketplaceUpgradeOutcome,
marketplace_name: Option<&str>,
) -> Result<()> {
for error in &outcome.errors {
eprintln!(
"Failed to upgrade marketplace `{}`: {}",
error.marketplace_name, error.message
);
}
if !outcome.all_succeeded() {
bail!("{} upgrade failure(s) occurred.", outcome.errors.len());
}
let selection_label = marketplace_name.unwrap_or("all configured Git marketplaces");
if outcome.selected_marketplaces.is_empty() {
println!("No configured Git marketplaces to upgrade.");
} else if outcome.upgraded_roots.is_empty() {
if marketplace_name.is_some() {
println!("Marketplace `{selection_label}` is already up to date.");
} else {
println!("All configured Git marketplaces are already up to date.");
}
} else if marketplace_name.is_some() {
println!("Upgraded marketplace `{selection_label}` to the latest configured revision.");
for root in &outcome.upgraded_roots {
println!("Installed marketplace root: {}", root.display());
}
} else {
println!("Upgraded {} marketplace(s).", outcome.upgraded_roots.len());
for root in &outcome.upgraded_roots {
println!("Installed marketplace root: {}", root.display());
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn sparse_paths_parse_before_or_after_source() {
let sparse_before_source =
AddMarketplaceArgs::try_parse_from(["add", "--sparse", "plugins/foo", "owner/repo"])
.unwrap();
assert_eq!(sparse_before_source.source, "owner/repo");
assert_eq!(sparse_before_source.sparse_paths, vec!["plugins/foo"]);
let sparse_after_source =
AddMarketplaceArgs::try_parse_from(["add", "owner/repo", "--sparse", "plugins/foo"])
.unwrap();
assert_eq!(sparse_after_source.source, "owner/repo");
assert_eq!(sparse_after_source.sparse_paths, vec!["plugins/foo"]);
let repeated_sparse = AddMarketplaceArgs::try_parse_from([
"add",
"--sparse",
"plugins/foo",
"--sparse",
"skills/bar",
"owner/repo",
])
.unwrap();
assert_eq!(repeated_sparse.source, "owner/repo");
assert_eq!(
repeated_sparse.sparse_paths,
vec!["plugins/foo", "skills/bar"]
);
}
#[test]
fn upgrade_subcommand_parses_optional_marketplace_name() {
let upgrade_all = UpgradeMarketplaceArgs::try_parse_from(["upgrade"]).unwrap();
assert_eq!(upgrade_all.marketplace_name, None);
let upgrade_one = UpgradeMarketplaceArgs::try_parse_from(["upgrade", "debug"]).unwrap();
assert_eq!(upgrade_one.marketplace_name.as_deref(), Some("debug"));
}
#[test]
fn remove_subcommand_parses_marketplace_name() {
let remove = RemoveMarketplaceArgs::try_parse_from(["remove", "debug"]).unwrap();
assert_eq!(remove.marketplace_name, "debug");
}
}

1164
codex-rs/cli/src/mcp_cmd.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,346 @@
//! Verifies MCP argument handling and managed networking in standalone commands.
use clap::Parser;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpError;
use codex_http_client::NetworkPolicyDenied;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;
use super::McpCli;
use super::McpSubcommand;
#[test]
fn oauth_client_secret_is_redacted_in_parsed_command_debug() {
let cli = McpCli::try_parse_from([
"mcp",
"add",
"private",
"--url",
"https://example.com/mcp",
"--oauth-client-id",
"registered-client",
"--oauth-client-secret",
"cli-secret-marker",
])
.expect("parse confidential client arguments");
let debug = format!("{cli:?}");
assert!(!debug.contains("cli-secret-marker"));
assert!(debug.contains("oauth_client_secret: Some(<redacted>)"));
let McpSubcommand::Add(add) = cli.subcommand else {
panic!("expected MCP add");
};
let http = add.transport_args.streamable_http.expect("HTTP arguments");
assert_eq!(
http.oauth_client_secret
.as_ref()
.map(|secret| secret.as_str()),
Some("cli-secret-marker")
);
}
#[test]
fn oauth_client_secret_requires_url_and_client_id_without_disclosure() {
for args in [
vec!["--url", "https://example.com/mcp"],
vec!["--oauth-client-id", "registered-client"],
] {
let error = McpCli::try_parse_from(
[
"mcp",
"add",
"private",
"--oauth-client-secret",
"cli-secret-marker",
]
.into_iter()
.chain(args),
)
.expect_err("client secret requires both HTTP URL and client ID");
assert_eq!(
error.kind(),
clap::error::ErrorKind::MissingRequiredArgument
);
assert!(!error.to_string().contains("cli-secret-marker"));
}
}
async fn isolated_test_home(test_name: &str) -> anyhow::Result<Option<PathBuf>> {
const CHILD: &str = "CODEX_MCP_NETWORK_TEST_CHILD";
let test_name = format!("mcp_cmd::tests::{test_name}");
if std::env::var(CHILD).as_deref() == Ok(test_name.as_str()) {
return Ok(Some(codex_core::config::find_codex_home()?.to_path_buf()));
}
// Only the child receives the temporary home; the production loader resolves
// CODEX_HOME normally and the parent test process keeps its environment.
let home = tempfile::tempdir()?;
let output = timeout(
Duration::from_secs(45),
Command::new(std::env::current_exe()?)
.args(["--exact", &test_name, "--nocapture"])
.kill_on_drop(true)
.env(CHILD, &test_name)
.env("CODEX_HOME", home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.current_dir(home.path())
.output(),
)
.await??;
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed; 0 failed"),
"{test_name}: {stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(None)
}
async fn config_with_application_network(
home: &std::path::Path,
requirements: &str,
extra_config: &str,
) -> anyhow::Result<codex_core::config::Config> {
std::fs::write(
home.join("config.toml"),
format!(
"forced_login_method = 'api'\n\
cli_auth_credentials_store = 'file'\n\
mcp_oauth_credentials_store = 'file'\n\
[features]\nplugins = false\nrecommended_plugins = false\n\
{extra_config}"
),
)?;
let requirements_path = home.join("requirements.toml");
std::fs::write(&requirements_path, requirements)?;
crate::cloud_config::load_config(
&codex_utils_cli::CliConfigOverrides::default(),
codex_core::config::LoaderOverrides {
system_config_path: Some(home.join("absent-system-config.toml")),
system_requirements_path: Some(requirements_path),
ignore_project_config: true,
..codex_core::config::LoaderOverrides::without_managed_config_for_tests()
},
)
.await
}
fn http_add_args(url: &str) -> super::AddArgs {
let cli = McpCli::try_parse_from(["mcp", "add", "policy-probe", "--url", url])
.expect("parse HTTP add arguments");
let McpSubcommand::Add(args) = cli.subcommand else {
panic!("expected MCP add");
};
args
}
#[tokio::test]
async fn application_network_mcp_add_denies_initial_oauth_discovery_before_connect()
-> anyhow::Result<()> {
let Some(home) = isolated_test_home(
"application_network_mcp_add_denies_initial_oauth_discovery_before_connect",
)
.await?
else {
return Ok(());
};
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
listener.set_nonblocking(true)?;
let url = format!("https://{}/mcp", listener.local_addr()?);
let config = config_with_application_network(&home, "[application.network]\n", "").await?;
// Add deliberately saves the server when discovery is unknown. A successful
// command is therefore not evidence that its network request was permitted.
tokio::time::timeout(
std::time::Duration::from_secs(5),
super::run_add(&config, http_add_args(&url)),
)
.await??;
let saved: toml::Value = toml::from_str(&std::fs::read_to_string(home.join("config.toml"))?)?;
assert_eq!(
saved["mcp_servers"]["policy-probe"]["url"].as_str(),
Some(url.as_str())
);
// No accepted TCP connection also proves no HTTP discovery request arrived.
assert_eq!(
listener.accept().unwrap_err().kind(),
std::io::ErrorKind::WouldBlock
);
Ok(())
}
#[tokio::test]
async fn application_network_mcp_add_discovers_when_policy_is_disabled() -> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_mcp_add_discovers_when_policy_is_disabled").await?
else {
return Ok(());
};
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::any())
.respond_with(wiremock::ResponseTemplate::new(404))
.mount(&server)
.await;
let url = format!("{}/mcp", server.uri());
let config =
config_with_application_network(&home, "[application.network]\nenabled = false\n", "")
.await?;
tokio::time::timeout(
std::time::Duration::from_secs(5),
super::run_add(&config, http_add_args(&url)),
)
.await??;
let requests = server.received_requests().await.expect("recorded requests");
assert!(
requests.iter().any(|request| request.url.path() == "/mcp"),
"the positive control must perform real OAuth discovery"
);
// The 404 response has no OAuth support, so this cannot open a browser.
Ok(())
}
#[tokio::test]
async fn application_network_mcp_login_denies_even_an_allowed_mcp_server() -> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_mcp_login_denies_even_an_allowed_mcp_server")
.await?
else {
return Ok(());
};
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
listener.set_nonblocking(true)?;
let url = format!("https://{}/mcp", listener.local_addr()?);
let requirements =
format!("[application.network]\n[mcp_servers.policy-probe.identity]\nurl = {url:?}\n");
let extra_config = format!("[mcp_servers.policy-probe]\nurl = {url:?}\n");
let config = config_with_application_network(&home, &requirements, &extra_config).await?;
let server = &config.mcp_servers.get()["policy-probe"];
assert!(
server.enabled,
"MCP identity allowlist must permit this server"
);
assert!(server.disabled_reason.is_none());
let error = tokio::time::timeout(
std::time::Duration::from_secs(5),
super::run_login(
&config,
super::LoginArgs {
name: "policy-probe".to_string(),
no_browser: true,
scopes: Vec::new(),
oauth_client_registration: None,
},
),
)
.await?
.expect_err("MCP permission must not override application network restrictions");
let message = format!("{error:#}");
assert!(
message.contains("destination denied by application network policy"),
"{message}"
);
assert_eq!(
listener.accept().unwrap_err().kind(),
std::io::ErrorKind::WouldBlock
);
Ok(())
}
#[tokio::test]
async fn application_network_loader_denies_unlisted_destination_before_connect()
-> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_loader_denies_unlisted_destination_before_connect")
.await?
else {
return Ok(());
};
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
listener.set_nonblocking(true)?;
let url = format!("https://{}/must-not-connect", listener.local_addr()?);
let config = config_with_application_network(
&home,
"[application.network.domains]\n'allowed.example' = 'allow'\n",
"",
)
.await?;
let factory = config.http_client_factory();
factory
.network_policy()
.acquire(&"https://allowed.example/v1".parse()?)?;
let client = factory.build_client(&url, ClientRouteClass::Other)?;
assert!(matches!(
timeout(Duration::from_secs(2), client.get(&url).send()).await?,
Err(HttpError::Policy(NetworkPolicyDenied::Destination))
));
assert_eq!(
listener.accept().unwrap_err().kind(),
std::io::ErrorKind::WouldBlock
);
Ok(())
}
#[tokio::test]
async fn application_network_loader_allows_listed_https_destination_to_connect()
-> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_loader_allows_listed_https_destination_to_connect")
.await?
else {
return Ok(());
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let url = format!("https://{}/allowed", listener.local_addr()?);
let config = config_with_application_network(
&home,
"[application.network.domains]\n'127.0.0.1' = 'allow'\n",
"",
)
.await?;
let client = config
.http_client_factory()
.build_client(&url, ClientRouteClass::Other)?;
let (response, connection) = timeout(Duration::from_secs(2), async {
tokio::join!(client.get(&url).send(), async {
let (stream, _) = listener.accept().await?;
// This listener proves TCP permission; it deliberately does not provide TLS.
drop(stream);
Ok::<_, std::io::Error>(())
})
})
.await?;
connection?;
assert!(response.is_err(), "the raw listener cannot complete TLS");
assert!(!matches!(response, Err(HttpError::Policy(_))));
Ok(())
}
#[tokio::test]
async fn application_network_loader_rejects_malformed_managed_policy() -> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_loader_rejects_malformed_managed_policy").await?
else {
return Ok(());
};
let error = config_with_application_network(
&home,
"[application.network.domains]\n'*.example.com' = 'allow'\n",
"",
)
.await
.expect_err("invalid application policy must not load as unrestricted");
let message = format!("{error:#}");
assert!(message.contains("requirements.toml"), "{message}");
assert!(
message.contains("application.network.domains requires exact ASCII domain names"),
"{message}"
);
Ok(())
}

View File

@@ -0,0 +1,266 @@
//! CLI MCP OAuth login modes and bounded, hidden callback input.
//!
//! Manual input remains cancellable while the OAuth flow waits for its HTTP
//! callback, and dropping terminal input restores the terminal immediately.
//! Ctrl-C also cancels token exchange and scope retries in manual login mode.
use std::collections::HashMap;
use std::io;
use std::io::BufRead;
use std::io::IsTerminal;
use std::io::Write;
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use codex_config::McpServerOAuthConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::HttpClient;
use codex_mcp::ResolvedMcpOAuthScopes;
use codex_mcp::should_retry_without_scopes;
use codex_rmcp_client::McpOAuthClientRegistration;
use codex_rmcp_client::perform_oauth_login;
use codex_rmcp_client::perform_oauth_login_with_callback_input;
use crossterm::event::Event;
use crossterm::event::EventStream;
use crossterm::event::KeyCode;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use crossterm::terminal;
use futures::StreamExt;
use tokio::sync::oneshot;
const MAX_CALLBACK_BYTES: usize = 64 * 1024;
#[derive(Clone, Copy)]
pub(crate) enum McpLoginMode {
Browser,
PasteCallback,
}
/// Retry provider-rejected discovered scopes once, retaining the selected input mode.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn perform_oauth_login_retry_without_scopes(
name: &str,
url: &str,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
resolved_scopes: &ResolvedMcpOAuthScopes,
oauth_config: Option<&McpServerOAuthConfig>,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
callback_port: Option<u16>,
callback_url: Option<&str>,
global_callback_url: Option<&str>,
http_client: Arc<dyn HttpClient>,
mode: McpLoginMode,
) -> Result<()> {
let mut pending_input = None;
// Tokio retains its process-wide signal handler, so keep listening throughout
// token exchange and scope retries after the callback input reader is dropped.
let ctrl_c = tokio::signal::ctrl_c();
tokio::pin!(ctrl_c);
for (attempt, scopes) in [resolved_scopes.scopes.as_slice(), &[]]
.into_iter()
.enumerate()
{
let login = async {
match mode {
McpLoginMode::Browser => {
perform_oauth_login(
name,
url,
store_mode,
keyring_backend_kind,
http_headers.clone(),
env_http_headers.clone(),
scopes,
oauth_config,
client_registration,
oauth_resource,
callback_port,
callback_url,
global_callback_url,
Arc::clone(&http_client),
)
.await
}
McpLoginMode::PasteCallback => {
let input = &mut pending_input;
perform_oauth_login_with_callback_input(
name,
url,
store_mode,
keyring_backend_kind,
http_headers.clone(),
env_http_headers.clone(),
scopes,
oauth_config,
client_registration,
oauth_resource,
callback_port,
callback_url,
global_callback_url,
Arc::clone(&http_client),
move |authorization_url| read_callback(authorization_url, input),
)
.await
}
}
};
let result = tokio::select! {
result = login => result,
result = &mut ctrl_c, if matches!(mode, McpLoginMode::PasteCallback) => {
result.context("failed to listen for Ctrl-C")?;
bail!("OAuth login cancelled");
}
};
match result {
Err(error) if attempt == 0 && should_retry_without_scopes(resolved_scopes, &error) => {
println!("OAuth provider rejected discovered scopes. Retrying without scopes…");
}
result => return result,
}
}
unreachable!("the empty-scope attempt always returns")
}
async fn read_callback(
authorization_url: String,
pending_input: &mut Option<oneshot::Receiver<Result<String>>>,
) -> Result<String> {
println!(
"Authorize the MCP server by opening this URL in your browser:\n{authorization_url}\n"
);
println!(
"After signing in, copy the full URL from your browser's address bar.\n\
If the callback page cannot load, paste that URL here anyway."
);
if io::stdin().is_terminal() {
return read_terminal_callback().await;
}
print_callback_prompt()?;
// A pipe may stay open after the HTTP callback wins. A detached thread avoids
// making runtime shutdown wait for an uncancellable blocking stdin read.
// Retain an unfinished read if an HTTP provider error triggers a scope retry.
// Otherwise its detached reader could consume the next attempt's pasted URL.
if pending_input.is_none() {
let (tx, rx) = oneshot::channel();
std::thread::Builder::new()
.name("mcp-oauth-callback-input".to_string())
.spawn(move || {
let result = read_callback_line(io::stdin().lock());
let _ = tx.send(result);
})
.context("failed to start callback input reader")?;
*pending_input = Some(rx);
}
let reader = pending_input
.as_mut()
.context("callback input reader was unavailable")?;
let result = reader.await;
*pending_input = None;
result.context("callback input reader stopped")?
}
fn read_callback_line(reader: impl BufRead) -> Result<String> {
let mut bytes = Vec::new();
reader
.take((MAX_CALLBACK_BYTES + 3) as u64)
.read_until(b'\n', &mut bytes)
.context("failed to read callback URL")?;
if bytes.ends_with(b"\n") {
bytes.pop();
}
if bytes.ends_with(b"\r") {
bytes.pop();
}
if bytes.len() > MAX_CALLBACK_BYTES {
bail!("OAuth callback URL exceeds 64 KiB");
}
if bytes.is_empty() {
bail!("No OAuth callback URL received before input closed");
}
String::from_utf8(bytes).map_err(|_| anyhow::anyhow!("OAuth callback URL must be valid UTF-8"))
}
struct TerminalInputGuard;
impl Drop for TerminalInputGuard {
fn drop(&mut self) {
let _ = terminal::disable_raw_mode();
eprintln!();
}
}
fn print_callback_prompt() -> Result<()> {
eprint!("Callback URL (input hidden): ");
io::stderr()
.flush()
.context("failed to display callback prompt")
}
async fn read_terminal_callback() -> Result<String> {
terminal::enable_raw_mode().context("failed to hide callback input")?;
let _guard = TerminalInputGuard;
print_callback_prompt()?;
let mut events = EventStream::new();
let mut input = String::new();
loop {
let event = events
.next()
.await
.context("callback input stream closed")?
.context("failed to read callback input")?;
match event {
Event::Key(key) if key.kind != KeyEventKind::Release => match key.code {
KeyCode::Enter => {
if input.is_empty() {
bail!("No OAuth callback URL entered");
}
return Ok(input);
}
KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
bail!("OAuth login cancelled");
}
KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
bail!("No OAuth callback URL received before input closed");
}
KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
input.clear()
}
KeyCode::Backspace => {
input.pop();
}
KeyCode::Char(character)
if !character.is_control()
&& !key.modifiers.contains(KeyModifiers::CONTROL) =>
{
if input.len() + character.len_utf8() > MAX_CALLBACK_BYTES {
bail!("OAuth callback URL exceeds 64 KiB");
}
input.push(character);
}
_ => {}
},
Event::Paste(paste) => {
if input.len() + paste.len() > MAX_CALLBACK_BYTES {
bail!("OAuth callback URL exceeds 64 KiB");
}
input.push_str(&paste);
}
_ => {}
}
// Yield even with queued input so callback completion and timeout stay responsive.
tokio::task::yield_now().await;
}
}
#[cfg(test)]
#[path = "mcp_login_tests.rs"]
mod tests;

View File

@@ -0,0 +1,46 @@
//! Checks bounded callback input independently of terminal state.
use super::MAX_CALLBACK_BYTES;
use super::read_callback_line;
use pretty_assertions::assert_eq;
use std::io::Cursor;
#[test]
fn callback_line_accepts_crlf_and_eof_after_input() {
for input in [
"https://example.test/callback?code=abc\r\n",
"https://example.test/callback?code=abc",
] {
assert_eq!(
read_callback_line(Cursor::new(input)).expect("read callback URL"),
"https://example.test/callback?code=abc"
);
}
}
#[test]
fn callback_line_is_bounded_and_does_not_expose_input_in_errors() {
let maximum_input = "s".repeat(MAX_CALLBACK_BYTES);
assert_eq!(
read_callback_line(Cursor::new(format!("{maximum_input}\r\n"))).expect("bounded input"),
maximum_input
);
let input = "s".repeat(MAX_CALLBACK_BYTES + 1);
assert_eq!(
read_callback_line(Cursor::new(input))
.unwrap_err()
.to_string(),
"OAuth callback URL exceeds 64 KiB"
);
assert_eq!(
read_callback_line(Cursor::new("")).unwrap_err().to_string(),
"No OAuth callback URL received before input closed"
);
assert_eq!(
format!(
"{:?}",
read_callback_line(Cursor::new(b"sensitive\xff")).unwrap_err()
),
"OAuth callback URL must be valid UTF-8"
);
}

View File

@@ -0,0 +1,117 @@
//! Confirms explicit database migration and reports the shared migrator's results.
//! Other SQLite clients must remain stopped during replacement, and NFS must enforce
//! cross-client POSIX locks.
use anyhow::Context;
use anyhow::ensure;
use clap::Parser;
use codex_config::LoaderOverrides;
use codex_core::config::ConfigBuilder;
use codex_state::NfsDbMigration;
use codex_state::NfsDbMigrationOutcome;
use codex_utils_cli::CliConfigOverrides;
use owo_colors::OwoColorize;
use std::path::PathBuf;
#[derive(Debug, Parser)]
#[command(
after_help = "Stop SQLite clients on every host and keep them stopped through cutover.\nThe NFS mount must support cross-client POSIX locks (no nolock/local_lock=all).\nThis command replaces configured databases in place and retains their WAL backups."
)]
pub(crate) struct MigrateNfsDbCommand {
/// Use a local directory with space for the database and WAL files.
/// The default is the system temporary directory.
#[arg(long, default_value_os_t = std::env::temp_dir())]
staging_dir: PathBuf,
}
pub(crate) async fn run(
command: MigrateNfsDbCommand,
config_overrides: CliConfigOverrides,
loader_overrides: LoaderOverrides,
) -> anyhow::Result<()> {
ensure!(
cfg!(unix),
"migrate-nfs-db currently requires Unix filesystem locking and directory fsync"
);
let warning = "WARNING: This operation is unsafe under concurrency.";
if supports_color::on(supports_color::Stream::Stderr).is_some() {
eprintln!("{}", warning.red().bold());
} else {
eprintln!("{warning}");
}
eprintln!(
"Stop all Codex instances on every host that uses these databases.\nKeep them stopped until the migration completes successfully."
);
let config = ConfigBuilder::default()
.cli_overrides(
config_overrides
.parse_overrides()
.map_err(anyhow::Error::msg)?,
)
.loader_overrides(loader_overrides)
.build()
.await?;
// Check the merged config for an explicit log directory.
let effective_config = config.config_layer_stack.effective_config();
let skip_logs = effective_config.get("log_dir").is_some();
let sqlite = config.sqlite_config();
if !sqlite.home().try_exists()? {
println!("No databases found.");
return Ok(());
}
let mut needs_permission_confirmation = false;
for database in sqlite.runtime_db_paths() {
if skip_logs && database.path == sqlite.logs_db_path() {
continue;
}
needs_permission_confirmation |=
NfsDbMigration::needs_permission_confirmation(&database.path)?;
}
if needs_permission_confirmation {
eprintln!(
"Some database files have permissions other than 0600.\nMigration preserves file mode bits, including group and other access."
);
}
eprintln!(
"Replacement files belong to you; the original owner, group, and extended ACLs are not copied.\nThis can remove another user's access even when file permissions are 0600.\nOriginal files remain in a private backup directory.\nYou need write access to the database directory and its migration lock."
);
let prompt = if needs_permission_confirmation {
"Migrate databases, including files with permissions other than 0600? [y/N]:"
} else {
"Continue? [y/N]:"
};
ensure!(
crate::confirm(prompt)?,
"Migration cancelled. No databases were changed."
);
let mut migration = NfsDbMigration::lock(sqlite.home())?;
let mut databases_found = 0;
for database in sqlite.runtime_db_paths() {
if skip_logs && database.path == sqlite.logs_db_path() {
println!("Skipped logs database: log_dir is configured.");
continue;
}
let outcome = migration.migrate(&database.path, &command.staging_dir).await.with_context(|| format!(
"migration failed for {}. Keep all Codex instances stopped. Correct the error and rerun codex migrate-nfs-db",
database.path.display()
))?;
match outcome {
NfsDbMigrationOutcome::Missing => continue,
NfsDbMigrationOutcome::AlreadyDelete => {
println!("Already in DELETE mode: {}", database.path.display())
}
NfsDbMigrationOutcome::Migrated { backup_directory } => println!(
"Migrated database: {}\nWAL backup: {}",
database.path.display(),
backup_directory.display()
),
}
databases_found += 1;
}
if databases_found == 0 {
println!("No databases found.");
return Ok(());
}
println!("Migration completed successfully. You can restart Codex.");
Ok(())
}

View File

@@ -0,0 +1,450 @@
use std::io;
use std::io::IsTerminal;
use std::io::Write;
use std::path::Path;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use clap::Parser;
use codex_core::config::ConfigBuilder;
use codex_protocol::ThreadId;
use codex_thread_store::LocalThreadStore;
use codex_thread_store::LocalThreadStoreConfig;
use codex_thread_store::RolloutMigrationMode;
use codex_thread_store::RolloutMigrationOptions;
use codex_thread_store::RolloutMigrationProgress;
use codex_thread_store::RolloutMigrationReport;
use codex_thread_store::RolloutMigrationStatus;
use codex_utils_cli::CliConfigOverrides;
#[derive(Debug, Parser)]
pub(crate) struct MigrateRolloutsCommand {
/// Publish the migration. Without this flag the command only reports eligible sessions.
#[arg(long)]
apply: bool,
/// Restrict inspection or migration to one or more thread IDs.
#[arg(long, value_name = "THREAD_ID", value_parser = ThreadId::from_string)]
thread: Vec<ThreadId>,
/// Limit aggregate rollout read and write throughput, in MiB per second.
#[arg(
long,
value_name = "MIB",
value_parser = clap::value_parser!(u64).range(1..)
)]
max_mib_per_second: Option<u64>,
/// Emit the complete per-thread report as JSON.
#[arg(long)]
json: bool,
/// Print one line for every inspected rollout.
#[arg(long)]
verbose: bool,
}
pub(crate) async fn run(
command: MigrateRolloutsCommand,
config_overrides: CliConfigOverrides,
) -> anyhow::Result<()> {
let overrides = config_overrides
.parse_overrides()
.map_err(anyhow::Error::msg)?;
let config = ConfigBuilder::default()
.cli_overrides(overrides)
.build()
.await?;
let otel = codex_core::otel_init::build_provider(
&config,
env!("CARGO_PKG_VERSION"),
/*service_name_override*/ None,
/*default_analytics_enabled*/ true,
)
.unwrap_or_else(|error| {
eprintln!("Could not create otel exporter: {error}");
None
});
codex_core::otel_init::record_process_start(otel.as_ref(), "codex_migrate_rollouts");
let mode = if command.apply {
RolloutMigrationMode::Apply
} else {
RolloutMigrationMode::DryRun
};
let json = command.json;
let verbose = command.verbose;
let thread_history_db_path = config.sqlite.thread_history_db_path();
let thread_storage_before = if mode == RolloutMigrationMode::Apply && !json {
thread_storage_bytes(
config.codex_home.as_path(),
thread_history_db_path.as_path(),
)
.await
.ok()
} else {
None
};
let state_db = if mode == RolloutMigrationMode::Apply {
Some(
codex_rollout::state_db::try_init(&config)
.await
.context("failed to initialize local thread metadata")?,
)
} else {
None
};
let store = LocalThreadStore::new(LocalThreadStoreConfig::from_config(&config), state_db);
let mut progress = MigrationProgress::new(mode, json);
progress.begin();
let result = store
.migrate_rollouts_with_progress(
RolloutMigrationOptions {
mode,
thread_ids: command.thread,
max_mib_per_second: command.max_mib_per_second,
},
|update| progress.update(update),
)
.await;
progress.finish();
let report = result?;
let thread_storage = match thread_storage_before {
Some(before) => thread_storage_bytes(
config.codex_home.as_path(),
thread_history_db_path.as_path(),
)
.await
.ok()
.map(|after| (before, after)),
None => None,
};
if json {
println!("{}", serde_json::to_string_pretty(&report)?);
} else {
print_human_report(&report, mode, verbose, progress.elapsed(), thread_storage);
}
if report
.outcomes
.iter()
.any(|outcome| outcome.status == RolloutMigrationStatus::Failed)
{
anyhow::bail!("one or more rollout migrations failed");
}
Ok(())
}
const TTY_PROGRESS_INTERVAL: Duration = Duration::from_millis(250);
const NON_TTY_PROGRESS_INTERVAL: usize = 1_000;
const MAX_EXCEPTION_DETAILS: usize = 20;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ProgressOutput {
Quiet,
Tty,
Plain,
}
struct MigrationProgress {
mode: RolloutMigrationMode,
output: ProgressOutput,
started_at: Instant,
last_rendered_at: Instant,
last_plain_processed: usize,
counts: MigrationCounts,
wrote_tty_line: bool,
}
impl MigrationProgress {
fn new(mode: RolloutMigrationMode, json: bool) -> Self {
let now = Instant::now();
let output = if json {
ProgressOutput::Quiet
} else if io::stderr().is_terminal()
&& std::env::var("TERM").ok().as_deref() != Some("dumb")
{
ProgressOutput::Tty
} else {
ProgressOutput::Plain
};
Self {
mode,
output,
started_at: now,
last_rendered_at: now,
last_plain_processed: 0,
counts: MigrationCounts::default(),
wrote_tty_line: false,
}
}
fn begin(&self) {
if self.output != ProgressOutput::Quiet {
eprintln!("Scanning local rollouts...");
}
}
fn update(&mut self, update: RolloutMigrationProgress) {
if let Some(status) = update.outcome_status {
self.counts.observe(status);
}
match self.output {
ProgressOutput::Quiet => {}
ProgressOutput::Tty
if update.processed_paths == update.total_paths
|| self.last_rendered_at.elapsed() >= TTY_PROGRESS_INTERVAL =>
{
let line = self.line(update);
let mut stderr = io::stderr().lock();
let _ = write!(stderr, "\r\x1b[2K{line}");
let _ = stderr.flush();
self.last_rendered_at = Instant::now();
self.wrote_tty_line = true;
}
ProgressOutput::Plain
if update.processed_paths == update.total_paths
|| update
.processed_paths
.saturating_sub(self.last_plain_processed)
>= NON_TTY_PROGRESS_INTERVAL =>
{
eprintln!("{}", self.line(update));
self.last_plain_processed = update.processed_paths;
}
ProgressOutput::Tty | ProgressOutput::Plain => {}
}
}
fn finish(&mut self) {
if self.output != ProgressOutput::Tty || !self.wrote_tty_line {
return;
}
let mut stderr = io::stderr().lock();
let _ = write!(stderr, "\r\x1b[2K");
let _ = stderr.flush();
self.wrote_tty_line = false;
}
fn elapsed(&self) -> Duration {
self.started_at.elapsed()
}
fn line(&self, update: RolloutMigrationProgress) -> String {
let percent = update
.processed_paths
.saturating_mul(100)
.checked_div(update.total_paths)
.unwrap_or(100);
let action = match self.mode {
RolloutMigrationMode::DryRun => "Checking",
RolloutMigrationMode::Apply => "Migrating",
};
let status_counts = match self.mode {
RolloutMigrationMode::DryRun => format!(
"{} eligible • {} already paginated",
self.counts.eligible, self.counts.already_paginated
),
RolloutMigrationMode::Apply => format!(
"{} migrated • {} already paginated",
self.counts.migrated, self.counts.already_paginated
),
};
format!(
"{action} rollouts {}/{} ({percent}%) • {status_counts} • {} skipped • {} failed • {}",
update.processed_paths,
update.total_paths,
self.counts.skipped(),
self.counts.failed,
format_elapsed(self.elapsed()),
)
}
}
#[derive(Default)]
struct MigrationCounts {
eligible: usize,
migrated: usize,
already_paginated: usize,
skipped_empty: usize,
skipped_busy: usize,
failed: usize,
}
impl MigrationCounts {
fn observe(&mut self, status: RolloutMigrationStatus) {
match status {
RolloutMigrationStatus::Eligible => self.eligible += 1,
RolloutMigrationStatus::Migrated => self.migrated += 1,
RolloutMigrationStatus::AlreadyPaginated => self.already_paginated += 1,
RolloutMigrationStatus::SkippedEmpty => self.skipped_empty += 1,
RolloutMigrationStatus::SkippedBusy => self.skipped_busy += 1,
RolloutMigrationStatus::Failed => self.failed += 1,
}
}
fn skipped(&self) -> usize {
self.skipped_empty + self.skipped_busy
}
}
fn print_human_report(
report: &RolloutMigrationReport,
mode: RolloutMigrationMode,
verbose: bool,
elapsed: Duration,
thread_storage: Option<(u64, u64)>,
) {
let mut counts = MigrationCounts::default();
for outcome in &report.outcomes {
counts.observe(outcome.status);
}
let completion = match mode {
RolloutMigrationMode::DryRun => "Scan complete",
RolloutMigrationMode::Apply => "Migration complete",
};
println!("{completion} in {}.", format_elapsed(elapsed));
match mode {
RolloutMigrationMode::DryRun => println!(
"Scanned {} rollout(s): {} eligible, {} already paginated, {} skipped ({} empty, {} busy), {} failed.",
report.outcomes.len(),
counts.eligible,
counts.already_paginated,
counts.skipped(),
counts.skipped_empty,
counts.skipped_busy,
counts.failed,
),
RolloutMigrationMode::Apply => println!(
"Scanned {} rollout(s): {} migrated, {} already paginated, {} skipped ({} empty, {} busy), {} failed.",
report.outcomes.len(),
counts.migrated,
counts.already_paginated,
counts.skipped(),
counts.skipped_empty,
counts.skipped_busy,
counts.failed,
),
}
if let Some((before, after)) = thread_storage {
println!(
"Disk used for thread storage: {} -> {}",
format_bytes(before),
format_bytes(after)
);
}
if mode == RolloutMigrationMode::DryRun && counts.eligible > 0 {
println!("Run `codex migrate-rollouts --apply` to migrate eligible sessions.");
}
if verbose {
for outcome in &report.outcomes {
print_outcome(outcome);
}
return;
}
let exceptions = report.outcomes.iter().filter(|outcome| {
matches!(
outcome.status,
RolloutMigrationStatus::SkippedBusy | RolloutMigrationStatus::Failed
)
});
let exception_count = exceptions.clone().count();
if exception_count == 0 {
return;
}
println!();
for outcome in exceptions.take(MAX_EXCEPTION_DETAILS) {
print_outcome(outcome);
}
if exception_count > MAX_EXCEPTION_DETAILS {
println!(
"... and {} more; rerun with --json for the complete report.",
exception_count - MAX_EXCEPTION_DETAILS
);
}
}
fn print_outcome(outcome: &codex_thread_store::RolloutMigrationOutcome) {
let status = match outcome.status {
RolloutMigrationStatus::Eligible => "eligible",
RolloutMigrationStatus::Migrated => "migrated",
RolloutMigrationStatus::AlreadyPaginated => "already paginated",
RolloutMigrationStatus::SkippedEmpty => "skipped empty",
RolloutMigrationStatus::SkippedBusy => "skipped busy",
RolloutMigrationStatus::Failed => "failed",
};
let thread_id = outcome
.thread_id
.map_or_else(|| "unknown".to_string(), |thread_id| thread_id.to_string());
match &outcome.message {
Some(message) => println!("{status}\t{thread_id}\t{message}"),
None => println!("{status}\t{thread_id}"),
}
}
fn format_elapsed(elapsed: Duration) -> String {
let seconds = elapsed.as_secs();
let minutes = seconds / 60;
if minutes == 0 {
return format!("{seconds}s");
}
let hours = minutes / 60;
if hours == 0 {
return format!("{minutes}m{:02}s", seconds % 60);
}
format!("{hours}h{:02}m{:02}s", minutes % 60, seconds % 60)
}
async fn thread_storage_bytes(codex_home: &Path, thread_history_db_path: &Path) -> io::Result<u64> {
let mut bytes = 0_u64;
let mut directories = vec![
codex_home.join(codex_rollout::SESSIONS_SUBDIR),
codex_home.join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR),
];
while let Some(directory) = directories.pop() {
let mut entries = match tokio::fs::read_dir(&directory).await {
Ok(entries) => entries,
Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
Err(error) => return Err(error),
};
while let Some(entry) = entries.next_entry().await? {
let file_type = entry.file_type().await?;
if file_type.is_dir() {
directories.push(entry.path());
} else if file_type.is_file() {
bytes = bytes.saturating_add(entry.metadata().await?.len());
}
}
}
for suffix in ["", "-wal", "-shm"] {
let mut path = thread_history_db_path.as_os_str().to_owned();
path.push(suffix);
match tokio::fs::metadata(path).await {
Ok(metadata) => bytes = bytes.saturating_add(metadata.len()),
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
Ok(bytes)
}
fn format_bytes(bytes: u64) -> String {
const KIB: f64 = 1024.0;
const MIB: f64 = KIB * 1024.0;
const GIB: f64 = MIB * 1024.0;
let bytes = bytes as f64;
if bytes >= GIB {
format!("{:.1} GB", bytes / GIB)
} else if bytes >= MIB {
format!("{:.1} MB", bytes / MIB)
} else if bytes >= KIB {
format!("{:.1} KB", bytes / KIB)
} else {
format!("{} B", bytes as u64)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,76 @@
//! Verify plugin-list output error handling at the writer boundary.
use super::ListPluginsArgs;
use super::write_plugin_list;
use pretty_assertions::assert_eq;
use std::io;
use std::io::Write;
#[derive(Clone, Copy)]
enum Failure {
Write,
Flush,
}
struct FailingWriter {
failure: Failure,
kind: io::ErrorKind,
}
impl Write for FailingWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match self.failure {
Failure::Write => Err(io::Error::new(self.kind, "output failed")),
Failure::Flush => Ok(bytes.len()),
}
}
fn flush(&mut self) -> io::Result<()> {
match self.failure {
Failure::Write => Ok(()),
Failure::Flush => Err(io::Error::new(self.kind, "output failed")),
}
}
}
#[test]
fn plugin_list_treats_broken_pipe_as_success() {
for json in [false, true] {
for failure in [Failure::Write, Failure::Flush] {
let mut writer = FailingWriter {
failure,
kind: io::ErrorKind::BrokenPipe,
};
let args = ListPluginsArgs {
marketplace_name: None,
json,
available: true,
};
write_plugin_list(&mut writer, Vec::new(), args).unwrap();
}
}
}
#[test]
fn plugin_list_preserves_other_output_errors() {
for json in [false, true] {
for failure in [Failure::Write, Failure::Flush] {
for kind in [io::ErrorKind::PermissionDenied, io::ErrorKind::WriteZero] {
let mut writer = FailingWriter { failure, kind };
let args = ListPluginsArgs {
marketplace_name: None,
json,
available: true,
};
let error = write_plugin_list(&mut writer, Vec::new(), args)
.unwrap_err()
.downcast::<io::Error>()
.unwrap();
assert_eq!(error.kind(), kind);
assert_eq!(error.to_string(), "output failed");
}
}
}
}

View File

@@ -0,0 +1,153 @@
use clap::Arg;
use clap::ArgMatches;
use clap::Command;
use clap::CommandFactory;
use clap::Parser;
use clap::builder::NonEmptyStringValueParser;
use clap::error::ErrorKind;
use clap::parser::ValueSource;
use codex_arg0::Arg0DispatchPaths;
use codex_tui::Cli as TuiCli;
use codex_utils_cli::CliConfigOverrides;
use crate::InteractiveRemoteOptions;
use crate::SessionArchiveConfigOverrides;
use crate::finalize_session_archive_interactive;
use crate::resolve_remote_endpoint;
#[derive(Debug, Parser)]
#[command(defer(configure_help))]
pub(crate) struct QueueCommand {
/// Session UUID or exact session name.
#[arg(long, value_name = "THREAD")]
thread: String,
/// Message text to queue.
#[arg(long, value_name = "TEXT", value_parser = NonEmptyStringValueParser::new())]
message: String,
/// After queueing, try to resume the thread on the local daemon or selected --remote server.
/// A failed resume produces a warning and the command still succeeds.
#[arg(long)]
resume: bool,
#[clap(flatten)]
remote: InteractiveRemoteOptions,
#[clap(flatten)]
pub(crate) config_overrides: SessionArchiveConfigOverrides,
}
/// Only inherited options need restrictions; queue owns its other arguments.
fn restricted_options(command: &Command) -> impl Iterator<Item = &Arg> {
command.get_arguments().filter(|arg| {
!matches!(
arg.get_long(),
Some(
"remote"
| "remote-auth-token-env"
| "config"
| "enable"
| "disable"
| "profile"
| "strict-config"
)
)
})
}
fn configure_help(command: Command) -> Command {
let interactive = TuiCli::command();
command.mut_args(|arg| {
if arg.get_long() == Some("config") {
arg.long_help(None).help("Override a startup configuration value (key=value). Queued messages use the thread's model.")
} else if !restricted_options(&interactive).any(|shared| shared.get_id() == arg.get_id()) {
arg
} else if arg.get_long() == Some("cd") {
arg.help_heading("Local server options (without --remote)")
} else {
arg.hide(true)
}
})
}
/// Check both scopes before root flags such as `--approve-for-me` become config overrides.
pub(super) fn validate_options(command: &Command, root: &ArgMatches) -> Result<(), clap::Error> {
let Some(queue) = root.subcommand_matches("queue") else {
return Ok(());
};
let remote = root
.get_one::<String>("remote")
.or_else(|| queue.get_one::<String>("remote"));
let supplied = [root, queue].into_iter().flat_map(|scope| {
scope
.ids()
.filter(|id| scope.value_source(id.as_str()) == Some(ValueSource::CommandLine))
});
for id in supplied {
let Some(arg) = restricted_options(command).find(|arg| arg.get_id() == id) else {
continue;
};
let message = match arg.get_long() {
Some("cd") if remote.is_none() => continue,
Some("cd") => "`codex queue` does not support `--cd` with `--remote`".to_string(),
// These flags already have dedicated diagnostics in the CLI and session startup.
Some("worktree" | "no-daemon") => continue,
Some("model") => {
"`codex queue` does not support `--model`; queued messages use the thread's model"
.to_string()
}
Some("image") => "`codex queue` does not support image attachments".to_string(),
Some(name) => format!("`codex queue` does not support `--{name}`"),
None => {
"`codex queue` does not accept a positional prompt; use `--message`".to_string()
}
};
return Err(clap::Error::raw(ErrorKind::ArgumentConflict, message));
}
Ok(())
}
pub(crate) async fn run_queue_command(
command: QueueCommand,
interactive: TuiCli,
root_config_overrides: CliConfigOverrides,
root_remote: Option<String>,
root_remote_auth_token_env: Option<String>,
arg0_paths: Arg0DispatchPaths,
) -> anyhow::Result<String> {
let QueueCommand {
thread,
message,
resume,
remote,
config_overrides,
} = command;
let cli =
finalize_session_archive_interactive(interactive, root_config_overrides, config_overrides);
if cli.config_overrides.raw_overrides.iter().any(|entry| {
entry
.split_once('=')
.is_some_and(|(key, _)| key.trim() == "model")
}) {
anyhow::bail!(
"`codex queue` does not support a `model` config override; queued messages use the thread's model"
);
}
let explicit_remote_endpoint = resolve_remote_endpoint(
remote.remote.or(root_remote),
remote.remote_auth_token_env.or(root_remote_auth_token_env),
)?;
codex_tui::run_session_queue_command(
thread,
message,
resume,
codex_tui::SessionArchiveCommandOptions {
cli,
arg0_paths,
explicit_remote_endpoint,
},
)
.await
.map_err(|error| anyhow::anyhow!("{error:#}"))
}

View File

@@ -0,0 +1,859 @@
use std::io::Write;
use std::time::Duration;
use anyhow::Context;
use clap::Args;
use codex_app_server::AppServerRuntimeOptions;
use codex_app_server::AppServerTransport;
use codex_app_server_daemon::LifecycleCommand as AppServerLifecycleCommand;
use codex_app_server_daemon::LifecycleOutput as AppServerLifecycleOutput;
use codex_app_server_daemon::LifecycleStatus as AppServerLifecycleStatus;
use codex_app_server_daemon::RemoteControlReadyOutput as AppServerRemoteControlReadyOutput;
use codex_app_server_daemon::RemoteControlReadyStatus as AppServerRemoteControlReadyStatus;
use codex_app_server_daemon::RemoteControlStartOutput as AppServerRemoteControlStartOutput;
use codex_app_server_protocol::RemoteControlConnectionStatus;
use codex_app_server_protocol::RemoteControlPairingStartResponse;
use codex_arg0::Arg0DispatchPaths;
use codex_config::LoaderOverrides;
use codex_core::config::ConfigBuilder;
use codex_features::Feature;
use codex_protocol::protocol::SessionSource;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_cli::CliConfigOverrides;
use codex_websocket_auth::WebsocketAuthSettings;
use serde::Serialize;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use tokio::time::timeout;
const FOREGROUND_SOCKET_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const FOREGROUND_SOCKET_CONNECT_RETRY_DELAY: Duration = Duration::from_millis(50);
const FOREGROUND_APP_SERVER_ABORT_TIMEOUT: Duration = Duration::from_secs(1);
#[derive(Debug, Args)]
pub(crate) struct RemoteControlCommand {
/// Emit machine-readable JSON.
#[arg(long = "json", global = true)]
json: bool,
/// Run an embedded app-server in the foreground until Ctrl-C.
#[arg(long = "no-daemon")]
pub(super) no_daemon: bool,
#[command(subcommand)]
pub(super) subcommand: Option<RemoteControlSubcommand>,
}
impl RemoteControlCommand {
pub(crate) fn subcommand_name(&self) -> &'static str {
match self.subcommand {
None => "remote-control",
Some(RemoteControlSubcommand::Start) => "remote-control start",
Some(RemoteControlSubcommand::Stop) => "remote-control stop",
Some(RemoteControlSubcommand::Pair) => "remote-control pair",
}
}
}
#[derive(Debug, Clone, Copy, clap::Subcommand)]
pub(super) enum RemoteControlSubcommand {
/// Start the app-server daemon with remote control enabled.
Start,
/// Stop the app-server daemon.
Stop,
/// Create and print a short-lived manual pairing code.
Pair,
}
pub(crate) async fn run(
command: RemoteControlCommand,
arg0_paths: Arg0DispatchPaths,
root_config_overrides: CliConfigOverrides,
) -> anyhow::Result<()> {
if command.no_daemon && command.subcommand.is_some() {
anyhow::bail!("`--no-daemon` cannot be used with a remote-control subcommand");
}
if command.subcommand.is_none() {
if command.no_daemon || command.json || !daemon_eligible(&root_config_overrides).await? {
run_foreground_remote_control(command.json, arg0_paths, root_config_overrides).await?;
} else {
print_remote_control_progress(
command.json,
"Starting app-server daemon with remote control enabled...",
)?;
let daemon = match codex_app_server_daemon::start_with_features(&Default::default())
.await
{
Ok(daemon) => daemon,
#[cfg(windows)]
Err(error) if error.is::<codex_app_server_daemon::DetachedLaunchRestricted>() => {
return run_foreground_remote_control(
command.json,
arg0_paths,
root_config_overrides,
)
.await;
}
Err(error) => return Err(error),
};
if daemon.backend.is_none() {
return run_foreground_remote_control(
command.json,
arg0_paths,
root_config_overrides,
)
.await;
}
let remote_control = codex_app_server_daemon::enable_remote_control_on_socket(
&daemon.socket_path,
FOREGROUND_SOCKET_CONNECT_TIMEOUT,
FOREGROUND_SOCKET_CONNECT_RETRY_DELAY,
)
.await?;
let output = AppServerRemoteControlReadyOutput {
daemon: AppServerRemoteControlStartOutput::Start(daemon),
remote_control,
};
print_remote_control_start_output(&output, command.json)?;
}
return Ok(());
}
match command.subcommand {
Some(RemoteControlSubcommand::Start) => {
print_remote_control_progress(
command.json,
"Starting app-server daemon with remote control enabled...",
)?;
let output = codex_app_server_daemon::ensure_remote_control_ready().await?;
print_remote_control_start_output(&output, command.json)?;
}
Some(RemoteControlSubcommand::Stop) => {
print_remote_control_progress(command.json, "Stopping remote control...")?;
let output = codex_app_server_daemon::run(AppServerLifecycleCommand::Stop).await?;
print_remote_control_stop_output(&output, command.json)?;
}
Some(RemoteControlSubcommand::Pair) => {
let output = codex_app_server_daemon::start_remote_control_pairing().await?;
print_remote_control_pairing_output(&output, command.json)?;
}
None => unreachable!("bare remote-control returned before explicit subcommand dispatch"),
}
Ok(())
}
async fn daemon_eligible(root_config_overrides: &CliConfigOverrides) -> anyhow::Result<bool> {
if !root_config_overrides.raw_overrides.is_empty()
|| codex_login::is_workload_identity_selected()
|| std::env::var_os(codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR).is_some()
{
return Ok(false);
}
#[cfg(windows)]
if codex_app_server_daemon::is_elevated()? {
return Ok(false);
}
let Ok(config) = ConfigBuilder::default().build().await else {
return Ok(false);
};
Ok(config.features.enabled(Feature::DaemonAutoStart)
&& !codex_tui::uses_wsl_drvfs(&config.codex_home))
}
fn print_remote_control_progress(json: bool, message: &str) -> anyhow::Result<()> {
if json {
return Ok(());
}
println!("{message}");
std::io::stdout()
.flush()
.context("failed to flush remote-control progress message")?;
Ok(())
}
async fn run_foreground_remote_control(
json: bool,
arg0_paths: Arg0DispatchPaths,
root_config_overrides: CliConfigOverrides,
) -> anyhow::Result<()> {
print_remote_control_progress(json, "Starting app-server with remote control enabled...")?;
#[cfg(not(windows))]
let socket_dir = tempfile::Builder::new()
.prefix("codex-rc-")
.tempdir_in("/tmp")
.or_else(|_| tempfile::tempdir())
.context("failed to create private app-server socket directory")?;
#[cfg(not(windows))]
let socket_path = socket_dir.path().join("rc.sock");
// Let the transport create this parent with a protected DACL instead of
// inheriting the broader ACL from a directory created under `%TEMP%`.
#[cfg(windows)]
let socket_path = std::env::temp_dir()
.join("codex-remote-control")
.join(format!("rc-{}.sock", std::process::id()));
let socket_path = AbsolutePathBuf::from_absolute_path(&socket_path)
.context("private app-server socket path was not absolute")?;
let transport = AppServerTransport::UnixSocket {
socket_path: socket_path.clone(),
};
let runtime_options = AppServerRuntimeOptions {
remote_control_startup_mode: codex_app_server::RemoteControlStartupMode::EnabledEphemeral,
install_shutdown_signal_handler: false,
..Default::default()
};
let (stop_rx, stop_signal_task) = foreground_stop_signal();
let app_server = codex_app_server::run_main_with_transport_options(
arg0_paths,
root_config_overrides,
LoaderOverrides::default(),
/*strict_config*/ false,
/*default_analytics_enabled*/ false,
transport,
SessionSource::VSCode,
WebsocketAuthSettings::default(),
runtime_options,
);
let mut app_server_task = tokio::spawn(async move { app_server.await.map(|_| ()) });
let summary = match wait_for_foreground_remote_control_start(
&mut app_server_task,
wait_for_foreground_remote_control_ready(socket_path),
stop_rx.clone(),
)
.await
{
ForegroundStartupResult::Ready(summary) => summary,
ForegroundStartupResult::Stopped => {
abort_foreground_app_server(app_server_task).await;
stop_signal_task.abort();
return Ok(());
}
ForegroundStartupResult::ReadyFailed(error) => {
abort_foreground_app_server(app_server_task).await;
stop_signal_task.abort();
return Err(error);
}
ForegroundStartupResult::AppServerExited(error) => {
stop_signal_task.abort();
return Err(error);
}
};
if *stop_rx.borrow() {
abort_foreground_app_server(app_server_task).await;
stop_signal_task.abort();
return Ok(());
}
if let Err(error) = print_foreground_ready_output(&summary, json) {
abort_foreground_app_server(app_server_task).await;
stop_signal_task.abort();
return Err(error);
}
let result = wait_for_foreground_app_server(app_server_task, stop_rx).await;
stop_signal_task.abort();
result
}
fn foreground_stop_signal() -> (watch::Receiver<bool>, JoinHandle<()>) {
let (stop_tx, stop_rx) = watch::channel(false);
let task = tokio::spawn(async move {
if let Err(err) = tokio::signal::ctrl_c().await {
eprintln!("failed to listen for Ctrl-C: {err}");
}
let _ = stop_tx.send(true);
});
(stop_rx, task)
}
enum ForegroundStartupResult {
Ready(AppServerRemoteControlReadyStatus),
Stopped,
ReadyFailed(anyhow::Error),
AppServerExited(anyhow::Error),
}
async fn wait_for_foreground_remote_control_start(
app_server_task: &mut JoinHandle<std::io::Result<()>>,
ready: impl std::future::Future<Output = anyhow::Result<AppServerRemoteControlReadyStatus>>,
mut stop_rx: watch::Receiver<bool>,
) -> ForegroundStartupResult {
tokio::pin!(ready);
tokio::select! {
ready_result = &mut ready => match ready_result {
Ok(summary) => ForegroundStartupResult::Ready(summary),
Err(error) => ForegroundStartupResult::ReadyFailed(error),
},
app_server_result = app_server_task => {
ForegroundStartupResult::AppServerExited(
foreground_app_server_exited_before_ready(app_server_result)
)
}
_ = wait_for_stop_signal(&mut stop_rx) => ForegroundStartupResult::Stopped,
}
}
async fn wait_for_foreground_app_server(
mut app_server_task: JoinHandle<std::io::Result<()>>,
mut stop_rx: watch::Receiver<bool>,
) -> anyhow::Result<()> {
tokio::select! {
app_server_result = &mut app_server_task => {
app_server_result
.context("foreground app-server task failed to join")?
.context("foreground app-server exited with an error")?;
}
_ = wait_for_stop_signal(&mut stop_rx) => {
abort_foreground_app_server(app_server_task).await;
}
}
Ok(())
}
async fn wait_for_stop_signal(stop_rx: &mut watch::Receiver<bool>) {
if *stop_rx.borrow() {
return;
}
let _ = stop_rx.wait_for(|stopped| *stopped).await;
}
fn foreground_app_server_exited_before_ready(
result: Result<std::io::Result<()>, tokio::task::JoinError>,
) -> anyhow::Error {
match result {
Ok(Ok(())) => {
anyhow::anyhow!("foreground app-server exited before remote control became ready")
}
Ok(Err(error)) => anyhow::Error::new(error)
.context("foreground app-server exited before remote control became ready"),
Err(error) => anyhow::Error::new(error)
.context("foreground app-server task failed before remote control became ready"),
}
}
async fn abort_foreground_app_server(app_server_task: JoinHandle<std::io::Result<()>>) {
app_server_task.abort();
let _ = timeout(FOREGROUND_APP_SERVER_ABORT_TIMEOUT, app_server_task).await;
}
async fn wait_for_foreground_remote_control_ready(
socket_path: AbsolutePathBuf,
) -> anyhow::Result<AppServerRemoteControlReadyStatus> {
codex_app_server_daemon::enable_remote_control_on_socket(
socket_path.as_path(),
FOREGROUND_SOCKET_CONNECT_TIMEOUT,
FOREGROUND_SOCKET_CONNECT_RETRY_DELAY,
)
.await
}
fn print_remote_control_start_output(
output: &AppServerRemoteControlReadyOutput,
json: bool,
) -> anyhow::Result<()> {
ensure_remote_control_startable(&output.remote_control)?;
if json {
println!(
"{}",
serde_json::to_string(&RemoteControlStartJsonOutput::daemon(output))?
);
return Ok(());
}
for line in remote_control_start_human_lines(
&output.remote_control,
RemoteControlHumanOutputMode::Daemon,
)? {
println!("{line}");
}
for line in daemon_app_server_human_lines(&output.daemon) {
println!("{line}");
}
Ok(())
}
fn print_foreground_ready_output(
summary: &AppServerRemoteControlReadyStatus,
json: bool,
) -> anyhow::Result<()> {
if json {
ensure_remote_control_startable(summary)?;
println!(
"{}",
serde_json::to_string(&RemoteControlStartJsonOutput::foreground(summary))?
);
return Ok(());
}
for line in remote_control_start_human_lines(summary, RemoteControlHumanOutputMode::Foreground)?
{
println!("{line}");
}
Ok(())
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct RemoteControlStartJsonOutput<'a> {
mode: RemoteControlModeJson,
status: RemoteControlConnectionStatus,
server_name: &'a str,
environment_id: Option<&'a str>,
timed_out: bool,
#[serde(skip_serializing_if = "Option::is_none")]
daemon: Option<&'a AppServerRemoteControlStartOutput>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
enum RemoteControlModeJson {
Foreground,
Daemon,
}
impl<'a> RemoteControlStartJsonOutput<'a> {
fn foreground(summary: &'a AppServerRemoteControlReadyStatus) -> Self {
Self {
mode: RemoteControlModeJson::Foreground,
status: summary.status,
server_name: &summary.server_name,
environment_id: summary.environment_id.as_deref(),
timed_out: summary.timed_out,
daemon: None,
}
}
fn daemon(output: &'a AppServerRemoteControlReadyOutput) -> Self {
let remote_control = &output.remote_control;
Self {
mode: RemoteControlModeJson::Daemon,
status: remote_control.status,
server_name: &remote_control.server_name,
environment_id: remote_control.environment_id.as_deref(),
timed_out: remote_control.timed_out,
daemon: Some(&output.daemon),
}
}
}
fn remote_control_start_human_message(
output: &AppServerRemoteControlReadyStatus,
) -> anyhow::Result<String> {
ensure_remote_control_startable(output)?;
match output.status {
RemoteControlConnectionStatus::Connected => Ok(format!(
"This machine is available for remote control as {}.",
output.server_name
)),
RemoteControlConnectionStatus::Connecting => Ok(format!(
"Remote control is enabled on {} and still connecting.",
output.server_name
)),
RemoteControlConnectionStatus::Errored | RemoteControlConnectionStatus::Disabled => {
unreachable!("errored and disabled statuses are rejected before formatting")
}
}
}
fn ensure_remote_control_startable(
output: &AppServerRemoteControlReadyStatus,
) -> anyhow::Result<()> {
match output.status {
RemoteControlConnectionStatus::Connected | RemoteControlConnectionStatus::Connecting => {
Ok(())
}
RemoteControlConnectionStatus::Errored => {
anyhow::bail!(
"Remote control is enabled on {} but the connection is errored.",
output.server_name
);
}
RemoteControlConnectionStatus::Disabled => {
anyhow::bail!("Remote control is disabled on {}.", output.server_name);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RemoteControlHumanOutputMode {
Foreground,
Daemon,
}
fn remote_control_start_human_lines(
summary: &AppServerRemoteControlReadyStatus,
mode: RemoteControlHumanOutputMode,
) -> anyhow::Result<Vec<String>> {
let mut lines = vec![remote_control_start_human_message(summary)?];
match mode {
RemoteControlHumanOutputMode::Foreground => {
lines.push("Press Ctrl-C to stop.".to_string());
}
RemoteControlHumanOutputMode::Daemon => {}
}
Ok(lines)
}
fn daemon_app_server_human_lines(output: &AppServerRemoteControlStartOutput) -> Vec<String> {
let (managed_codex_path, managed_codex_version) = daemon_app_server_identity(output);
vec![
"Daemon used app-server:".to_string(),
format!(" path: {}", managed_codex_path.display()),
format!(" version: {}", managed_codex_version.unwrap_or("unknown")),
]
}
fn daemon_app_server_identity(
output: &AppServerRemoteControlStartOutput,
) -> (&std::path::Path, Option<&str>) {
match output {
AppServerRemoteControlStartOutput::Bootstrap(output) => (
&output.managed_codex_path,
output.managed_codex_version.as_deref(),
),
AppServerRemoteControlStartOutput::Start(output) => (
&output.managed_codex_path,
output.managed_codex_version.as_deref(),
),
}
}
fn print_remote_control_stop_output(
output: &AppServerLifecycleOutput,
json: bool,
) -> anyhow::Result<()> {
if json {
println!("{}", serde_json::to_string(output)?);
return Ok(());
}
println!("{}", remote_control_stop_human_message(output));
Ok(())
}
fn print_remote_control_pairing_output(
output: &RemoteControlPairingStartResponse,
json: bool,
) -> anyhow::Result<()> {
println!("{}", format_remote_control_pairing_output(output, json)?);
Ok(())
}
fn format_remote_control_pairing_output(
output: &RemoteControlPairingStartResponse,
json: bool,
) -> anyhow::Result<String> {
if json {
return Ok(serde_json::to_string(output)?);
}
let manual_pairing_code = output
.manual_pairing_code
.as_deref()
.context("remote-control pairing response did not include a manual pairing code")?;
Ok(format!("Pairing code: {manual_pairing_code}"))
}
fn remote_control_stop_human_message(output: &AppServerLifecycleOutput) -> String {
match output.status {
AppServerLifecycleStatus::Stopped => "Remote control stopped.".to_string(),
AppServerLifecycleStatus::NotRunning => "Remote control is not running.".to_string(),
AppServerLifecycleStatus::Started
| AppServerLifecycleStatus::Restarted
| AppServerLifecycleStatus::AlreadyRunning
| AppServerLifecycleStatus::Running => {
format!(
"Remote control stop completed with status {:?}.",
output.status
)
}
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::PathBuf;
use super::*;
fn remote_control_status(
status: RemoteControlConnectionStatus,
) -> AppServerRemoteControlReadyStatus {
AppServerRemoteControlReadyStatus {
status,
server_name: "owen-mbp".to_string(),
environment_id: Some("env_test".to_string()),
timed_out: status == RemoteControlConnectionStatus::Connecting,
}
}
fn daemon_ready_output(
status: RemoteControlConnectionStatus,
) -> AppServerRemoteControlReadyOutput {
AppServerRemoteControlReadyOutput {
daemon: AppServerRemoteControlStartOutput::Start(AppServerLifecycleOutput {
status: AppServerLifecycleStatus::Started,
backend: None,
pid: Some(42),
managed_codex_path: PathBuf::from("/opt/codex/bin/codex"),
managed_codex_version: Some("1.0.0".to_string()),
socket_path: PathBuf::from("/tmp/app-server-control.sock"),
cli_version: Some("1.0.0".to_string()),
app_server_version: Some("2.0.0".to_string()),
}),
remote_control: AppServerRemoteControlReadyStatus {
status,
server_name: "owen-mbp".to_string(),
environment_id: Some("env_test".to_string()),
timed_out: status == RemoteControlConnectionStatus::Connecting,
},
}
}
fn pairing_response(manual_pairing_code: Option<&str>) -> RemoteControlPairingStartResponse {
RemoteControlPairingStartResponse {
pairing_code: "pairing-code".to_string(),
manual_pairing_code: manual_pairing_code.map(str::to_string),
environment_id: "env_test".to_string(),
expires_at: 1_700_000_000,
}
}
#[test]
fn remote_control_human_start_messages_use_server_name() {
assert_eq!(
remote_control_start_human_message(&remote_control_status(
RemoteControlConnectionStatus::Connected
))
.expect("connected message"),
"This machine is available for remote control as owen-mbp."
);
assert_eq!(
remote_control_start_human_message(&remote_control_status(
RemoteControlConnectionStatus::Connecting
))
.expect("connecting message"),
"Remote control is enabled on owen-mbp and still connecting."
);
assert_eq!(
remote_control_start_human_message(&remote_control_status(
RemoteControlConnectionStatus::Errored
))
.expect_err("errored status should fail")
.to_string(),
"Remote control is enabled on owen-mbp but the connection is errored."
);
assert_eq!(
remote_control_start_human_message(&remote_control_status(
RemoteControlConnectionStatus::Disabled
))
.expect_err("disabled status should fail")
.to_string(),
"Remote control is disabled on owen-mbp."
);
}
#[test]
fn remote_control_human_lines_include_foreground_stop_hint_only() {
let summary = remote_control_status(RemoteControlConnectionStatus::Connected);
assert_eq!(
remote_control_start_human_lines(&summary, RemoteControlHumanOutputMode::Foreground)
.expect("foreground lines"),
vec![
"This machine is available for remote control as owen-mbp.".to_string(),
"Press Ctrl-C to stop.".to_string(),
]
);
assert_eq!(
remote_control_start_human_lines(&summary, RemoteControlHumanOutputMode::Daemon)
.expect("daemon lines"),
vec!["This machine is available for remote control as owen-mbp.".to_string()]
);
}
#[test]
fn daemon_app_server_human_lines_include_path_and_version() {
assert_eq!(
daemon_app_server_human_lines(
&daemon_ready_output(RemoteControlConnectionStatus::Connected).daemon
),
vec![
"Daemon used app-server:".to_string(),
" path: /opt/codex/bin/codex".to_string(),
" version: 1.0.0".to_string(),
]
);
}
#[test]
fn remote_control_json_output_marks_foreground_or_daemon() {
let foreground_summary = remote_control_status(RemoteControlConnectionStatus::Connected);
assert_eq!(
serde_json::to_value(RemoteControlStartJsonOutput::foreground(
&foreground_summary
))
.expect("foreground JSON"),
json!({
"mode": "foreground",
"status": "connected",
"serverName": "owen-mbp",
"environmentId": "env_test",
"timedOut": false,
})
);
let daemon_output = daemon_ready_output(RemoteControlConnectionStatus::Connected);
assert_eq!(
serde_json::to_value(RemoteControlStartJsonOutput::daemon(&daemon_output))
.expect("daemon JSON"),
json!({
"mode": "daemon",
"status": "connected",
"serverName": "owen-mbp",
"environmentId": "env_test",
"timedOut": false,
"daemon": {
"status": "started",
"pid": 42,
"managedCodexPath": "/opt/codex/bin/codex",
"managedCodexVersion": "1.0.0",
"socketPath": "/tmp/app-server-control.sock",
"cliVersion": "1.0.0",
"appServerVersion": "2.0.0",
},
})
);
}
#[test]
fn remote_control_daemon_json_rejects_unstartable_status() {
assert_eq!(
print_remote_control_start_output(
&daemon_ready_output(RemoteControlConnectionStatus::Errored),
/*json*/ true
)
.expect_err("errored daemon status should fail")
.to_string(),
"Remote control is enabled on owen-mbp but the connection is errored."
);
}
#[test]
fn remote_control_pairing_human_output_labels_the_manual_code() {
assert_eq!(
format_remote_control_pairing_output(
&pairing_response(Some("ABCD-EFGH")),
/*json*/ false,
)
.expect("manual pairing output"),
"Pairing code: ABCD-EFGH"
);
}
#[test]
fn remote_control_pairing_json_output_preserves_pairing_artifacts() {
let output = format_remote_control_pairing_output(
&pairing_response(Some("ABCD-EFGH")),
/*json*/ true,
)
.expect("pairing JSON output");
assert_eq!(
serde_json::from_str::<serde_json::Value>(&output).expect("valid JSON"),
json!({
"pairingCode": "pairing-code",
"manualPairingCode": "ABCD-EFGH",
"environmentId": "env_test",
"expiresAt": 1_700_000_000,
})
);
}
#[test]
fn remote_control_pairing_human_output_requires_manual_code() {
assert_eq!(
format_remote_control_pairing_output(
&pairing_response(/*manual_pairing_code*/ None),
/*json*/ false,
)
.expect_err("missing manual pairing code should fail")
.to_string(),
"remote-control pairing response did not include a manual pairing code"
);
}
#[tokio::test]
async fn foreground_wait_aborts_app_server_on_stop_signal() {
let app_server_task = tokio::spawn(std::future::pending::<std::io::Result<()>>());
let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
stop_tx.send(true).expect("send stop signal");
tokio::time::timeout(
std::time::Duration::from_secs(1),
wait_for_foreground_app_server(app_server_task, stop_rx),
)
.await
.expect("foreground wait should return after stop signal")
.expect("stop signal should shut down cleanly");
}
#[tokio::test]
async fn foreground_start_wait_stops_before_ready() {
let mut app_server_task = tokio::spawn(std::future::pending::<std::io::Result<()>>());
let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
stop_tx.send(true).expect("send stop signal");
let startup = tokio::time::timeout(
std::time::Duration::from_secs(1),
wait_for_foreground_remote_control_start(
&mut app_server_task,
std::future::pending::<anyhow::Result<AppServerRemoteControlReadyStatus>>(),
stop_rx,
),
)
.await
.expect("foreground startup wait should return after stop signal");
assert!(matches!(startup, ForegroundStartupResult::Stopped));
app_server_task.abort();
let _ = app_server_task.await;
}
#[tokio::test]
async fn foreground_start_wait_reports_app_server_exit_before_ready() {
let mut app_server_task =
tokio::spawn(async { Err(std::io::Error::other("startup failed before socket bind")) });
let (_stop_tx, stop_rx) = tokio::sync::watch::channel(false);
let startup = tokio::time::timeout(
std::time::Duration::from_secs(1),
wait_for_foreground_remote_control_start(
&mut app_server_task,
std::future::pending::<anyhow::Result<AppServerRemoteControlReadyStatus>>(),
stop_rx,
),
)
.await
.expect("foreground startup wait should return after app-server exits");
let ForegroundStartupResult::AppServerExited(error) = startup else {
panic!("expected app-server exit before ready");
};
assert_eq!(
error.to_string(),
"foreground app-server exited before remote control became ready"
);
}
}

View File

@@ -0,0 +1,230 @@
use std::path::PathBuf;
use anyhow::Context;
use clap::ArgAction;
use clap::ArgGroup;
use clap::Parser;
use codex_core::config::ConfigBuilder;
use codex_core::config::edit::ConfigEditsBuilder;
use codex_core::config::find_codex_home;
use codex_utils_cli::ProfileV2Name;
use toml::Value as TomlValue;
#[derive(Debug, Parser)]
#[command(group(
ArgGroup::new("sandbox_user")
.required(true)
.args(["user", "current_user"])
))]
pub(crate) struct SandboxSetupCommand {
/// Set up the elevated Windows sandbox.
#[arg(long = "elevated", action = ArgAction::SetTrue)]
elevated_sandbox_level: bool,
/// Windows user that will run Codex after managed deployment.
#[arg(
long = "user",
value_name = "USER",
conflicts_with = "current_user",
requires = "codex_home"
)]
user: Option<String>,
/// Use the current Windows user as the Codex user.
#[arg(
long = "current-user",
default_value_t = false,
conflicts_with = "user"
)]
current_user: bool,
/// CODEX_HOME for the Codex user. Required with --user.
#[arg(long = "codex-home", value_name = "DIR")]
codex_home: Option<PathBuf>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SandboxSetupLevel {
Elevated,
}
impl SandboxSetupCommand {
fn setup_level(&self) -> anyhow::Result<SandboxSetupLevel> {
if self.elevated_sandbox_level {
Ok(SandboxSetupLevel::Elevated)
} else {
anyhow::bail!("`codex sandbox setup` currently requires --elevated");
}
}
}
pub(crate) async fn run(
cmd: SandboxSetupCommand,
config_profile: Option<ProfileV2Name>,
cli_overrides: Vec<(String, TomlValue)>,
) -> anyhow::Result<()> {
match cmd.setup_level()? {
SandboxSetupLevel::Elevated => run_elevated(cmd, config_profile, cli_overrides).await,
}
}
pub(crate) fn parse_setup_command(
sandbox_command: &[String],
) -> anyhow::Result<Option<SandboxSetupCommand>> {
if sandbox_command
.first()
.is_none_or(|command| command != "setup")
{
return Ok(None);
}
SandboxSetupCommand::try_parse_from(sandbox_command.iter().map(String::as_str))
.map(Some)
.map_err(anyhow::Error::from)
}
async fn run_elevated(
cmd: SandboxSetupCommand,
config_profile: Option<ProfileV2Name>,
cli_overrides: Vec<(String, TomlValue)>,
) -> anyhow::Result<()> {
let identity = resolve_sandbox_setup_identity(&cmd)?;
let config = ConfigBuilder::default()
.codex_home(identity.codex_home.clone())
.fallback_cwd(Some(identity.codex_home.clone()))
.loader_overrides(super::loader_overrides_for_profile_at_codex_home(
config_profile.as_ref(),
&identity.codex_home,
))
.cli_overrides(cli_overrides)
.build()
.await
.context("failed to load target user's Codex config for sandbox provisioning")?;
codex_core::windows_sandbox::run_elevated_provisioning_setup(
identity.codex_home.as_path(),
identity.real_user.as_str(),
config.permissions.network.as_ref(),
)?;
ConfigEditsBuilder::new(identity.codex_home.as_path())
.set_windows_sandbox_mode("elevated")
.apply()
.await
.map_err(|err| {
anyhow::anyhow!(
"sandbox provisioning succeeded, but failed to persist elevated sandbox config: {err}"
)
})?;
println!(
"Windows elevated sandbox setup completed for {} at {}.",
identity.real_user,
identity.codex_home.display()
);
Ok(())
}
struct SandboxSetupIdentity {
real_user: String,
codex_home: PathBuf,
}
fn resolve_sandbox_setup_identity(
cmd: &SandboxSetupCommand,
) -> anyhow::Result<SandboxSetupIdentity> {
if cmd.current_user {
let real_user = std::env::var("USERNAME")
.or_else(|_| std::env::var("USER"))
.map_err(|err| {
anyhow::anyhow!("failed to determine current user from environment: {err}")
})?;
let codex_home = match cmd.codex_home.clone() {
Some(codex_home) => codex_home,
None => find_codex_home()?.to_path_buf(),
};
return Ok(SandboxSetupIdentity {
real_user,
codex_home,
});
}
let real_user = cmd
.user
.clone()
.ok_or_else(|| anyhow::anyhow!("--user or --current-user is required"))?;
let codex_home = cmd
.codex_home
.clone()
.ok_or_else(|| anyhow::anyhow!("--codex-home is required with --user"))?;
Ok(SandboxSetupIdentity {
real_user,
codex_home,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_managed_user_identity() {
let command = SandboxSetupCommand::try_parse_from([
"setup",
"--elevated",
"--user",
"DOMAIN\\alice",
"--codex-home",
r"C:\Users\alice\.codex",
])
.expect("parse");
assert!(command.elevated_sandbox_level);
assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice"));
assert!(!command.current_user);
assert_eq!(
command.codex_home.as_deref(),
Some(std::path::Path::new(r"C:\Users\alice\.codex"))
);
}
#[test]
fn requires_explicit_user_identity() {
let err = SandboxSetupCommand::try_parse_from(["setup", "--elevated"])
.expect_err("parse should fail");
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
}
#[test]
fn requires_codex_home_for_managed_user() {
let err =
SandboxSetupCommand::try_parse_from(["setup", "--elevated", "--user", "DOMAIN\\alice"])
.expect_err("parse should fail");
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
}
#[test]
fn parses_setup_from_sandbox_command_args() {
let command = parse_setup_command(&[
"setup".to_string(),
"--elevated".to_string(),
"--user".to_string(),
r"DOMAIN\alice".to_string(),
"--codex-home".to_string(),
r"C:\Users\alice\.codex".to_string(),
])
.expect("parse")
.expect("setup command");
assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice"));
}
#[test]
fn ignores_non_setup_sandbox_command_args() {
let command =
parse_setup_command(&["echo".to_string(), "hello".to_string()]).expect("parse");
assert!(command.is_none());
}
}

View File

@@ -0,0 +1,21 @@
//! Uninstalls the legacy Windows sandbox without loading config or removing user data.
use clap::Args;
#[derive(Debug, Args)]
#[command(
about = "Remove the legacy Windows sandbox's machine-wide accounts and network rules",
after_help = "Run as administrator after stopping apps using the legacy sandbox and its provisioning service, if installed.\nPreserves Codex home, including sandbox directories and filesystem permissions."
)]
pub(crate) struct SandboxUninstallCommand {}
impl SandboxUninstallCommand {
pub(crate) fn run(self) -> anyhow::Result<()> {
#[cfg(target_os = "windows")]
{
codex_windows_sandbox::clean_up_legacy_windows_sandbox()
}
#[cfg(not(target_os = "windows"))]
anyhow::bail!("`codex sandbox uninstall` is only supported on Windows")
}
}

View File

@@ -0,0 +1,25 @@
---
source: cli/src/doctor.rs
expression: "render_human_report(&report, HumanOutputOptions\n{ show_details: true, show_all: true, ascii: true, color_enabled: false, })"
---
Codex Doctor v0.0.0
Notes
[!!] terminal TERM=dumb - colors and cursor control are disabled in this non-interactive run
-------------------------------------------------------------
Environment
[!!] terminal TERM=dumb - colors and cursor control are disabled in this non-interactive run
terminal dumb
TERM dumb
stdin is terminal false
stdout is terminal false
stderr is terminal false
terminal size 120x40
color output disabled (TERM=dumb)
-------------------------------------------------------------
0 ok | 1 notes | 1 warn | 0 fail degraded
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,18 @@
---
source: cli/src/doctor.rs
expression: "render_human_report(&DoctorReport\n{\n schema_version: 1, generated_at: \"0s since unix epoch\".to_string(),\n overall_status: check.status, codex_version: \"0.0.0\".to_string(), checks:\n vec![check],\n}, HumanOutputOptions\n{ show_details: false, show_all: false, ascii: true, color_enabled: false, })"
---
Codex Doctor v0.0.0
Notes
[XX] terminal 3 issues - TERMINFO unreadable - terminal capabilities are unknown; TERM=dumb - colors and cursor control are disabled in this non-interactive run
-------------------------------------------------------------
Environment
[XX] terminal 3 issues - TERMINFO unreadable - terminal capabilities are unknown; TERM=dumb - colors and cursor control are disabled in this non-interactive run
-------------------------------------------------------------
0 ok | 1 notes | 0 warn | 1 fail failed
Run codex doctor without --summary for detailed diagnostics.
--all expand truncated lists --json redacted report

View File

@@ -0,0 +1,67 @@
---
source: cli/src/doctor.rs
expression: rendered
---
successful handshake
Codex Doctor v0.0.0
Connectivity
[ok] network network environment is readable
HTTPS proxy not set
[ok] websocket Responses WebSocket handshake succeeded
handshake result HTTP 101
reasoning header true
server model present true
[ok] reachability active provider endpoints are reachable over HTTP
OpenAI endpoint HTTP 200
-------------------------------------------------------------
3 ok | 0 warn | 0 fail ok
--summary compact output --all expand truncated lists
--json redacted report
immediate close
Codex Doctor v0.0.0
Notes
[!!] websocket Responses WebSocket closed immediately after handshake - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
-------------------------------------------------------------
Connectivity
[ok] network network environment is readable
HTTPS proxy not set
[!!] websocket Responses WebSocket closed immediately after handshake - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
handshake result HTTP 101
immediate close code 1008
immediate close reason present (redacted)
[ok] reachability active provider endpoints are reachable over HTTP
OpenAI endpoint HTTP 200
-------------------------------------------------------------
2 ok | 1 notes | 1 warn | 0 fail degraded
--summary compact output --all expand truncated lists
--json redacted report
stream failure
Codex Doctor v0.0.0
Notes
[!!] websocket Responses WebSocket failed; HTTPS fallback may still work - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
-------------------------------------------------------------
Connectivity
[ok] network network environment is readable
HTTPS proxy not set
[!!] websocket Responses WebSocket failed; HTTPS fallback may still work - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
endpoint wss://example.com/responses
handshake stream error [redacted]
[ok] reachability active provider endpoints are reachable over HTTP
OpenAI endpoint HTTP 200
-------------------------------------------------------------
2 ok | 1 notes | 1 warn | 0 fail degraded
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,136 @@
---
source: cli/src/exec_server_args_tests.rs
expression: help_text
---
[EXPERIMENTAL] Run the standalone exec-server service
Usage: codex exec-server [OPTIONS] [COMMAND]
Commands:
forward Register an existing WebSocket exec-server as a remote environment
help Print this message or the help of the given subcommand(s)
Options:
-c, --config <key=value>
Override a configuration value that would otherwise be loaded from
`~/.codex/config.toml`. Use a dotted path (`foo.bar.baz`) to override
nested values. The `value` portion is parsed as TOML. If it fails to
parse as TOML, the raw string is used as a literal.
Examples: - `-c model="o3"` - `-c
'sandbox_permissions=["disk-full-read-access"]'` - `-c
shell_environment_policy.inherit=all`
--enable <FEATURE>
Enable a feature (repeatable). Equivalent to `-c features.<name>=true`
--strict-config
Error out when config.toml contains fields that are not recognized by
this version of Codex
--disable <FEATURE>
Disable a feature (repeatable). Equivalent to `-c
features.<name>=false`
--linux-sandbox-pid-namespace <MODE>
Linux PID namespace: isolate (default) or inherit. Inherit allows
signals to other same-UID processes; enable only when provisioning a
dedicated environment
[default: isolate]
--proxy-private-ips-via-upstream
Allow permitted private IP destinations to use the configured upstream
proxy. If no valid upstream proxy applies to the request protocol,
connect directly. Loopback stays local. This flag does not require
upstream routing
[env: CODEX_EXEC_SERVER_PROXY_PRIVATE_IPS_VIA_UPSTREAM]
--concurrent-requests <COUNT>
Maximum number of requests to process concurrently on each connection
[default: 1]
--listen <URL>
Transport endpoint URL. Supported values: `ws://IP:PORT` (default),
`stdio`, `stdio://`
--ws-auth <MODE>
Authentication mode for incoming WebSocket connections
[possible values: capability-token, signed-bearer-token]
--ws-token-file <PATH>
Absolute path to the capability-token file
--ws-token-sha256 <HEX>
Hex-encoded SHA-256 digest of the capability token
--ws-shared-secret-file <PATH>
Absolute path to the shared secret file for signed JWT bearer tokens
--ws-issuer <ISSUER>
Expected issuer for signed JWT bearer tokens
--ws-audience <AUDIENCE>
Expected audience for signed JWT bearer tokens
--ws-max-clock-skew-seconds <SECONDS>
Maximum clock skew when validating signed JWT bearer tokens
--remote <URL>
Register this exec-server as a remote environment using the given base
URL
--remote-transport <REMOTE_TRANSPORT>
Transport used for the remote executor connection
[default: noise]
[possible values: noise, direct]
--environment-id <ID>
Environment id to attach to when registering remotely
--name <NAME>
Human-readable environment name
--use-agent-identity-auth
Use Agent Identity auth from CODEX_ACCESS_TOKEN for remote
registration
--registration-bearer-stdin
Read one registration bearer from stdin
--executor-credential-stdin
Read rotating executor credentials from stdin; exit when the pipe
closes
--chatgpt-token-stdin
Read a ChatGPT access token from stdin for HTTPS registration
--chatgpt-account-id <ID>
ChatGPT account ID. Must match the token's account claim when present
--aws-sigv4
Sign Direct registration and WebSocket handshake requests with AWS
SigV4
--aws-profile <PROFILE>
AWS profile used for SigV4 authentication
--aws-region <REGION>
AWS signing region. Uses the SDK region chain when omitted
--aws-service <SERVICE>
AWS signing service
[default: execute-api]
--exit-on-stdin-close
Exit when the parent-owned standard-input pipe closes
[env: CODEX_EXEC_SERVER_EXIT_ON_STDIN_CLOSE]
-h, --help
Print help (see a summary with '-h')

View File

@@ -0,0 +1,13 @@
---
source: cli/src/main.rs
assertion_line: 3324
expression: "errors.join(\"\\n\")"
---
codex --worktree login: `--worktree` supports new interactive sessions, `codex fork`, `codex exec`, and `codex exec fork`
codex fork --worktree: `codex fork --worktree` requires an explicit session ID
codex fork --worktree --last: `codex fork --worktree` requires an explicit session ID
codex exec resume --worktree session: `--worktree` cannot resume an existing session; use `codex exec fork --worktree`
codex exec review --worktree: `--worktree` is not supported for code review
codex resume --worktree session: `--worktree` supports new interactive sessions, `codex fork`, `codex exec`, and `codex exec fork`
codex archive session --worktree: `--worktree` supports new interactive sessions, `codex fork`, `codex exec`, and `codex exec fork`
codex queue --thread session --message hi --worktree: `--worktree` supports new interactive sessions, `codex fork`, `codex exec`, and `codex exec fork`

View File

@@ -0,0 +1,7 @@
---
source: cli/src/login_storage_tests.rs
assertion_line: 47
expression: "logs.replace(home.path().join(\"secrets\").to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
---
WARN codex_login::auth::storage: failed to save auth to keyring, falling back to file storage: failed to write OAuth tokens to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]
WARN codex_otel::auth_storage: credential storage file fallback completed credential_kind="codex" store_mode="auto" selected_store="secrets" actual_store="file" operation="save" secure_outcome="error" outcome="success" fallback_reason="secure_error" secure_error="other" storage_phase="policy" originator="none"

View File

@@ -0,0 +1,6 @@
---
source: cli/src/login_storage_tests.rs
assertion_line: 58
expression: "message.replace(secrets_path.to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
---
failed to write OAuth tokens to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]

View File

@@ -0,0 +1,156 @@
//! CLI handling for local state database startup failures.
//!
//! This keeps user-facing backup and lock-contention handling out of the main
//! CLI dispatch path while preserving the TUI startup error as the boundary type.
use codex_state::RuntimeDbBackup;
use codex_tui::LocalStateDbStartupError;
use std::io::IsTerminal;
use std::path::Path;
pub(crate) fn startup_error(err: &std::io::Error) -> Option<&LocalStateDbStartupError> {
err.get_ref()
.and_then(|err| err.downcast_ref::<LocalStateDbStartupError>())
}
pub(crate) fn is_locked(detail: &str) -> bool {
codex_state::sqlite_error_detail_is_lock(detail)
}
pub(crate) fn is_auto_backup_recoverable(startup_error: &LocalStateDbStartupError) -> bool {
startup_error.is_corruption() || sqlite_home_is_blocking_file(startup_error)
}
fn sqlite_home_is_blocking_file(startup_error: &LocalStateDbStartupError) -> bool {
startup_error
.database_path()
.parent()
.and_then(|path| std::fs::metadata(path).ok())
.is_some_and(|metadata| metadata.is_file())
}
pub(crate) fn print_auto_backup_start(startup_error: &LocalStateDbStartupError) {
eprintln!("Codex couldn't start because its local database appears to be damaged.");
eprintln!("Moving the damaged local database aside so Codex can rebuild it from saved data.");
print_technical_details(startup_error);
}
pub(crate) async fn backup_files_for_fresh_start(
startup_error: &LocalStateDbStartupError,
) -> std::io::Result<Vec<RuntimeDbBackup>> {
codex_state::backup_runtime_db_for_fresh_start(startup_error.database_path()).await
}
pub(crate) fn confirm_fresh_start_rebuild(
startup_error: &LocalStateDbStartupError,
backups: &[RuntimeDbBackup],
) -> std::io::Result<()> {
eprintln!("Codex rebuilt its local database.");
eprintln!(
"Codex detected a damaged local database, moved it into a backup folder, and will continue startup with a fresh database."
);
eprintln!("Database path: {}", startup_error.database_path().display());
if let Some(backup_folder) = backup_folder(backups) {
eprintln!("Backup folder: {}", backup_folder.display());
} else {
eprintln!("Backup folder: unavailable");
}
if std::io::stdin().is_terminal() && std::io::stderr().is_terminal() {
eprintln!("Press Enter to continue.");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
} else {
eprintln!("Continuing startup with a fresh local database...");
}
Ok(())
}
pub(crate) fn print_diagnostic_guidance(startup_error: &LocalStateDbStartupError) {
eprintln!("Codex couldn't start because its local database appears to be damaged.");
eprintln!("Run `codex doctor` to check your setup and get next-step guidance.");
eprintln!("If this keeps happening, share the technical details below when asking for help.");
print_technical_details(startup_error);
}
pub(crate) fn print_locked_guidance(startup_error: &LocalStateDbStartupError) {
eprintln!("Codex couldn't start because another Codex process is using its local data.");
eprintln!("Quit any other copies of Codex that may still be running, then try again.");
print_technical_details(startup_error);
}
fn print_technical_details(startup_error: &LocalStateDbStartupError) {
eprintln!("Technical details:");
eprintln!(" Location: {}", startup_error.database_path().display());
eprintln!(" Cause: {}", startup_error.detail());
}
fn backup_folder(backups: &[RuntimeDbBackup]) -> Option<&Path> {
backups.first()?.backup_path.parent()
}
#[cfg(test)]
mod tests {
use super::*;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
use tempfile::TempDir;
#[tokio::test]
async fn backup_backs_up_only_failed_database_file() -> std::io::Result<()> {
let temp_dir = TempDir::new()?;
let sqlite = codex_state::SqliteConfig::new_for_testing(temp_dir.path().abs());
let state_path = sqlite.state_db_path();
let failed_db_path = sqlite.logs_db_path();
tokio::fs::write(state_path.as_path(), b"state").await?;
tokio::fs::write(failed_db_path.as_path(), b"logs").await?;
let startup_error =
LocalStateDbStartupError::new(failed_db_path.clone(), anyhow::anyhow!("corrupt"));
let backups = backup_files_for_fresh_start(&startup_error).await?;
assert_eq!(
backups
.iter()
.map(|backup| &backup.original_path)
.collect::<Vec<_>>(),
vec![&failed_db_path]
);
assert!(!tokio::fs::try_exists(failed_db_path.as_path()).await?);
assert!(tokio::fs::try_exists(state_path.as_path()).await?);
assert!(tokio::fs::try_exists(backups[0].backup_path.as_path()).await?);
Ok(())
}
#[tokio::test]
async fn backup_replaces_blocking_sqlite_home_file() -> std::io::Result<()> {
let temp_dir = TempDir::new()?;
let sqlite_home = temp_dir.path().join("sqlite-home");
tokio::fs::write(sqlite_home.as_path(), b"not-a-directory").await?;
let sqlite = codex_state::SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let startup_error =
LocalStateDbStartupError::new(sqlite.state_db_path(), anyhow::anyhow!("File exists"));
assert!(is_auto_backup_recoverable(&startup_error));
let backups = backup_files_for_fresh_start(&startup_error).await?;
assert_eq!(backups.len(), 1);
assert!(tokio::fs::metadata(sqlite_home.as_path()).await?.is_dir());
assert!(tokio::fs::try_exists(backups[0].backup_path.as_path()).await?);
Ok(())
}
#[test]
fn backup_folder_uses_parent_of_first_backup_path() {
let backups = vec![RuntimeDbBackup {
original_path: PathBuf::from("/tmp/state_5.sqlite"),
backup_path: PathBuf::from("/tmp/db-backups/sqlite-1-0/state_5.sqlite"),
}];
assert_eq!(
backup_folder(&backups),
Some(Path::new("/tmp/db-backups/sqlite-1-0"))
);
}
}

View File

@@ -0,0 +1,59 @@
use std::ffi::OsStr;
/// Returns true if the current process is running under WSL.
pub use codex_utils_path::is_wsl;
/// Convert a Windows absolute path (`C:\foo\bar` or `C:/foo/bar`) to a WSL mount path (`/mnt/c/foo/bar`).
/// Returns `None` if the input does not look like a Windows drive path.
pub fn win_path_to_wsl(path: &str) -> Option<String> {
let bytes = path.as_bytes();
if bytes.len() < 3
|| bytes[1] != b':'
|| !(bytes[2] == b'\\' || bytes[2] == b'/')
|| !bytes[0].is_ascii_alphabetic()
{
return None;
}
let drive = (bytes[0] as char).to_ascii_lowercase();
let tail = path[3..].replace('\\', "/");
if tail.is_empty() {
return Some(format!("/mnt/{drive}"));
}
Some(format!("/mnt/{drive}/{tail}"))
}
/// If under WSL and given a Windows-style path, return the equivalent `/mnt/<drive>/…` path.
/// Otherwise returns the input unchanged.
pub fn normalize_for_wsl<P: AsRef<OsStr>>(path: P) -> String {
let value = path.as_ref().to_string_lossy().to_string();
if !is_wsl() {
return value;
}
if let Some(mapped) = win_path_to_wsl(&value) {
return mapped;
}
value
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn win_to_wsl_basic() {
assert_eq!(
win_path_to_wsl(r"C:\Temp\codex.zip").as_deref(),
Some("/mnt/c/Temp/codex.zip")
);
assert_eq!(
win_path_to_wsl("D:/Work/codex.tgz").as_deref(),
Some("/mnt/d/Work/codex.tgz")
);
assert!(win_path_to_wsl("/home/user/codex").is_none());
}
#[test]
fn normalize_is_noop_on_unix_paths() {
assert_eq!(normalize_for_wsl("/home/u/x"), "/home/u/x");
}
}

View File

@@ -0,0 +1,361 @@
use std::path::Path;
use anyhow::Result;
use app_test_support::app_server_json_shutdown_event;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
cmd.env("CODEX_HOME", codex_home)
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT");
Ok(cmd)
}
#[test]
fn strict_config_rejects_unknown_config_fields_for_app_server() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
r#"
foo = "bar"
"#,
)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["app-server", "--strict-config", "--listen", "off"])
.assert()
.failure()
.stderr(contains("unknown configuration field"));
Ok(())
}
#[test]
fn app_server_preserves_config_overrides_across_subcommand() -> Result<()> {
let home = TempDir::new()?;
codex_command(home.path())?
.args([
"-c",
"missing-equals",
"app-server",
"--print-startup-config",
"-c",
"model=example",
])
.assert()
.failure()
.stdout(contains("Invalid override (missing '='): missing-equals"));
Ok(())
}
#[test]
fn agents_accept_interactive_configuration_overrides() -> Result<()> {
let codex_home = TempDir::new()?;
for args in [
["-c", "features.multi_agent_mode=true", "agents"].as_slice(),
["--enable", "multi_agent_mode", "agents"].as_slice(),
["--yolo", "agents"].as_slice(),
["--no-daemon", "agents"].as_slice(),
["agents", "--no-daemon"].as_slice(),
["--search", "agents"].as_slice(),
["--model", "gpt-5", "agents"].as_slice(),
["--approve-for-me", "agents"].as_slice(),
["--cd", ".", "agents"].as_slice(),
] {
let mut cmd = codex_command(codex_home.path())?;
cmd.env("TERM", "xterm-256color").args(args);
cmd.assert()
.failure()
.stderr(contains("stdin is not a terminal"));
}
Ok(())
}
#[test]
fn agents_reject_inputs_that_cannot_be_applied() -> Result<()> {
let codex_home = TempDir::new()?;
for (args, expected_error) in [
(
["--image=image.png", "agents"].as_slice(),
"does not accept an initial prompt or images",
),
(
["--oss", "agents", "--remote", "ws://127.0.0.1:4512"].as_slice(),
"cannot apply local provider or additional-directory overrides",
),
(
[
"--add-dir",
".",
"agents",
"--remote",
"ws://127.0.0.1:4512",
]
.as_slice(),
"cannot apply local provider or additional-directory overrides",
),
(
[
"-c",
"sandbox_workspace_write.writable_roots=[\"../shared\"]",
"agents",
"--remote",
"ws://127.0.0.1:4512",
]
.as_slice(),
"cannot apply local provider or additional-directory overrides",
),
] {
let mut cmd = codex_command(codex_home.path())?;
cmd.args(args)
.assert()
.failure()
.stderr(contains(expected_error));
}
Ok(())
}
#[test]
fn app_server_emits_json_info_events() -> Result<()> {
let codex_home = TempDir::new()?;
let event = app_server_json_shutdown_event("codex", &["app-server"], codex_home.path())?;
assert_eq!(
event,
json!({
"level": "INFO",
"fields": {
"message": "processor task exited",
"exit_reason": "stdio_connection_closed",
"remaining_connection_count": 0,
"shutdown_forced": false,
},
"target": "codex_app_server",
})
);
Ok(())
}
#[test]
fn app_server_keeps_sqlite_logs_in_overridden_sqlite_home() -> Result<()> {
let home = TempDir::new()?;
let sqlite_home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"[features]\nplugins = false\n",
)?;
codex_command(home.path())?
.env("CODEX_SQLITE_HOME", sqlite_home.path())
.env(
"CODEX_APP_SERVER_MANAGED_CONFIG_PATH",
home.path().join("managed_config.toml"),
)
.arg("app-server")
.write_stdin("")
.assert()
.success();
assert!(sqlite_home.path().join("state_5.sqlite").is_file());
assert!(std::fs::metadata(sqlite_home.path().join("logs_2.sqlite"))?.len() > 0);
assert!(!home.path().join("logs_2.sqlite").exists());
assert!(!home.path().join("log/logs_2.sqlite").exists());
Ok(())
}
#[cfg(unix)]
#[test]
fn app_server_preserves_the_existing_sqlite_logs_symlink() -> Result<()> {
let home = TempDir::new()?;
let external_logs = TempDir::new()?;
let target = external_logs.path().join("logs_2.sqlite");
let link = home.path().join("logs_2.sqlite");
std::os::unix::fs::symlink(&target, &link)?;
std::fs::write(
home.path().join("config.toml"),
"[features]\nplugins = false\n",
)?;
codex_command(home.path())?
.env_remove("CODEX_SQLITE_HOME")
.env(
"CODEX_APP_SERVER_MANAGED_CONFIG_PATH",
home.path().join("managed_config.toml"),
)
.arg("app-server")
.write_stdin("")
.assert()
.success();
assert_eq!(std::fs::read_link(&link)?, target);
assert!(std::fs::metadata(&target)?.len() > 0);
assert!(home.path().join("state_5.sqlite").is_file());
assert!(!home.path().join("log/logs_2.sqlite").exists());
Ok(())
}
#[test]
fn print_startup_config_preserves_project_login_restrictions() -> Result<()> {
let home = TempDir::new()?;
let project = TempDir::new()?;
let project_key =
serde_json::to_string(&codex_config::loader::project_trust_key(project.path()))?;
std::fs::write(
home.path().join("config.toml"),
format!("[projects.{project_key}]\ntrust_level = \"trusted\"\n"),
)?;
std::fs::create_dir(project.path().join(".git"))?;
std::fs::create_dir(project.path().join(".codex"))?;
for method in ["chatgpt", "api"] {
std::fs::write(
project.path().join(".codex/config.toml"),
format!("forced_login_method = '{method}'\n"),
)?;
for sign_out in [None, Some("--startup-sign-out")] {
let mut command = codex_command(home.path())?;
command
.current_dir(project.path())
.args(["app-server", "--print-startup-config"])
.args(sign_out);
let output = command.assert().success();
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
assert_eq!(
value["configRequirements"]["requirements"]["allowedLoginMethods"],
json!([method])
);
}
}
Ok(())
}
#[test]
fn print_startup_config_rejects_sign_out_with_environment_access_token() -> Result<()> {
let home = TempDir::new()?;
let auth_path = home.path().join("auth.json");
let saved_auth = br#"{"OPENAI_API_KEY":"saved-test-key"}"#;
std::fs::write(&auth_path, saved_auth)?;
for token in ["at-test-token", "header.payload.signature"] {
let output = codex_command(home.path())?
.env("CODEX_ACCESS_TOKEN", token)
.args(["app-server", "--print-startup-config", "--startup-sign-out"])
.assert()
.failure();
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
assert_eq!(
value["error"]["message"],
"Configured external authentication is owned by the app-server host and cannot be changed during startup recovery."
);
assert_eq!(std::fs::read(&auth_path)?, saved_auth);
}
Ok(())
}
#[test]
fn print_startup_config_validates_configuration() -> Result<()> {
let home = TempDir::new()?;
let config_path = home.path().join("config.toml");
for (config, strict_arg, error) in [
("[broken\n", None, Some("failed to load configuration")),
(
"unknown_future_setting = true\n",
Some("--strict-config"),
Some("unknown configuration field"),
),
("unknown_future_setting = true\n", None, None),
] {
std::fs::write(&config_path, config)?;
let output = codex_command(home.path())?
.args(["app-server", "--print-startup-config"])
.args(strict_arg)
.assert();
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
if let Some(error) = error {
output.failure().stdout(contains(error));
assert_eq!(value["error"]["data"]["reason"], "configLoad");
assert_eq!(
Path::new(value["error"]["data"]["filePath"].as_str().unwrap()).canonicalize()?,
config_path.canonicalize()?
);
assert!(value["error"]["data"]["line"].as_u64().is_some());
assert!(value.get("configRequirements").is_none());
} else {
output.success();
assert_eq!(value["appServerVersion"], env!("CARGO_PKG_VERSION"));
assert!(value["configRequirements"].get("requirements").is_some());
assert!(value.get("config").is_none());
}
}
Ok(())
}
#[tokio::test]
async fn print_startup_config_is_independent_of_a_locked_history_database() -> Result<()> {
use sqlx::Executor;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;
let home = TempDir::new()?;
let sqlite = TempDir::new()?;
let binary = codex_utils_cargo_bin::cargo_bin("codex")?;
let mut command = Command::new(&binary);
command
.env("CODEX_HOME", home.path())
.env("CODEX_SQLITE_HOME", sqlite.path())
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT")
.args(["app-server", "--print-startup-config"])
.kill_on_drop(true);
let baseline = timeout(Duration::from_secs(10), command.output()).await??;
assert!(baseline.status.success());
let path = sqlite.path().join("state_5.sqlite");
let sqlite_config = codex_state::SqliteConfig::new_for_testing(
codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(sqlite.path())?,
);
let pool = sqlite_config.open_read_write_pool(&path).await?;
let mut database = pool.acquire().await?;
database
.execute("CREATE TABLE synthetic_history (id INTEGER)")
.await?;
database.execute("PRAGMA journal_mode=DELETE").await?;
let readers = sqlite_config
.open_read_only_pool(&path, Some(Duration::ZERO))
.await?;
let mut reader = readers.acquire().await?;
database.execute("BEGIN EXCLUSIVE").await?;
assert!(
reader
.execute("SELECT * FROM synthetic_history")
.await
.is_err()
);
let before = std::fs::read(&path)?;
let output = timeout(Duration::from_secs(10), command.output()).await??;
assert!(output.status.success());
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&output.stdout)?,
serde_json::from_slice::<serde_json::Value>(&baseline.stdout)?
);
assert_eq!(std::fs::read(&path)?, before);
database.execute("ROLLBACK").await?;
Ok(())
}

View File

@@ -0,0 +1,552 @@
//! Managed daemon lifecycle through the public CLI, using isolated standalone fixtures.
#![cfg(unix)]
#[path = "app_server_daemon/support.rs"]
mod support;
use support::TestDaemon;
use support::signal;
use support::wait_for_exit;
use std::process::Command;
use std::process::Stdio;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use pretty_assertions::assert_eq;
use serde_json::Value;
#[test]
fn managed_daemon_restarts_from_deleted_working_directory() -> Result<()> {
let daemon = TestDaemon::new()?;
let project = daemon.home.path().join("project");
std::fs::create_dir(&project)?;
let started = daemon
.command()
.current_dir(&project)
.args(["app-server", "daemon", "start"])
.output()?;
ensure!(
started.status.success(),
"{}",
String::from_utf8_lossy(&started.stderr)
);
let old_pid = daemon.pid("app-server.pid")?;
let old_updater_pid = daemon.pid("app-server-updater.pid")?;
signal(old_updater_pid, libc::SIGTERM)?;
wait_for_exit(old_updater_pid)?;
// Delete the restart caller's cwd without changing the test process's cwd.
let restarted = Command::new("/bin/sh")
.args([
"-c",
"rmdir \"$1\" && exec \"$2\" app-server daemon restart",
"restart",
])
.arg(&project)
.arg(&daemon.codex)
.current_dir(&project)
.env("CODEX_HOME", daemon.home.path())
.output()?;
ensure!(
restarted.status.success(),
"{}",
String::from_utf8_lossy(&restarted.stderr)
);
let restarted: Value = serde_json::from_slice(&restarted.stdout)?;
assert_eq!(restarted["status"], "restarted");
assert_ne!(daemon.pid("app-server.pid")?, old_pid);
assert_ne!(daemon.pid("app-server-updater.pid")?, old_updater_pid);
assert_eq!(daemon.lifecycle("version")?["status"], "running");
let updater_socket = daemon
.home
.path()
.join("app-server-daemon/app-server-updater.sock");
let deadline = Instant::now() + Duration::from_secs(30);
while std::os::unix::net::UnixStream::connect(&updater_socket).is_err() {
ensure!(
Instant::now() < deadline,
"replacement updater did not become ready"
);
std::thread::sleep(Duration::from_millis(50));
}
Ok(())
}
#[test]
fn bootstrap_updater_is_ready_in_deep_codex_home() -> Result<()> {
let mut daemon = TestDaemon::new()?;
let deep_home = tempfile::Builder::new()
.prefix(&"deep-codex-home-".repeat(8))
.tempdir_in("/tmp")?;
for name in ["packages", "app-server-daemon"] {
std::fs::rename(daemon.home.path().join(name), deep_home.path().join(name))?;
}
daemon.home = deep_home;
let state = daemon.home.path().join("app-server-daemon");
std::fs::write(
state.join("settings.json"),
br#"{"shutdownGraceSeconds":0}"#,
)?;
let socket = state.join("app-server-updater.sock");
let result = daemon.lifecycle("bootstrap")?;
assert_eq!(result["autoUpdateEnabled"], true);
assert_eq!(result["status"], "bootstrapped");
signal(daemon.pid("app-server-updater.pid")?, /*signal*/ 0)?;
let target = socket.canonicalize()?;
let _connection = std::os::unix::net::UnixStream::connect(target)?;
assert_eq!(daemon.lifecycle("version")?["status"], "running");
Ok(())
}
#[test]
fn bootstrap_reports_updater_bind_failure() -> Result<()> {
let daemon = TestDaemon::new()?;
let state = daemon.home.path().join("app-server-daemon");
std::fs::write(
state.join("settings.json"),
br#"{"shutdownGraceSeconds":0}"#,
)?;
let socket = state.join("app-server-updater.sock");
std::fs::write(&socket, b"not a socket")?;
let result = daemon
.command()
.args(["app-server", "daemon", "bootstrap"])
.output()?;
assert!(!result.status.success());
assert_eq!(std::fs::read(socket)?, b"not a socket");
assert_eq!(daemon.lifecycle("version")?["status"], "running");
Ok(())
}
#[test]
fn explicit_restart_applies_feature_overrides_and_preserves_saved_settings() -> Result<()> {
let daemon = TestDaemon::new()?;
let settings_path = daemon.home.path().join("app-server-daemon/settings.json");
std::fs::write(
&settings_path,
serde_json::to_vec(&serde_json::json!({
"shutdownGraceSeconds": 0,
"updater": { "autoUpdateEnabled": false },
"featureOverrides": {
"api_key_model_discovery": false,
"auth_elicitation": true,
"connectors": true,
"apps": true
}
}))?,
)?;
let mut previous_pid = None;
// Start from a stopped daemon, change running settings, and restart again
// with omitted flags. Every explicit restart replaces the process.
for (args, discovery) in [
(
vec![
"--enable",
"api_key_model_discovery",
"--disable",
"connectors",
"-c",
"features.network_proxy.enabled=false",
],
true,
),
(vec!["--disable", "api_key_model_discovery"], false),
(vec!["-c", "features.api_key_model_discovery=true"], true),
(vec![], true),
] {
let output = daemon
.command()
.args(["app-server", "daemon", "restart"])
.args(args)
.output()?;
ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let output: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(output["status"], "restarted");
let pid = output["pid"].as_u64().context("restarted daemon PID")?;
assert_ne!(Some(pid), previous_pid);
previous_pid = Some(pid);
let settings: Value = serde_json::from_slice(&std::fs::read(&settings_path)?)?;
assert_eq!(
settings["featureOverrides"],
serde_json::json!({
"api_key_model_discovery": discovery,
"auth_elicitation": true,
"apps": false,
"network_proxy": false
})
);
assert_eq!(settings["updater"]["autoUpdateEnabled"], false);
}
// Non-toggle config keys must fail before stopping the daemon or saving settings.
let saved_settings = std::fs::read(&settings_path)?;
let output = daemon
.command()
.args([
"app-server",
"daemon",
"restart",
"--enable",
"tool_registry",
])
.output()?;
assert!(!output.status.success());
insta::assert_snapshot!(
String::from_utf8(output.stderr)?,
@"Error: daemon restart requires a boolean feature toggle: tool_registry"
);
assert_eq!(std::fs::read(&settings_path)?, saved_settings);
assert_eq!(Some(u64::from(daemon.pid("app-server.pid")?)), previous_pid);
assert_eq!(daemon.lifecycle("version")?["status"], "running");
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn managed_identity_survives_locale_and_timezone_changes() -> Result<()> {
let daemon = TestDaemon::new()?;
let mut original = Vec::new();
let mut updater_pid = 0;
let pid_file = daemon.home.path().join("app-server-daemon/app-server.pid");
for (action, locale, timezone, expected_status) in [
("start", "C", "UTC0", "started"),
("version", "en_AU.UTF-8", "PST8PDT", "running"),
("restart", "en_AU.UTF-8", "PST8PDT", "restarted"),
("stop", "C", "UTC0", "stopped"),
] {
let output = daemon
.command()
.args(["app-server", "daemon", action])
.env("LC_ALL", locale)
.env("TZ", timezone)
.output()?;
ensure!(
output.status.success(),
"daemon {action} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let output: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(output["status"], expected_status);
if action == "start" {
updater_pid = daemon.pid("app-server-updater.pid")?;
original = std::fs::read(&pid_file)?;
let record: Value = serde_json::from_slice(&original)?;
assert!(record["processIdentity"].is_object());
// Older clients still receive the original, unnormalized ps value.
let legacy = Command::new("ps")
.args([
"-p",
&daemon.pid("app-server.pid")?.to_string(),
"-o",
"lstart=",
])
.env("LC_ALL", locale)
.env("TZ", timezone)
.output()?;
ensure!(legacy.status.success(), "failed to read legacy start time");
assert_eq!(
record["processStartTime"],
String::from_utf8(legacy.stdout)?.trim()
);
} else if action == "version" {
assert_eq!(output["backend"], "pid");
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
assert_eq!(std::fs::read(&pid_file)?, original);
// Finish startup promotion before deliberately restoring a legacy record.
let updater_socket = daemon
.home
.path()
.join("app-server-daemon/app-server-updater.sock");
let deadline = Instant::now() + Duration::from_secs(30);
while !updater_socket.exists() {
ensure!(Instant::now() < deadline, "updater did not become ready");
std::thread::sleep(Duration::from_millis(50));
}
let mut legacy: Value = serde_json::from_slice(&original)?;
legacy
.as_object_mut()
.context("PID record object")?
.remove("processIdentity");
let legacy_bytes = serde_json::to_vec(&legacy)?;
std::fs::write(&pid_file, &legacy_bytes)?;
let result = daemon
.command()
.args(["app-server", "daemon", "version"])
.env("LC_ALL", locale)
.env("TZ", timezone)
.output();
let preserved = std::fs::read(&pid_file);
// Restore the native identity before assertions so Drop can stop the daemon.
std::fs::write(&pid_file, &original)?;
let result = result?;
assert!(!result.status.success());
assert_eq!(preserved?, legacy_bytes);
let stderr =
String::from_utf8(result.stderr)?.replace(&legacy["pid"].to_string(), "[PID]");
insta::assert_snapshot!(stderr, @"Error: cannot verify pid-managed process [PID]: legacy start time changed; PID record retained. Retry with the locale and timezone used to start the daemon. If the system clock changed, stop the original process before restarting the daemon");
}
if action == "restart" {
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
}
}
assert!(!pid_file.exists());
Ok(())
}
#[test]
fn package_ownership_check_does_not_start_an_updater() -> Result<()> {
let daemon = TestDaemon::new()?;
let output = daemon
.command()
.args([
"app-server",
"daemon",
"pid-update-loop",
"--check-package-ownership",
])
.output()?;
ensure!(
output.status.success(),
"ownership check failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let state = daemon.home.path().join("app-server-daemon");
assert!(!state.join("app-server-updater.pid").exists());
assert!(!state.join("daemon-updater.pid").exists());
Ok(())
}
#[test]
fn managed_starts_ensure_one_updater_and_recover_a_missing_one() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let backend_pid = daemon.pid("app-server.pid")?;
let updater_pid = daemon.pid("app-server-updater.pid")?;
assert_ne!(backend_pid, updater_pid);
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, backend_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
signal(updater_pid, libc::SIGTERM)?;
wait_for_exit(updater_pid)?;
// A replacement updater also upgrades still-verifiable records left by an old CLI.
let server_record_path = daemon.home.path().join("app-server-daemon/app-server.pid");
let mut legacy: Value = serde_json::from_slice(&std::fs::read(&server_record_path)?)?;
let native = legacy.as_object_mut().unwrap().remove("processIdentity");
std::fs::write(&server_record_path, serde_json::to_vec(&legacy)?)?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, backend_pid);
let replacement_pid = daemon.pid("app-server-updater.pid")?;
assert_ne!(replacement_pid, updater_pid);
if let Some(native) = native {
legacy["processIdentity"] = native;
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let record: Value = serde_json::from_slice(&std::fs::read(&server_record_path)?)?;
if record == legacy {
break;
}
ensure!(
Instant::now() < deadline,
"legacy record was not upgraded: {record}"
);
std::thread::sleep(Duration::from_millis(50));
}
}
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
assert_ne!(daemon.pid("app-server.pid")?, backend_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, replacement_pid);
daemon.lifecycle("stop")?;
assert!(
!daemon
.home
.path()
.join("app-server-daemon/app-server.pid")
.exists()
);
assert_eq!(daemon.lifecycle("start")?["status"], "started");
assert!(
!daemon
.home
.path()
.join("packages/app-server-daemon")
.exists()
);
Ok(())
}
#[test]
fn managed_start_succeeds_when_updater_record_is_invalid() -> Result<()> {
let daemon = TestDaemon::new()?;
let state_dir = daemon.home.path().join("app-server-daemon");
std::fs::create_dir_all(&state_dir)?;
std::fs::write(state_dir.join("app-server-updater.pid"), "not a PID record")?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let server_pid = daemon.pid("app-server.pid")?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, server_pid);
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn wall_clock_shift_keeps_server_and_updater_managed() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let server_pid = daemon.pid("app-server.pid")?;
let updater_pid = daemon.pid("app-server-updater.pid")?;
for name in ["app-server.pid", "app-server-updater.pid"] {
let path = daemon.home.path().join("app-server-daemon").join(name);
let mut record: Value = serde_json::from_slice(&std::fs::read(&path)?)?;
record["processStartTime"] = "historical wall-clock start time".into();
let replacement = path.with_extension("replacement");
std::fs::write(&replacement, serde_json::to_vec(&record)?)?;
std::fs::rename(replacement, path)?;
}
let version = daemon.lifecycle("version")?;
assert_eq!(version["status"], "running");
assert_eq!(version["backend"], "pid");
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, server_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
wait_for_exit(server_pid)?;
assert_ne!(daemon.pid("app-server.pid")?, server_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
Ok(())
}
#[test]
fn managed_start_keeps_updater_on_marker_mismatch_but_stops_it_for_pin() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let updater_pid = daemon.pid("app-server-updater.pid")?;
let marker = daemon
.home
.path()
.join("packages/standalone/auto-update-version");
std::fs::write(&marker, "0.1.0-other-target")?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
std::thread::sleep(Duration::from_millis(250));
let updater_state = Command::new("/bin/ps")
.args(["-p", &updater_pid.to_string(), "-o", "stat="])
.output()?;
ensure!(
updater_state.status.success()
&& !String::from_utf8_lossy(&updater_state.stdout)
.trim()
.starts_with('Z'),
"updater exited during the latest marker transition"
);
std::fs::remove_file(marker)?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
wait_for_exit(updater_pid)?;
assert!(
!daemon
.home
.path()
.join("app-server-daemon/app-server-updater.pid")
.exists()
);
Ok(())
}
#[test]
fn restart_applies_saved_updater_preference() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let updater_pid = daemon.pid("app-server-updater.pid")?;
let settings = daemon.home.path().join("app-server-daemon/settings.json");
std::fs::write(
&settings,
serde_json::to_vec(&serde_json::json!({
"updater": {"autoUpdateEnabled": false, "updateIntervalMinutes": 2},
}))?,
)?;
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
wait_for_exit(updater_pid)?;
assert!(daemon.pid("app-server-updater.pid").is_err());
assert_eq!(daemon.lifecycle("bootstrap")?["autoUpdateEnabled"], false);
assert!(daemon.pid("app-server-updater.pid").is_err());
std::fs::write(
&settings,
serde_json::to_vec(&serde_json::json!({
"updater": {"autoUpdateEnabled": true, "updateIntervalMinutes": 2},
}))?,
)?;
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
assert_ne!(daemon.pid("app-server-updater.pid")?, updater_pid);
std::fs::write(&settings, "{malformed")?;
assert_eq!(daemon.lifecycle("stop")?["status"], "stopped");
Ok(())
}
#[test]
fn unmanaged_app_server_does_not_launch_updater() -> Result<()> {
let mut daemon = TestDaemon::new()?;
daemon.unmanaged = Some(
daemon
.command()
.args(["app-server", "--listen", "unix://"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?,
);
let deadline = Instant::now() + Duration::from_secs(30);
while !daemon
.command()
.args(["app-server", "daemon", "version"])
.output()?
.status
.success()
{
ensure!(Instant::now() < deadline, "app server did not become ready");
std::thread::sleep(Duration::from_millis(50));
}
let output = daemon.lifecycle("start")?;
assert_eq!(output["status"], "alreadyRunning");
assert_eq!(output["backend"], Value::Null);
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
assert!(
!daemon
.home
.path()
.join("app-server-daemon/app-server-updater.pid")
.exists()
);
Ok(())
}
#[test]
fn manual_update_rejects_an_unowned_installation() -> Result<()> {
let daemon = TestDaemon::new()?;
std::fs::remove_file(
daemon
.home
.path()
.join("packages/standalone/current/bin/codex"),
)?;
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
assert!(daemon.pid("app-server.pid").is_err());
assert!(daemon.pid("app-server-updater.pid").is_err());
Ok(())
}

View File

@@ -0,0 +1,219 @@
//! Real package installation and replacement through the daemon CLI.
//! Keep these I/O-heavy cases separate from ordinary lifecycle coverage.
#![cfg(unix)]
mod support;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use pretty_assertions::assert_eq;
use serde_json::Value;
use support::TestDaemon;
use support::wait_for_exit;
#[derive(Clone, Copy, PartialEq, Eq)]
enum InitialDaemon {
Missing,
Legacy,
}
fn packaged_daemon_launch(action: &str, initial: InitialDaemon) -> Result<()> {
let mut daemon = TestDaemon::new()?;
let standalone = daemon.home.path().join("packages/standalone");
let package = if action == "start" && initial == InitialDaemon::Missing {
standalone.join("releases/caller")
} else {
daemon.home.path().join("cli-package")
};
for directory in ["bin", "codex-path", "codex-resources"] {
std::fs::create_dir_all(package.join(directory))?;
}
// Both paths are in this test's temp home and therefore on the same filesystem.
// Reuse its prepared (and on Intel macOS, translated) executable. The installer
// still makes a real independent package copy; only fixture setup shares this inode.
std::fs::hard_link(
standalone.join("current/bin/codex"),
package.join("bin/codex"),
)?;
daemon.codex = package.join("bin/codex");
for helper in [
"bin/codex-code-mode-host",
"codex-path/rg",
"codex-resources/bwrap",
] {
codex_utils_cargo_bin::write_executable(&package.join(helper), "runtime fixture")?;
}
let target = format!(
"{}-{}",
std::env::consts::ARCH,
if cfg!(target_os = "macos") {
"apple-darwin"
} else if cfg!(target_env = "gnu") {
"unknown-linux-gnu"
} else {
"unknown-linux-musl"
}
);
std::fs::write(
package.join("codex-package.json"),
serde_json::to_vec(&serde_json::json!({
"version": env!("CARGO_PKG_VERSION"), "target": target, "entrypoint": "bin/codex"
}))?,
)?;
if action == "start" && initial == InitialDaemon::Missing {
std::fs::remove_file(standalone.join("current"))?;
std::os::unix::fs::symlink(&package, standalone.join("current"))?;
}
let cli_selection = standalone.join("current").canonicalize()?;
let state = daemon.home.path().join("app-server-daemon");
if initial == InitialDaemon::Missing {
std::fs::remove_file(state.join("app-server.stderr.log"))?;
}
std::fs::write(
state.join("settings.json"),
br#"{"shutdownGraceSeconds":0}"#,
)?;
let cli_before = daemon.codex.canonicalize()?;
let result = daemon
.command()
.args(["app-server", "daemon", action])
.output()
.context("failed to launch packaged daemon fixture")?;
ensure!(
result.status.success(),
"{}",
String::from_utf8_lossy(&result.stderr)
);
assert_eq!(
String::from_utf8_lossy(&result.stderr).contains("Installing daemon from CLI version"),
initial == InitialDaemon::Missing
);
let output: Value = serde_json::from_slice(&result.stdout)?;
let dedicated = daemon
.home
.path()
.canonicalize()?
.join("packages/app-server-daemon");
let (initial_root, initial_pid_file) = match initial {
InitialDaemon::Missing => (&dedicated, "daemon.pid"),
InitialDaemon::Legacy => (&standalone, "app-server.pid"),
};
assert_eq!(
output["managedCodexPath"],
initial_root
.canonicalize()?
.join("current/bin/codex")
.to_str()
.context("managed path is not UTF-8")?
);
assert_eq!(daemon.codex.canonicalize()?, cli_before);
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
assert!(state.join(initial_pid_file).exists());
let legacy_updater = match initial {
InitialDaemon::Missing => {
assert!(!state.join("app-server-updater.pid").exists());
None
}
InitialDaemon::Legacy => Some(daemon.pid("app-server-updater.pid")?),
};
if action == "start" {
let initial_current = initial_root.join("current");
let current = dedicated.join("current");
let original = initial_current.canonicalize()?;
let original_pid = daemon.pid(initial_pid_file)?;
let settings_before = std::fs::read(state.join("settings.json"))?;
let refused = daemon
.command()
.args(["app-server", "daemon", "update", "--from-cli"])
.output()?;
assert!(!refused.status.success());
assert!(String::from_utf8_lossy(&refused.stderr).contains("rerun with --yes"));
assert_eq!(daemon.pid(initial_pid_file)?, original_pid);
assert_eq!(initial_current.canonicalize()?, original);
if initial == InitialDaemon::Legacy {
assert!(!current.exists());
}
std::fs::remove_file(package.join("bin/codex-code-mode-host"))?;
let invalid = daemon
.command()
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
.output()?;
assert!(!invalid.status.success());
assert_eq!(daemon.pid(initial_pid_file)?, original_pid);
assert_eq!(initial_current.canonicalize()?, original);
if initial == InitialDaemon::Legacy {
assert!(!current.exists());
}
codex_utils_cargo_bin::write_executable(
&package.join("bin/codex-code-mode-host"),
"replacement helper",
)?;
let replaced = daemon
.command()
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
.output()?;
ensure!(
replaced.status.success(),
"{}",
String::from_utf8_lossy(&replaced.stderr)
);
let output: Value = serde_json::from_slice(&replaced.stdout)?;
assert_eq!(output["status"], "updated");
assert_ne!(daemon.pid("daemon.pid")?, original_pid);
wait_for_exit(original_pid)?;
if let Some(pid) = legacy_updater {
wait_for_exit(pid)?;
}
assert!(!state.join("app-server.pid").exists());
assert!(!state.join("app-server-updater.pid").exists());
assert_eq!(
output["managedCodexPath"],
current
.join("bin/codex")
.to_str()
.context("managed path is not UTF-8")?
);
assert_ne!(current.canonicalize()?, original);
assert!(!dedicated.join("auto-update-version").exists());
assert_eq!(std::fs::read(state.join("settings.json"))?, settings_before);
assert_eq!(
std::fs::read(current.join("bin/codex-code-mode-host"))?,
b"replacement helper"
);
if initial == InitialDaemon::Missing {
assert_eq!(
std::fs::read(original.join("bin/codex-code-mode-host"))?,
b"runtime fixture"
);
}
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.lifecycle("stop")?["status"], "stopped");
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
}
if action == "bootstrap" {
assert_eq!(output["autoUpdateEnabled"], false);
}
Ok(())
}
#[test]
fn packaged_daemon_start_and_explicit_replacement() -> Result<()> {
packaged_daemon_launch("start", InitialDaemon::Missing)
}
#[test]
fn packaged_daemon_restart_seeds_local_package() -> Result<()> {
packaged_daemon_launch("restart", InitialDaemon::Missing)
}
#[test]
fn packaged_daemon_bootstrap_seeds_local_package() -> Result<()> {
packaged_daemon_launch("bootstrap", InitialDaemon::Missing)
}
#[test]
fn packaged_daemon_explicit_replacement_migrates_running_legacy() -> Result<()> {
packaged_daemon_launch("start", InitialDaemon::Legacy)
}

View File

@@ -0,0 +1,140 @@
//! Isolated installed-CLI fixtures and PID cleanup for Unix daemon integration tests.
//! Every test owns its home and CLI selection; only immutable executable contents are shared.
use std::path::PathBuf;
use std::process::Child;
use std::process::Command;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use codex_utils_cargo_bin::copy_executable;
use serde_json::Value;
use tempfile::TempDir;
pub(super) struct TestDaemon {
pub(super) home: TempDir,
pub(super) codex: PathBuf,
pub(super) unmanaged: Option<Child>,
}
impl TestDaemon {
pub(super) fn new() -> Result<Self> {
let home = tempfile::Builder::new().tempdir_in("/tmp")?;
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
let codex_source = std::fs::canonicalize(&codex)?;
let target = if cfg!(target_os = "macos") {
format!("{}-apple-darwin", std::env::consts::ARCH)
} else {
format!("{}-unknown-linux-musl", std::env::consts::ARCH)
};
let standalone = home.path().join("packages/standalone");
let release_name = format!("0.0.0-{target}");
let managed = standalone
.join("releases")
.join(&release_name)
.join("bin/codex");
std::fs::create_dir_all(managed.parent().context("managed bin parent")?)?;
// Preserve the installed path without invalidating the shared CLI's Rosetta cache.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
{
copy_executable(&codex_source, &managed)?;
// Translate the fixture before timed daemon capability and readiness checks.
ensure!(
Command::new(&managed)
.env("CODEX_HOME", home.path())
.arg("--version")
.output()?
.status
.success(),
"failed to prepare managed test executable"
);
}
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
if std::fs::hard_link(&codex_source, &managed).is_err() {
copy_executable(&codex_source, &managed)?;
}
std::fs::write(standalone.join("auto-update-version"), &release_name)?;
std::os::unix::fs::symlink(
PathBuf::from("releases").join(release_name),
standalone.join("current"),
)?;
// Model a daemon that was previously launched and is currently stopped.
let state = home.path().join("app-server-daemon");
std::fs::create_dir(&state)?;
std::fs::write(state.join("app-server.stderr.log"), b"")?;
Ok(Self {
home,
codex,
unmanaged: None,
})
}
pub(super) fn command(&self) -> Command {
let mut command = Command::new(&self.codex);
command.env("CODEX_HOME", self.home.path());
command
}
pub(super) fn lifecycle(&self, action: &str) -> Result<Value> {
let output = self
.command()
.args(["app-server", "daemon", action])
.output()?;
ensure!(
output.status.success(),
"daemon {action} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
Ok(serde_json::from_slice(&output.stdout)?)
}
pub(super) fn pid(&self, name: &str) -> Result<u32> {
let record = std::fs::read(self.home.path().join("app-server-daemon").join(name))
.with_context(|| format!("failed to read {name}"))?;
Ok(serde_json::from_slice::<Value>(&record)?["pid"]
.as_u64()
.context("pid missing")? as u32)
}
}
impl Drop for TestDaemon {
fn drop(&mut self) {
if let Some(mut child) = self.unmanaged.take() {
let _ = child.kill();
let _ = child.wait();
}
let _ = self.lifecycle("stop");
if let Ok(pid) = self.pid("app-server-updater.pid") {
let _ = signal(pid, libc::SIGTERM);
}
}
}
pub(super) fn signal(pid: u32, signal: libc::c_int) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid).context("pid out of range")?;
ensure!(
unsafe { libc::kill(raw_pid, signal) } == 0,
"failed to signal pid {pid}: {}",
std::io::Error::last_os_error()
);
Ok(())
}
pub(super) fn wait_for_exit(pid: u32) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let output = Command::new("/bin/ps")
.args(["-p", &pid.to_string(), "-o", "stat="])
.output()
.context("failed to invoke ps")?;
let state = String::from_utf8_lossy(&output.stdout);
if !output.status.success() || state.trim().starts_with('Z') {
return Ok(());
}
ensure!(Instant::now() < deadline, "pid {pid} did not exit: {state}");
std::thread::sleep(Duration::from_millis(50));
}
}

View File

@@ -0,0 +1,126 @@
//! Exercises daemon installation from the Windows WinGet archive layout.
#![cfg(windows)]
use anyhow::Result;
use anyhow::ensure;
use codex_utils_cargo_bin::copy_executable;
use pretty_assertions::assert_eq;
use serde_json::Value;
use sha2::Digest;
use sha2::Sha256;
use std::process::Command;
#[test]
fn winget_package_starts_and_reselects_daemon() -> Result<()> {
if codex_app_server_daemon::is_elevated()? {
eprintln!("requires a non-elevated Windows runner");
return Ok(());
}
let temp = tempfile::tempdir()?;
let home = temp.path().join("home");
let package = temp.path().join("WinGet/Packages/OpenAI.Codex");
let target = format!("{}-pc-windows-msvc", std::env::consts::ARCH);
let entrypoint = format!("codex-{target}.exe");
let codex = package.join(&entrypoint);
for directory in ["bin", "codex-path", "codex-resources/voice"] {
std::fs::create_dir_all(package.join(directory))?;
}
copy_executable(&codex_utils_cargo_bin::cargo_bin("codex")?, &codex)?;
for helper in [
"codex-code-mode-host.exe",
"codex-path/rg.exe",
"codex-resources/codex-command-runner.exe",
"codex-resources/codex-windows-sandbox-setup.exe",
] {
std::fs::write(package.join(helper), b"runtime fixture")?;
}
let mut metadata = serde_json::json!({
"layoutVersion": 1, "version": env!("CARGO_PKG_VERSION"),
"target": target, "entrypoint": entrypoint
});
let manifest_bytes = serde_json::to_vec(&metadata)?;
std::fs::write(package.join("codex-package.json"), &manifest_bytes)?;
let checksum = format!("{:x}", Sha256::digest(std::fs::read(&codex)?));
let voice_bytes = serde_json::to_vec(&serde_json::json!({
"sha256": { &entrypoint: checksum, "codex-resources/voice/runtime": "untouched" }
}))?;
std::fs::write(
package.join("codex-resources/voice/manifest.json"),
&voice_bytes,
)?;
let current = home.join("packages/app-server-daemon/current");
// Drop before temp so assertion failures also release the managed executable.
struct StopDaemon(Command);
impl Drop for StopDaemon {
fn drop(&mut self) {
let _ = self.0.output();
}
}
let mut stop = Command::new(&codex);
stop.env("CODEX_HOME", &home)
.args(["app-server", "daemon", "stop"]);
let mut daemon = StopDaemon(stop);
for args in [
vec!["start"],
vec!["update", "--from-cli", "--yes"],
vec!["update", "--from-cli", "--yes"],
] {
let output = Command::new(&codex)
.env("CODEX_HOME", &home)
.args(["app-server", "daemon"])
.args(&args)
.output()?;
ensure!(
output.status.success(),
"daemon {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let selected_metadata: Value =
serde_json::from_slice(&std::fs::read(current.join("codex-package.json"))?)?;
metadata["entrypoint"] = "bin/codex.exe".into();
assert_eq!(selected_metadata, metadata);
let selected_voice: Value = serde_json::from_slice(&std::fs::read(
current.join("codex-resources/voice/manifest.json"),
)?)?;
assert_eq!(
selected_voice,
serde_json::json!({
"sha256": {
"bin/codex.exe": checksum,
"codex-resources/voice/runtime": "untouched"
}
})
);
assert_eq!(
std::fs::read(current.join("bin/codex-code-mode-host.exe"))?,
b"runtime fixture"
);
let selected = current.canonicalize()?;
std::fs::remove_file(package.join("codex-code-mode-host.exe"))?;
let invalid = Command::new(&codex)
.env("CODEX_HOME", &home)
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
.output()?;
ensure!(
!invalid.status.success(),
"an incomplete WinGet package was accepted"
);
assert_eq!(current.canonicalize()?, selected);
assert_eq!(
std::fs::read(package.join("codex-package.json"))?,
manifest_bytes
);
assert_eq!(
std::fs::read(package.join("codex-resources/voice/manifest.json"))?,
voice_bytes
);
let stopped = daemon.0.output()?;
ensure!(
stopped.status.success(),
"failed to stop daemon: {}",
String::from_utf8_lossy(&stopped.stderr)
);
Ok(())
}

View File

@@ -0,0 +1,113 @@
//! Exercise Cloud credential isolation through the CLI using a synthetic login.
use anyhow::Result;
use predicates::str::contains;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::path;
#[tokio::test]
async fn cloud_list_respects_the_credential_store_and_trusted_destinations() -> Result<()> {
let server = MockServer::start().await;
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
"cli_auth_credentials_store = 'file'\n",
)?;
std::fs::write(
codex_home.path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"tokens": {
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "synthetic-cloud-access-token",
"refresh_token": "synthetic-cloud-refresh-token",
"account_id": "synthetic-cloud-account",
},
"last_refresh": chrono::Utc::now(),
}))?,
)?;
let command = || -> Result<assert_cmd::Command> {
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.current_dir(codex_home.path())
.env("CODEX_HOME", codex_home.path())
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_CLOUD_TASKS_MODE")
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.timeout(std::time::Duration::from_secs(15));
Ok(command)
};
// Establish that the isolated profile has a usable ChatGPT login.
command()?
.args(["login", "status"])
.assert()
.success()
.stderr(contains("Logged in using ChatGPT"));
let output = command()?
.env(
"CODEX_CLOUD_TASKS_BASE_URL",
format!("{}/backend-api", server.uri()),
)
.args(["cloud", "list", "--limit", "1", "--json"])
.assert()
.failure()
.get_output()
.stderr
.clone();
insta::assert_snapshot!(String::from_utf8(output)?, @"Error: CODEX_CLOUD_TASKS_BASE_URL must use a trusted HTTPS origin on port 443, without user information, a query, or a fragment; custom backends cannot use saved ChatGPT credentials");
assert!(server.received_requests().await.unwrap().is_empty());
// An explicit ephemeral store must exclude the saved login for Cloud itself.
command()?
.env(
"CODEX_CLOUD_TASKS_BASE_URL",
"https://chatgpt-staging.com/backend-api",
)
.env("HTTPS_PROXY", server.uri())
.env("https_proxy", server.uri())
.args([
"-c",
"cli_auth_credentials_store='ephemeral'",
"cloud",
"list",
"--limit",
"1",
"--json",
])
.assert()
.failure()
.stderr(contains("Not signed in. Please run 'codex login'"));
assert!(server.received_requests().await.unwrap().is_empty());
// Staging must reach explicit PAT authentication. Reject the synthetic PAT locally so
// this test never sends a request to the real staging backend.
let auth_server = MockServer::start().await;
Mock::given(path("/v1/user-auth-credential/whoami"))
.and(header("authorization", "Bearer at-synthetic-cloud"))
.respond_with(ResponseTemplate::new(401))
.expect(1)
.mount(&auth_server)
.await;
command()?
.env(
"CODEX_CLOUD_TASKS_BASE_URL",
"https://chatgpt-staging.com/backend-api",
)
.env("CODEX_ACCESS_TOKEN", "at-synthetic-cloud")
.env("CODEX_AUTHAPI_BASE_URL", auth_server.uri())
.args(["cloud", "list", "--limit", "1", "--json"])
.assert()
.failure()
.stderr(contains("Not signed in. Please run 'codex login'"));
auth_server.verify().await;
Ok(())
}

View File

@@ -0,0 +1,688 @@
use std::process::Output;
use std::process::Stdio;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::ConfigLoadOptions;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::load_config_toml_with_layer_stack;
use codex_core::config::load_global_mcp_servers;
use codex_core_plugins::installed_marketplaces::marketplace_install_root;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpStream;
use tokio::process::Command;
use tokio::time::timeout;
use url::Url;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_string_contains;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const MANAGED_SERVER_NAME: &str = "managed-slack";
const MANAGED_CLIENT_ID: &str = "managed-oauth-client";
const MANAGED_SCOPE: &str = "managed.read";
const MOCK_ACCESS_TOKEN: &str = "mock-managed-access-token";
const MOCK_REFRESH_TOKEN: &str = "mock-managed-refresh-token";
struct CloudManagedConfigFixture {
server: MockServer,
codex_home: TempDir,
user_config: String,
mcp_url: String,
}
impl CloudManagedConfigFixture {
async fn for_backend() -> Result<Option<Self>> {
let server = MockServer::start().await;
let chatgpt_base_url = format!("{}/backend-api", server.uri());
let codex_home = TempDir::new()?;
let user_config = format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{chatgpt_base_url}\"\n"
);
std::fs::write(codex_home.path().join("config.toml"), &user_config)?;
let bootstrap_config = load_config_toml_with_layer_stack(
codex_home.path(),
Some(&AbsolutePathBuf::from_absolute_path(codex_home.path())?),
Vec::new(),
ConfigLoadOptions::default(),
)
.await?;
if bootstrap_config.config_toml.cli_auth_credentials_store
!= Some(AuthCredentialsStoreMode::File)
|| bootstrap_config.config_toml.chatgpt_base_url.as_deref()
!= Some(chatgpt_base_url.as_str())
{
eprintln!(
"skipping cloud-managed subprocess: host-managed authentication or backend routing prevents isolated mock credentials"
);
return Ok(None);
}
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
let mcp_url = format!("{}/mcp", server.uri());
Ok(Some(Self {
server,
codex_home,
user_config,
mcp_url,
}))
}
async fn new() -> Result<Option<Self>> {
let Some(fixture) = Self::for_backend().await? else {
return Ok(None);
};
let mcp_url = &fixture.mcp_url;
let managed_config = format!(
"mcp_oauth_credentials_store = \"file\"\n\n\
[mcp_servers.{MANAGED_SERVER_NAME}]\n\
url = \"{mcp_url}\"\n\
auth = \"oauth\"\n\
scopes = [\"{MANAGED_SCOPE}\"]\n\n\
[mcp_servers.{MANAGED_SERVER_NAME}.oauth]\n\
client_id = \"{MANAGED_CLIENT_ID}\"\n\n\
[marketplaces.managed]\n\
source_type = \"git\"\n\
source = \"https://github.com/owner/repo.git\"\n"
);
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"config_toml": {
"enterprise_managed": [{
"id": "managed-config",
"name": "Managed resources",
"contents": managed_config,
}],
},
})))
.expect(1)
.mount(&fixture.server)
.await;
Ok(Some(fixture))
}
fn command(&self, args: &[&str]) -> Result<Command> {
let mut command = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.kill_on_drop(true)
.current_dir(self.codex_home.path())
.env("CODEX_HOME", self.codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT")
.args(args);
Ok(command)
}
async fn output(&self, args: &[&str]) -> Result<Output> {
let output = self.command(args)?.output().await?;
ensure!(
output.status.success(),
"codex {} failed with status {}: stdout={}; stderr={}",
args.join(" "),
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
Ok(output)
}
fn assert_user_config_unchanged(&self) -> Result<()> {
assert_eq!(
std::fs::read_to_string(self.codex_home.path().join("config.toml"))?,
self.user_config
);
Ok(())
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_and_get_resolve_cloud_managed_mcp_without_writing_user_config() -> Result<()> {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
let output = fixture.output(&["mcp", "list", "--json"]).await?;
let entries: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(entries[0]["name"], MANAGED_SERVER_NAME);
assert_eq!(entries[0]["transport"]["type"], "streamable_http");
assert_eq!(entries[0]["transport"]["url"], fixture.mcp_url);
let output = fixture
.output(&["mcp", "get", MANAGED_SERVER_NAME, "--json"])
.await?;
let entry: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(entry["name"], MANAGED_SERVER_NAME);
assert_eq!(entry["transport"]["url"], fixture.mcp_url);
assert!(
fixture
.codex_home
.path()
.join("cloud-config-bundle-cache.json")
.exists()
);
fixture.assert_user_config_unchanged()?;
fixture.server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn login_and_logout_persist_only_cloud_managed_mcp_oauth_credentials() -> Result<()> {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
let challenge = format!(
"Bearer resource_metadata=\"{}/oauth-resource\"",
fixture.server.uri()
);
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(401).insert_header("WWW-Authenticate", challenge))
.mount(&fixture.server)
.await;
Mock::given(method("GET"))
.and(path("/oauth-resource"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": fixture.mcp_url,
"authorization_servers": [fixture.server.uri()],
})))
.mount(&fixture.server)
.await;
let oauth_metadata = json!({
"issuer": fixture.server.uri(),
"authorization_endpoint": format!("{}/oauth/authorize", fixture.server.uri()),
"token_endpoint": format!("{}/oauth/token", fixture.server.uri()),
"response_types_supported": ["code"],
"code_challenge_methods_supported": ["S256"],
"scopes_supported": [MANAGED_SCOPE],
});
for metadata_path in [
"/.well-known/oauth-authorization-server",
"/.well-known/oauth-authorization-server/mcp",
] {
Mock::given(method("GET"))
.and(path(metadata_path))
.respond_with(ResponseTemplate::new(200).set_body_json(oauth_metadata.clone()))
.mount(&fixture.server)
.await;
}
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_string_contains(format!(
"client_id={MANAGED_CLIENT_ID}"
)))
.and(body_string_contains("grant_type=authorization_code"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": MOCK_ACCESS_TOKEN,
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": MOCK_REFRESH_TOKEN,
"scope": MANAGED_SCOPE,
})))
.expect(1)
.mount(&fixture.server)
.await;
let mut command = fixture.command(&["mcp", "login", MANAGED_SERVER_NAME, "--no-browser"])?;
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
let mut child = command.spawn()?;
// Keep input open through child.wait() so the HTTP callback cannot race EOF.
let _stdin = child
.stdin
.take()
.context("MCP login did not provide stdin")?;
let stdout = child
.stdout
.take()
.context("MCP login did not provide captured stdout")?;
let mut lines = BufReader::new(stdout).lines();
let authorization_url = timeout(Duration::from_secs(30), async {
while let Some(line) = lines.next_line().await? {
if line.starts_with("http://") || line.starts_with("https://") {
return Ok::<_, anyhow::Error>(Url::parse(line.trim())?);
}
}
anyhow::bail!("MCP login exited before printing its OAuth authorization URL")
})
.await
.context("timed out waiting for the managed MCP authorization URL")??;
let query_pairs: Vec<_> = authorization_url.query_pairs().into_owned().collect();
let state = query_pairs
.iter()
.find(|(name, _)| name == "state")
.map(|(_, value)| value.as_str())
.context("managed MCP authorization URL did not contain OAuth state")?;
assert_eq!(
query_pairs
.iter()
.find(|(name, _)| name == "client_id")
.map(|(_, value)| value.as_str()),
Some(MANAGED_CLIENT_ID)
);
assert_eq!(
query_pairs
.iter()
.find(|(name, _)| name == "scope")
.map(|(_, value)| value.as_str()),
Some(MANAGED_SCOPE)
);
let redirect_uri = query_pairs
.iter()
.find(|(name, _)| name == "redirect_uri")
.map(|(_, value)| value.as_str())
.context("managed MCP authorization URL did not contain a callback")?;
let mut callback_url = Url::parse(redirect_uri)?;
callback_url
.query_pairs_mut()
.append_pair("code", "mock-managed-authorization-code")
.append_pair("state", state);
let callback_host = callback_url
.host_str()
.context("managed MCP callback did not contain a host")?;
let callback_port = callback_url
.port_or_known_default()
.context("managed MCP callback did not contain a port")?;
let callback_path = match callback_url.query() {
Some(query) => format!("{}?{query}", callback_url.path()),
None => callback_url.path().to_string(),
};
let callback_response = timeout(Duration::from_secs(30), async {
let mut callback = TcpStream::connect((callback_host, callback_port)).await?;
callback
.write_all(
format!(
"GET {callback_path} HTTP/1.1\r\nHost: {callback_host}:{callback_port}\r\nConnection: close\r\n\r\n"
)
.as_bytes(),
)
.await?;
let mut response_lines = BufReader::new(callback).lines();
response_lines
.next_line()
.await?
.context("managed MCP OAuth callback returned an empty HTTP response")
})
.await
.context("timed out waiting for the managed MCP OAuth callback response")??;
ensure!(
callback_response.starts_with("HTTP/1.1 200")
|| callback_response.starts_with("HTTP/1.0 200"),
"managed MCP OAuth callback failed: {callback_response}"
);
let login_status = timeout(Duration::from_secs(30), child.wait())
.await
.context("timed out waiting for managed MCP login")??;
ensure!(
login_status.success(),
"managed MCP login failed: status={login_status}"
);
timeout(Duration::from_secs(30), async {
while let Some(line) = lines.next_line().await? {
if line.contains("Successfully logged in to MCP server 'managed-slack'.") {
return Ok::<_, anyhow::Error>(());
}
}
anyhow::bail!("managed MCP login exited before printing its success message")
})
.await
.context("timed out waiting for the managed MCP login success message")??;
let credentials_path = fixture.codex_home.path().join(".credentials.json");
let credentials: Value = serde_json::from_slice(&std::fs::read(&credentials_path)?)?;
let entries = credentials
.as_object()
.context("MCP credentials should be a JSON object")?;
assert_eq!(entries.len(), 1);
let credential = entries
.values()
.next()
.context("managed MCP OAuth credentials were not persisted")?;
assert_eq!(credential["server_name"], MANAGED_SERVER_NAME);
assert_eq!(credential["server_url"], fixture.mcp_url);
assert_eq!(credential["client_id"], MANAGED_CLIENT_ID);
assert_eq!(credential["access_token"], MOCK_ACCESS_TOKEN);
assert_eq!(credential["refresh_token"], MOCK_REFRESH_TOKEN);
assert_eq!(credential["scopes"], json!([MANAGED_SCOPE]));
fixture.assert_user_config_unchanged()?;
let list_output = fixture.output(&["mcp", "list", "--json"]).await?;
let entries: Value = serde_json::from_slice(&list_output.stdout)?;
assert_eq!(entries[0]["name"], MANAGED_SERVER_NAME);
assert_eq!(entries[0]["auth_status"], "o_auth");
let logout_output = fixture
.output(&["mcp", "logout", MANAGED_SERVER_NAME])
.await?;
assert!(
String::from_utf8(logout_output.stdout)?
.contains("Removed OAuth credentials for 'managed-slack'.")
);
assert!(!credentials_path.exists());
fixture.assert_user_config_unchanged()?;
fixture.server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn add_and_remove_preserve_cloud_managed_resources() -> Result<()> {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
let installed_root = marketplace_install_root(fixture.codex_home.path()).join("managed");
std::fs::create_dir_all(&installed_root)?;
let marker = installed_root.join("marker.txt");
std::fs::write(&marker, "installed")?;
// Exercise both the initial fetch and the cached bundle without a user entry.
for _ in 0..2 {
let output = fixture
.command(&["plugin", "marketplace", "remove", "managed"])?
.output()
.await?;
assert!(!output.status.success());
assert!(String::from_utf8(output.stderr)?.contains(
"marketplace `managed` is configured in enterprise-managed (Managed resources, managed-config); remove it from that configuration source instead"
));
fixture.assert_user_config_unchanged()?;
assert_eq!(std::fs::read_to_string(&marker)?, "installed");
}
fixture
.output(&["mcp", "get", MANAGED_SERVER_NAME, "--json"])
.await?;
fixture
.output(&["mcp", "add", "local-docs", "--", "echo", "hello"])
.await?;
let local_servers = load_global_mcp_servers(fixture.codex_home.path()).await?;
assert!(local_servers.contains_key("local-docs"));
assert!(!local_servers.contains_key(MANAGED_SERVER_NAME));
let output = fixture
.output(&["mcp", "remove", MANAGED_SERVER_NAME])
.await?;
assert!(
String::from_utf8(output.stdout)?.contains("No MCP server named 'managed-slack' found.")
);
let local_servers = load_global_mcp_servers(fixture.codex_home.path()).await?;
assert!(local_servers.contains_key("local-docs"));
assert!(!local_servers.contains_key(MANAGED_SERVER_NAME));
fixture.output(&["mcp", "remove", "local-docs"]).await?;
assert!(
load_global_mcp_servers(fixture.codex_home.path())
.await?
.is_empty()
);
fixture
.output(&["mcp", "get", MANAGED_SERVER_NAME, "--json"])
.await?;
fixture.server.verify().await;
Ok(())
}
async fn mock_startup_bundle(server: &MockServer, status: u16, config: &str, requirements: &str) {
server.reset().await;
let layer = |contents: &str| {
json!({
"enterprise_managed": [{"id": "startup", "name": "Startup policy", "contents": contents}]
})
};
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.respond_with(ResponseTemplate::new(status).set_body_json(json!({
"config_toml": layer(config), "requirements_toml": layer(requirements),
})))
.expect(1..)
.mount(server)
.await;
}
async fn successful_json(command: &mut Command) -> Result<Value> {
let output = command.output().await?;
ensure!(output.status.success(), "{output:?}");
Ok(serde_json::from_slice(&output.stdout)?)
}
#[tokio::test]
async fn startup_config_loads_managed_policy_or_reports_cloud_failure() -> Result<()> {
for status in [200, 401, 503] {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
mock_startup_bundle(
&fixture.server,
status,
"forced_login_method = 'api'\n",
"[application.network.domains]\n'127.0.0.1' = 'allow'\n'example.com' = 'allow'\n",
)
.await;
let sqlite_home = TempDir::new()?;
let history_path = sqlite_home.path().join("state_5.sqlite");
std::fs::write(&history_path, b"history must not be repaired")?;
let output = fixture
.command(&["app-server", "--print-startup-config"])?
.env("CODEX_SQLITE_HOME", sqlite_home.path())
.env(
"CODEX_REFRESH_TOKEN_URL_OVERRIDE",
format!("{}/refresh", fixture.server.uri()),
)
.output()
.await?;
let value: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(output.status.success(), status == 200, "{value}");
if status == 200 {
let requirements = &value["configRequirements"]["requirements"];
assert_eq!(requirements["allowedLoginMethods"], json!(["api"]));
assert_eq!(
requirements["application"]["network"]["domains"]["example.com"],
"allow"
);
} else {
assert_eq!(value["error"]["data"]["reason"], "cloudConfigBundle");
assert!(value.get("configRequirements").is_none());
}
assert_eq!(
std::fs::read(&history_path)?,
b"history must not be repaired"
);
assert_eq!(std::fs::read_dir(sqlite_home.path())?.count(), 1);
fixture.server.verify().await;
}
Ok(())
}
#[tokio::test]
async fn startup_config_sign_out_reloads_policy_without_starting_runtime() -> Result<()> {
for (status, provider) in [(200, None), (503, None), (503, Some("amazon-bedrock"))] {
let Some(mut fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
if let Some(provider) = provider {
fixture
.user_config
.push_str(&format!("model_provider = \"{provider}\"\n"));
}
std::fs::write(
fixture.codex_home.path().join("config.toml"),
&fixture.user_config,
)?;
mock_startup_bundle(
&fixture.server, status, "forced_login_method = 'api'\n",
"cli_auth_credentials_store = 'ephemeral'\nenforce_residency = 'us'\n[application.network.domains]\n'127.0.0.1' = 'allow'\n[windows]\nrequire_mxc = true\n",
).await;
let mut revoke = Mock::given(method("POST")).and(path("/revoke"));
if status == 200 {
revoke = revoke.and(header("x-openai-internal-codex-residency", "us"));
}
revoke
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&fixture.server)
.await;
let signed_out_home = TempDir::new()?;
std::fs::write(
signed_out_home.path().join("config.toml"),
&fixture.user_config,
)?;
let baseline = successful_json(
fixture
.command(&["app-server", "--print-startup-config"])?
.env("CODEX_HOME", signed_out_home.path()),
)
.await?;
let sqlite_home = TempDir::new()?;
let value = successful_json(
fixture
.command(&["app-server", "--print-startup-config", "--startup-sign-out"])?
.env("CODEX_SQLITE_HOME", sqlite_home.path())
.env(
"CODEX_REVOKE_TOKEN_URL_OVERRIDE",
format!("{}/revoke", fixture.server.uri()),
),
)
.await?;
assert_eq!(value["configRequirements"], baseline["configRequirements"]);
assert_eq!(std::fs::read_dir(sqlite_home.path())?.count(), 0);
let user_config: toml::Value = toml::from_str(&std::fs::read_to_string(
fixture.codex_home.path().join("config.toml"),
)?)?;
assert!(user_config.get("model_provider").is_none());
let status = fixture.command(&["login", "status"])?.output().await?;
assert!(!status.status.success());
fixture.server.verify().await;
}
Ok(())
}
const BUNDLE: &str = "/backend-api/wham/config/bundle";
const REGISTER: &str = "/cloud/environment/test/register";
const REGISTRATION_REACHED: &str = "registration reached";
#[tokio::test]
async fn remote_exec_server_loads_cloud_provider_with_chatgpt_auth() -> Result<()> {
check_registration(
"forced_login_method = 'chatgpt'\nmodel_provider = 'cloud-provider'",
Some((
"[model_providers.cloud-provider]\nname = 'Cloud provider'\nwire_api = 'responses'",
"",
)),
"Bearer chatgpt-token",
REGISTRATION_REACHED,
&[BUNDLE, REGISTER],
)
.await
}
#[tokio::test]
async fn remote_exec_server_api_key_skips_chatgpt_cloud_config() -> Result<()> {
check_registration(
"",
/*bundle*/ None,
"Bearer test-api-key",
REGISTRATION_REACHED,
&[REGISTER],
)
.await
}
#[tokio::test]
async fn remote_exec_server_cloud_policy_denies_registration() -> Result<()> {
check_registration(
"forced_login_method = 'chatgpt'",
Some(("", "[application.network]\nenabled = true\n[application.network.domains]\n'gateway.example.com' = 'allow'")),
"Bearer chatgpt-token",
"destination denied by application network policy",
&[BUNDLE],
)
.await
}
async fn check_registration(
config: &str,
bundle: Option<(&str, &str)>,
registration_auth: &str,
expected_error: &str,
expected_paths: &[&str],
) -> Result<()> {
let fixture = CloudManagedConfigFixture::for_backend()
.await?
.context("remote registration test requires isolated mock credentials")?;
let server = &fixture.server;
if let Some((config, requirements)) = bundle {
mock_startup_bundle(server, /*status*/ 200, config, requirements).await;
}
Mock::given(method("POST"))
.and(path(REGISTER))
.and(header("authorization", registration_auth))
.respond_with(ResponseTemplate::new(400).set_body_string(REGISTRATION_REACHED))
.mount(server)
.await;
std::fs::write(
fixture.codex_home.path().join("config.toml"),
format!("{}{config}\n", fixture.user_config),
)?;
let mut command = fixture.command(&[
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"test",
])?;
command.env("CODEX_API_KEY", "test-api-key");
let output = timeout(Duration::from_secs(30), command.output()).await??;
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success() && stderr.contains(expected_error),
"{stderr}"
);
let requests = server
.received_requests()
.await
.context("mock request log")?;
let paths: Vec<_> = requests.iter().map(|request| request.url.path()).collect();
assert_eq!(paths, expected_paths);
Ok(())
}

View File

@@ -0,0 +1,633 @@
//! Exercises daemon startup and excluded resume/fork pickers with Cargo's CLI executable.
use anyhow::Context as _;
use anyhow::Result;
use anyhow::ensure;
use std::collections::VecDeque;
use std::fs;
use std::process::Command;
use std::time::Duration;
#[tokio::test]
#[cfg(unix)]
async fn auto_daemon_start_attaches_to_shared_server() -> Result<()> {
daemon_startup("start").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_can_offer_restart_for_managed_daemon() -> Result<()> {
daemon_startup("agents").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_no_daemon_uses_embedded_even_with_a_running_daemon() -> Result<()> {
daemon_startup("agents-no-daemon").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_defers_launch_directory_trust_until_starting_a_task() -> Result<()> {
daemon_startup("agents-untrusted").await
}
#[tokio::test]
#[cfg(unix)]
async fn discovered_managed_daemon_can_restart_with_auto_start_disabled() -> Result<()> {
daemon_startup("discovered").await
}
#[tokio::test]
#[cfg(unix)]
async fn incompatible_daemon_can_cancel() -> Result<()> {
daemon_startup("mismatch-cancel").await
}
#[tokio::test]
#[cfg(unix)]
async fn incompatible_daemon_can_run_embedded() -> Result<()> {
daemon_startup("mismatch-embedded").await
}
#[tokio::test]
#[cfg(unix)]
async fn incompatible_daemon_can_restart_with_confirmed_settings() -> Result<()> {
daemon_startup("mismatch-restart").await
}
#[tokio::test]
#[cfg(unix)]
async fn fresh_daemon_requires_confirmation_to_disable_shared_features() -> Result<()> {
daemon_startup("mismatch-disable").await
}
#[tokio::test]
#[cfg(unix)]
async fn stopped_daemon_requires_confirmation_to_disable_persisted_features() -> Result<()> {
daemon_startup("mismatch-disable-persisted").await
}
#[tokio::test]
async fn daemon_exclusion_survives_resume_picker() -> Result<()> {
daemon_startup("resume").await
}
#[tokio::test]
async fn daemon_exclusion_survives_fork_picker() -> Result<()> {
daemon_startup("fork").await
}
#[tokio::test]
async fn daemon_auto_start_preserves_bedrock_onboarding() -> Result<()> {
daemon_startup("bedrock").await
}
#[tokio::test]
#[cfg(windows)]
async fn elevated_local_tui_uses_embedded_without_starting_daemon() -> Result<()> {
if !codex_app_server_daemon::is_elevated()? {
eprintln!("requires an elevated Windows runner");
return Ok(());
}
for command in ["elevated", "elevated-resume", "elevated-fork"] {
daemon_startup(command).await?;
}
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
let home = tempfile::tempdir()?;
for operation in ["start", "restart"] {
let output = Command::new(&codex)
.env("CODEX_HOME", home.path())
.args(["app-server", "daemon", operation])
.output()?;
ensure!(
!output.status.success(),
"{operation} must reject elevation"
);
ensure!(
String::from_utf8_lossy(&output.stderr).contains("non-elevated terminal"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
ensure!(!home.path().join("app-server-daemon").exists());
Ok(())
}
#[tokio::test]
#[cfg(windows)]
async fn restrictive_launcher_uses_embedded_if_daemon_cannot_start() -> Result<()> {
const CHILD: &str = "CODEX_TEST_RESTRICTIVE_DAEMON_START";
if std::env::var_os(CHILD).is_some() {
// The PTY creates its own breakaway-permitted job. Add Cargo's
// restriction *inside* the PTY so it is the CLI's innermost job.
let job = codex_utils_pty::JobObject::create_without_breakaway()?;
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
let mut command = tokio::process::Command::new(codex);
command
.arg("--no-alt-screen")
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
// This interactive CLI must inherit the PTY console rather than use
// the background helper's CREATE_NO_WINDOW launch policy.
.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED)
.kill_on_drop(true);
let mut child = command.spawn()?;
ensure!(
job.assign_and_resume_process(child.id().context("missing CLI pid")?)?
.is_some(),
"CLI job assignment failed"
);
let status = child.wait().await?;
ensure!(status.success(), "CLI exited: {status}");
return Ok(());
}
daemon_startup("restrictive-job").await
}
#[tokio::test]
#[cfg(unix)]
async fn bedrock_onboarding_discovers_credentials_on_the_running_daemon() -> Result<()> {
daemon_startup("bedrock-running").await
}
async fn daemon_startup(command: &str) -> Result<()> {
#[cfg(windows)]
let elevated = codex_app_server_daemon::is_elevated()?;
#[cfg(not(windows))]
let elevated = false;
let elevated_launch = command.starts_with("elevated");
let codex = codex_utils_cargo_bin::cargo_bin("codex")?.canonicalize()?;
let workspace = tempfile::tempdir()?;
let workspace_path = workspace.path().canonicalize()?;
#[cfg(unix)]
let home = tempfile::Builder::new().tempdir_in("/tmp")?;
#[cfg(not(unix))]
let home = tempfile::tempdir()?;
// Keep cold Rosetta translation outside the timed startup assertions.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
anyhow::ensure!(
Command::new(&codex)
.env("CODEX_HOME", home.path())
.arg("--version")
.output()?
.status
.success(),
"failed to prepare CLI test executable"
);
let bedrock_onboarding = matches!(command, "bedrock" | "bedrock-running");
fs::write(
home.path().join("config.toml"),
format!(
"model = \"gpt-5.6-terra\"\n\
cli_auth_credentials_store = \"file\"\n\
suppress_unstable_features_warning = true\nanalytics.enabled = false\n\
windows.sandbox = \"unelevated\"\n\
tui.disable_paste_burst = true\n\
{}\n\
notice.model_migrations.\"gpt-5.6-terra\" = \"gpt-6-sol\"\n\
[projects.{}]\ntrust_level = \"{}\"\n",
if command == "discovered" {
"tui.status_line=[\"model\",\"thread-id\",\"thread-name\"]\nfeatures.daemon_auto_start=false"
} else if bedrock_onboarding {
"features.gcp_setup_wizard=false"
} else {
""
},
serde_json::to_string(&workspace_path)?,
if command == "agents-untrusted" {
"untrusted"
} else {
"trusted"
},
),
)?;
let mismatch = command.starts_with("mismatch-");
let persisted = command == "mismatch-disable-persisted";
let disabling = matches!(command, "mismatch-disable" | "mismatch-disable-persisted");
let restart = command == "mismatch-restart" || disabling;
if !bedrock_onboarding {
fs::write(
home.path().join("auth.json"),
r#"{"OPENAI_API_KEY":"daemon-startup-test","tokens":null,"last_refresh":null}"#,
)?;
}
let mut env = std::env::vars().collect::<std::collections::HashMap<_, _>>();
for key in [
"CODEX_EXEC_SERVER_URL",
"CODEX_ACCESS_TOKEN",
"CODEX_API_KEY",
"CODEX_CLOUD_TASKS_MODE",
"OPENAI_API_KEY",
"OPENAI_FEDERATION_RULE_ID",
"OPENAI_IDENTITY_TOKEN_FILE",
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
] {
env.remove(key);
}
env.insert("CODEX_HOME".into(), home.path().display().to_string());
env.insert(
"CODEX_SQLITE_HOME".into(),
home.path().display().to_string(),
);
env.insert("TERM".into(), "xterm-256color".into());
let mut args = vec!["--no-alt-screen".to_string()];
let mut steps: VecDeque<(&str, &[u8])> = VecDeque::new();
if matches!(
command,
"start"
| "agents"
| "agents-no-daemon"
| "agents-untrusted"
| "discovered"
| "bedrock"
| "bedrock-running"
| "restrictive-job"
) || mismatch
{
// A selected package with a stopped daemon avoids installing a release.
let managed = home
.path()
.join("packages/app-server-daemon/current/bin")
.join(if cfg!(windows) { "codex.exe" } else { "codex" });
fs::create_dir_all(home.path().join("packages/app-server-daemon/current/bin"))?;
// Hard links change the executable's ctime and invalidate Rosetta's translation cache.
#[cfg(unix)]
std::os::unix::fs::symlink(&codex, &managed)?;
#[cfg(not(unix))]
fs::hard_link(&codex, &managed)
.or_else(|_| codex_utils_cargo_bin::copy_executable(&codex, &managed))?;
if command != "restrictive-job" {
fs::create_dir(home.path().join("app-server-daemon"))?;
fs::write(
home.path().join("app-server-daemon/settings.json"),
if persisted {
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false},"featureOverrides":{"api_key_model_discovery":true}}"#
} else {
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false}}"#
},
)?;
}
}
let pid_file = home.path().join("app-server-daemon/daemon.pid");
let result = async {
let mut existing_daemon = if matches!(command, "bedrock-running" | "discovered" | "agents-no-daemon")
|| (mismatch && !disabling)
{
if command == "bedrock-running" {
// This Unix-only case uses a daemon-only token and no ambient profiles.
env.insert("AWS_CONFIG_FILE".into(), "/dev/null".into());
env.insert("AWS_SHARED_CREDENTIALS_FILE".into(), "/dev/null".into());
env.remove("AWS_ACCESS_KEY_ID");
env.remove("AWS_SECRET_ACCESS_KEY");
env.insert("AWS_BEARER_TOKEN_BEDROCK".into(), "daemon-only-test-token".into());
}
let started = Command::new(&codex)
.env_clear()
.envs(&env)
.current_dir(&workspace_path)
.args(["app-server", "daemon", "start"])
.output()?;
ensure!(
started.status.success(),
"{}",
String::from_utf8_lossy(&started.stderr)
);
Some(fs::read(&pid_file)?)
} else {
None
};
let expected = if command == "start" {
// The draft header is visible before the session's command composer is ready.
steps.push_back(("GPT-5.6-Terra", b"/status\r"));
"Server:Localbackgroundserver"
} else if command == "agents-no-daemon" {
args.extend(["agents".into(), "--no-daemon".into()]);
steps.push_back(("Notasksyet", b"n"));
steps.push_back(("GPT-5.6-Terra", b"/daemon\r"));
"Notconnectedtothelocalbackgroundserver"
} else if command == "agents" {
args.push("agents".into());
steps.push_back(("Notasksyet", b"n"));
steps.push_back(("GPT-5.6-Terra", b"/daemon\r"));
steps.push_back(("Restartbackgroundserver", b"\x1b[F\r"));
"Restartbackgroundserver?"
} else if command == "agents-untrusted" {
args.push("agents".into());
steps.push_back(("Notasksyet", b"n"));
"entercontinue·escback"
} else if command == "discovered" {
args.extend(["--disable".into(), "daemon_auto_start".into()]);
// Empty drafts need not survive a daemon restart. Renaming materializes the
// thread; wait for the confirmed footer name, not the echoed command.
steps.push_back(("GPT-5.6-Terra", b"/rename daemon-restart-test\r"));
steps.push_back(("·daemon-restart-test", b"/daemon\r"));
steps.push_back(("Restartbackgroundserver", b"2"));
steps.push_back(("Restartbackgroundserver?", b"2\r"));
// Offline editing preserves text but suppresses Enter. Observe the command
// popup in a complete connected frame before submitting the retained draft.
steps.push_back(("GPT-5.6-Terra", b"/status"));
steps.push_back(("/statusshowcurrentsessionconfigurationandtokenusage", b"\r"));
"Server:Localbackgroundserver"
} else if elevated_launch || command == "restrictive-job" && elevated {
if let Some(action) = command.strip_prefix("elevated-") {
args.push(action.into());
steps.push_back(("Nosessionsyet", b"\x1b"));
}
steps.push_back(("GPT-5.6-Terra", b"\x14"));
"Runningasadministrator:sharedbackgroundserverdisabled."
} else if command == "restrictive-job" {
steps.push_back(("GPT-5.6-Terra", b"\x14"));
"Runningwithoutthesharedbackgroundserver:thisWindowslauncher"
} else if mismatch {
args.extend(if disabling && !persisted {
["--disable".into(), "auth_elicitation".into()]
} else {
["--disable".into(), "api_key_model_discovery".into()]
});
let input: &[u8] = match command {
"mismatch-cancel" => b"\x03",
"mismatch-embedded" => b"1",
"mismatch-restart" | "mismatch-disable" | "mismatch-disable-persisted" => b"2\r",
_ => unreachable!(),
};
steps.push_back(("Backgroundserverhasincompatiblefeaturesettings", input));
if command == "mismatch-cancel" {
"--no-daemon"
} else {
steps.push_back(("GPT-5.6-Terra", b"/status\r"));
if restart { "Server:Localbackgroundserver" } else { "Model:" }
}
} else if command == "bedrock-running" {
env.remove("AWS_BEARER_TOKEN_BEDROCK");
steps.push_back(("UseanAPIkeyoranotherprovider", b"3"));
steps.push_back(("UseAmazonBedrock", b"2"));
"Continuewithdetectedcredentials"
} else if bedrock_onboarding {
// With GCP disabled, only Bedrock makes the sign-in menu advertise another provider.
"UseanAPIkeyoranotherprovider"
} else {
args.extend([command.into(), "--strict-config".into()]);
if command == "resume" {
let thread_id = "00000000-0000-0000-0000-000000000001";
let sessions = home.path().join("sessions/2025/01/05");
fs::create_dir_all(&sessions)?;
let metadata = serde_json::json!({
"timestamp": "2025-01-05T12:00:00Z",
"type": "session_meta",
"payload": {
"session_id": thread_id, "id": thread_id,
"timestamp": "2025-01-05T12:00:00Z", "cwd": workspace_path,
"originator": "codex", "cli_version": "0.0.0",
"source": "cli", "model_provider": "openai"
}
});
let message = serde_json::json!({
"timestamp": "2025-01-05T12:00:00Z",
"type": "event_msg",
"payload": {"type": "user_message", "message": "Saved resume session", "kind": "plain"}
});
fs::write(
sessions.join(format!("rollout-2025-01-05T12-00-00-{thread_id}.jsonl")),
format!("{metadata}\n{message}\n"),
)?;
steps.push_back(("Savedresumesession", b"\r"));
} else {
steps.push_back(("Nosessionsyet", b"\x1b"));
}
steps.push_back(("GPT-5.6-Terra", b"\x14"));
if elevated {
"Runningasadministrator:sharedbackgroundserverdisabled."
} else {
"Runningwithoutthesharedbackgroundserver:--strict-config"
}
};
let program = if cfg!(windows) && command == "restrictive-job" {
env.insert("CODEX_TEST_RESTRICTIVE_DAEMON_START".into(), "1".into());
args = vec![
"--exact".into(),
"restrictive_launcher_uses_embedded_if_daemon_cannot_start".into(),
"--nocapture".into(),
];
std::env::current_exe()?
} else {
codex.clone()
};
let spawned = codex_utils_pty::spawn_pty_process(
&program.to_string_lossy(),
&args,
&workspace_path,
&env,
/*arg0*/ &None,
codex_utils_pty::TerminalSize {
rows: 40,
cols: 120,
},
codex_utils_pty::ChildFds::Inherited(&[]),
)
.await?;
let exit = spawned.exit_rx;
let session = spawned.session;
let writer = session.writer_sender();
let mut stdout = spawned.stdout_rx;
let mut output = String::new();
let mut initial_agents_screen = String::new();
let mut screen = vt100::Parser::new(
/*rows*/ 40, /*cols*/ 120, /*scrollback_len*/ 0,
);
let mut queries: Vec<(&str, &[u8])> = vec![
("\x1b[6n", b"\x1b[1;1R"),
("\x1b[?u", b"\x1b[?0u\x1b[?1;2c"),
("\x1b[c", b"\x1b[?1;2c"),
("\x1b]10;?", b"\x1b]10;rgb:ffff/ffff/ffff\x1b\\"),
("\x1b]11;?", b"\x1b]11;rgb:0000/0000/0000\x1b\\"),
];
// A fresh disable request includes both cold daemon startup and its confirmed restart.
let timeout = Duration::from_secs(if disabling { 90 } else { 45 });
let result = tokio::time::timeout(timeout, async {
loop {
let bytes = tokio::select! {
bytes = stdout.recv() => bytes,
// The first onboarding draw precedes its typeahead drain. Retry the
// main menu shortcut until the submenu appears (it has no option 3).
() = tokio::time::sleep(Duration::from_millis(/*millis*/ 250)),
if steps.front().is_some_and(|(ready, _)| *ready == "UseAmazonBedrock") => {
writer.send(b"3".to_vec()).await?;
continue;
}
};
let Some(bytes) = bytes else { break };
output.push_str(&String::from_utf8_lossy(&bytes));
screen.process(&bytes);
for (query, reply) in &mut queries {
if !query.is_empty() && output.contains(*query) {
writer.send(reply.to_vec()).await?;
*query = "";
}
}
// PTY reads can split a redraw after the reconnect notice is erased but
// before it is repainted. Only inspect completed synchronized updates.
if command == "discovered"
&& output
.rfind("\x1b[?2026l")
.is_none_or(|end| output[end..].contains("\x1b[?2026h"))
{
continue;
}
let text: String = screen
.screen()
.contents()
.chars()
.filter(|c| !c.is_whitespace())
.collect();
if let Some((ready, input)) = steps.front()
&& text.contains(ready)
{
if command == "agents-untrusted" && *ready == "Notasksyet" {
if !text.contains("enteropennnew") {
continue;
}
initial_agents_screen = screen.screen().contents();
}
if command == "discovered" {
if *ready == "Restartbackgroundserver?" {
existing_daemon = Some(fs::read(&pid_file)?);
} else if *ready == "GPT-5.6-Terra" {
// The header renders before thread/start completes. Wait for the
// live status line to confirm there is a session to reconnect.
if !screen.screen().contents().split_whitespace().any(|part| {
codex_protocol::ThreadId::from_string(part).is_ok()
}) {
continue;
}
}
// A replacement PID can appear before the TUI observes the disconnect.
// Wait for reconnect to clear/rebuild the transcript, so the old
// composer's command popup cannot make the status probe look ready.
if *input == b"/status" && !output.contains("\x1b[3J") {
continue;
}
// The old header can linger while the daemon stops. Check both
// the draft and its Enter against the replacement process and UI.
if (*input == b"/status" || *input == b"\r")
&& (!fs::read(&pid_file).is_ok_and(|pid| Some(pid) != existing_daemon)
|| text.contains("Reconnecting"))
{
continue;
}
}
if disabling && *ready == "Backgroundserverhasincompatiblefeaturesettings" {
existing_daemon = Some(fs::read(&pid_file)?);
let settings: serde_json::Value = serde_json::from_slice(&fs::read(home.path().join("app-server-daemon/settings.json"))?)?;
if persisted {
ensure!(settings["featureOverrides"]["api_key_model_discovery"] == true);
} else {
ensure!(settings["featureOverrides"]["auth_elicitation"].is_null());
}
}
writer.send(input.to_vec()).await?;
steps.pop_front();
output.clear();
} else if steps.is_empty() && text.contains(expected) {
if command == "agents-untrusted" {
let transition = format!(
"{initial_agents_screen}\n\n--- Start a task ---\n\n{}",
screen.screen().contents()
)
.replace(&*workspace_path.to_string_lossy(), "[WORKSPACE]")
.replace(&*home.path().to_string_lossy(), "[CODEX_HOME]")
.replace(" tab/⇧tab filter", "tab/shift+tab filter");
let transition = transition.lines().map(str::trim_end).collect::<Vec<_>>().join("\n");
let snapshot = codex_utils_cargo_bin::find_resource!(
"tests/snapshots/daemon_startup__agents_overview_before_folder_consent.snap"
)?;
insta::with_settings!({snapshot_path => snapshot.parent().context("snapshot has no parent")?}, {
insta::assert_snapshot!("agents_overview_before_folder_consent", transition);
});
}
if mismatch {
let previous_pid = existing_daemon.as_ref().context("missing original daemon PID")?;
ensure!((fs::read(&pid_file)? != *previous_pid) == restart);
if command == "mismatch-cancel" {
ensure!(text.contains("Cannotusethesharedbackgroundserver:Thissessionrequiresapi_key_model_discoverytobedisabled."));
} else {
ensure!(text.contains("Server:Localbackgroundserver") == restart);
if restart {
let settings: serde_json::Value = serde_json::from_slice(
&fs::read(home.path().join("app-server-daemon/settings.json"))?
)?;
let flag = if disabling && !persisted {
"auth_elicitation"
} else {
"api_key_model_discovery"
};
assert_eq!(settings["featureOverrides"], serde_json::json!({(flag): false}));
}
}
} else if command == "start" {
ensure!(text.contains("Server:Localbackgroundserver"));
ensure!(home.path().join("app-server-daemon/daemon.pid").exists());
} else if command == "discovered" {
let previous_pid = existing_daemon.as_ref().context("missing original daemon PID")?;
ensure!(fs::read(&pid_file)? != *previous_pid, "daemon PID did not change");
} else if let Some(existing_daemon) = &existing_daemon {
ensure!(fs::read(&pid_file)? == *existing_daemon);
} else if elevated_launch {
ensure!(!home.path().join("app-server-daemon").exists());
ensure!(!home.path().join("packages/app-server-daemon").exists());
} else if bedrock_onboarding {
ensure!(pid_file.exists() != elevated);
} else if command == "restrictive-job" {
ensure!(!pid_file.exists());
if !elevated {
let contents = screen.screen().contents();
let warning = contents.lines()
.find(|line| line.contains("Running without the shared background server:"))
.context("missing rendered fallback warning")?;
insta::assert_snapshot!("restrictive_launcher_warning", warning.trim());
}
}
return Ok::<_, anyhow::Error>(());
}
}
anyhow::bail!(
"TUI exited before {expected}: {}",
screen.screen().contents()
)
})
.await;
if command == "mismatch-cancel" && matches!(result, Ok(Ok(()))) {
let status = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), exit).await??;
ensure!(status != 0, "incompatible daemon launch must fail");
}
Ok::<_, anyhow::Error>((
session,
result.with_context(|| format!("{command} timed out waiting for {}: {}", steps.front().map_or(expected, |(ready, _)| *ready), screen.screen().contents())),
))
}
.await;
// Elevated fresh Bedrock onboarding already verified that no daemon started.
if elevated
&& command == "bedrock"
&& let Ok((session, Ok(Ok(())))) = &result
{
session.terminate();
return Ok(());
}
// Stop the detached daemon, including on timeout or failed assertions.
let stopped = Command::new(&codex)
.env_clear()
.envs(&env)
.args(["app-server", "daemon", "stop"])
.output()?;
let (session, result) = result?;
session.terminate();
result??;
ensure!(
stopped.status.success(),
"{}",
String::from_utf8_lossy(&stopped.stderr)
);
Ok(())
}

View File

@@ -0,0 +1,77 @@
//! Foreground updates honor explicit metrics exporters and never claim unconfirmed installation.
use anyhow::Context as _;
use pretty_assertions::assert_eq;
use serde_json::Value;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
#[tokio::test]
async fn foreground_update_honors_metrics_exporter_and_reports_unconfirmed() -> anyhow::Result<()> {
for (analytics_config, analytics_default_enabled, metrics_enabled) in [
("", false, true),
("", true, true),
("analytics.enabled = true\n", false, true),
("analytics.enabled = false\n", true, true),
("analytics.enabled = true\n", true, false),
] {
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
let server = MockServer::start().await;
Mock::given(wiremock::matchers::path("/metrics"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.await;
let home = tempfile::tempdir()?;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\n{analytics_config}[otel]\nmetrics_exporter = {{ otlp-http = {{ endpoint = \"{}/metrics\", protocol = \"json\" }} }}\n",
server.uri(),
),
)?;
// No managed installation exists, so the command cannot confirm an applied update.
let mut command = tokio::process::Command::new(&codex);
command
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove(codex_app_server_daemon::telemetry::HANDOFF_ENV)
.arg("app-server");
if analytics_default_enabled {
command.arg("--analytics-default-enabled");
}
if !metrics_enabled {
command.args(["-c", "otel.metrics_exporter=\"none\""]);
}
let output = command
.args(["daemon", "update", "--from-cli", "--yes"])
.output()
.await?;
assert!(!output.status.success());
let requests = server
.received_requests()
.await
.context("metric requests")?;
assert_eq!(requests.len(), usize::from(metrics_enabled));
if !metrics_enabled {
continue;
}
let body: Value = serde_json::from_slice(&requests[0].body)?;
let metric = body["resourceMetrics"]
.as_array()
.into_iter()
.flatten()
.flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten())
.flat_map(|scope| scope["metrics"].as_array().into_iter().flatten())
.find(|metric| metric["name"] == "codex.daemon.update")
.context("daemon update metric")?;
assert!(
metric["sum"]["dataPoints"][0]["attributes"]
.as_array()
.context("metric attributes")?
.iter()
.any(|tag| tag["key"] == "outcome" && tag["value"]["stringValue"] == "unconfirmed")
);
}
Ok(())
}

View File

@@ -0,0 +1,185 @@
use std::path::Path;
use anyhow::Result;
use codex_state::StateRuntime;
use codex_utils_absolute_path::test_support::PathExt;
use predicates::str::contains;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
cmd.env("CODEX_HOME", codex_home);
Ok(cmd)
}
#[tokio::test]
async fn debug_clear_memories_resets_state_and_removes_memory_dir() -> Result<()> {
let codex_home = TempDir::new()?;
let sqlite = codex_state::SqliteConfig::new_for_testing(codex_home.path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
runtime.close().await;
let thread_id = "00000000-0000-0000-0000-000000000123";
let db_path = sqlite.state_db_path();
let pool = sqlite.open_read_write_pool(&db_path).await?;
let memories_db_path = sqlite.memories_db_path();
let memories_pool = sqlite.open_read_write_pool(&memories_db_path).await?;
sqlx::query(
r#"
INSERT INTO threads (
id,
rollout_path,
created_at,
updated_at,
source,
agent_nickname,
agent_role,
model_provider,
cwd,
cli_version,
title,
sandbox_policy,
approval_mode,
tokens_used,
first_user_message,
archived,
archived_at,
git_sha,
git_branch,
git_origin_url,
memory_mode
) VALUES (?, ?, 1, 1, 'cli', NULL, NULL, 'test-provider', ?, '', '', 'read-only', 'on-request', 0, '', 0, NULL, NULL, NULL, NULL, 'enabled')
"#,
)
.bind(thread_id)
.bind(codex_home.path().join("session.jsonl").display().to_string())
.bind(codex_home.path().display().to_string())
.execute(&pool)
.await?;
sqlx::query(
r#"
INSERT INTO stage1_outputs (
thread_id,
source_updated_at,
raw_memory,
rollout_summary,
generated_at,
rollout_slug,
usage_count,
last_usage,
selected_for_phase2,
selected_for_phase2_source_updated_at
) VALUES (?, 1, 'raw', 'summary', 1, NULL, 0, NULL, 0, NULL)
"#,
)
.bind(thread_id)
.execute(&memories_pool)
.await?;
sqlx::query(
r#"
INSERT INTO jobs (
kind,
job_key,
status,
worker_id,
ownership_token,
started_at,
finished_at,
lease_until,
retry_at,
retry_remaining,
last_error,
input_watermark,
last_success_watermark
) VALUES
('memory_stage1', ?, 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1),
('memory_consolidate_global', 'global', 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1)
"#,
)
.bind(thread_id)
.execute(&memories_pool)
.await?;
let memory_root = codex_home.path().join("memories");
std::fs::create_dir_all(&memory_root)?;
std::fs::write(memory_root.join("memory_summary.md"), "stale memory")?;
pool.close().await;
memories_pool.close().await;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["debug", "clear-memories"])
.assert()
.success()
.stdout(contains("Cleared memory state"));
let pool = sqlite.open_read_write_pool(&memories_db_path).await?;
let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs")
.fetch_one(&pool)
.await?;
assert_eq!(stage1_outputs_count, 0);
let memory_jobs_count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM jobs WHERE kind = 'memory_stage1' OR kind = 'memory_consolidate_global'",
)
.fetch_one(&pool)
.await?;
assert_eq!(memory_jobs_count, 0);
assert!(memory_root.exists());
assert_eq!(std::fs::read_dir(memory_root)?.count(), 0);
pool.close().await;
Ok(())
}
#[tokio::test]
async fn debug_clear_memories_resets_memories_db_without_state_db() -> Result<()> {
let codex_home = TempDir::new()?;
let sqlite = codex_state::SqliteConfig::new_for_testing(codex_home.path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
runtime.close().await;
let db_path = sqlite.state_db_path();
let memories_db_path = sqlite.memories_db_path();
let memories_pool = sqlite.open_read_write_pool(&memories_db_path).await?;
sqlx::query(
r#"
INSERT INTO stage1_outputs (
thread_id,
source_updated_at,
raw_memory,
rollout_summary,
generated_at,
rollout_slug,
usage_count,
last_usage,
selected_for_phase2,
selected_for_phase2_source_updated_at
) VALUES ('00000000-0000-0000-0000-000000000123', 1, 'raw', 'summary', 1, NULL, 0, NULL, 0, NULL)
"#,
)
.execute(&memories_pool)
.await?;
memories_pool.close().await;
std::fs::remove_file(&db_path)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["debug", "clear-memories"])
.assert()
.success()
.stdout(contains("Cleared memory state"));
let pool = sqlite.open_read_write_pool(&memories_db_path).await?;
let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs")
.fetch_one(&pool)
.await?;
assert_eq!(stage1_outputs_count, 0);
pool.close().await;
assert!(!db_path.exists());
Ok(())
}

View File

@@ -0,0 +1,40 @@
use std::path::Path;
use anyhow::Result;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
cmd.env("CODEX_HOME", codex_home);
Ok(cmd)
}
#[test]
fn debug_models_bundled_prints_json() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models", "--bundled"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}
#[test]
fn debug_models_default_prints_json_without_auth() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}

View File

@@ -0,0 +1,17 @@
use predicates::prelude::*;
#[test]
fn missing_session_fails_before_delete_confirmation() -> anyhow::Result<()> {
let codex_home = tempfile::tempdir()?;
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
cmd.env("CODEX_HOME", codex_home.path())
.args(["delete", "123e4567-e89b-12d3-a456-426614174000"]);
cmd.assert()
.failure()
.stderr(predicate::str::contains(
"No active or archived session found matching",
))
.stderr(predicate::str::contains("cannot confirm").not());
Ok(())
}

View File

@@ -0,0 +1,463 @@
#[cfg(target_os = "macos")]
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use anyhow::Context as _;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::types::AuthCredentialsStoreMode;
use codex_state::SqliteConfig;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use regex_lite::Regex;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
async fn local_provider() -> Result<(MockServer, TempDir)> {
let server = MockServer::start().await;
for (request_method, request_path, status) in
[("HEAD", "/v1/responses", 200), ("GET", "/v1/models", 401)]
{
Mock::given(method(request_method))
.and(path(request_path))
.respond_with(ResponseTemplate::new(status).insert_header("x-request-id", "fixture-id"))
.mount(&server)
.await;
}
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"ephemeral\"\ncheck_for_update_on_startup = false\nmodel_provider = \"local\"\n[model_providers.local]\nname = \"local\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\n",
server.uri()
),
)?;
Ok((server, home))
}
fn local_command(home: &TempDir) -> Result<Command> {
let mut command = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.stdin(Stdio::null());
for name in [
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"http_proxy",
"https_proxy",
"all_proxy",
"CODEX_ACCESS_TOKEN",
"CODEX_API_KEY",
"OPENAI_API_KEY",
"CODEX_CA_CERTIFICATE",
"SSL_CERT_FILE",
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
"OPENAI_IDENTITY_TOKEN_FILE",
"OPENAI_FEDERATION_RULE_ID",
] {
command.env_remove(name);
}
Ok(command)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_selects_checks_without_database_or_mcp_scans() -> Result<()> {
let (server, home) = local_provider().await?;
Mock::given(path("/unrelated-mcp"))
.respond_with(ResponseTemplate::new(200))
.expect(0)
.mount(&server)
.await;
let sqlite =
SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(home.path().to_path_buf())?);
let database = sqlite.logs_db_path();
std::fs::write(&database, "not a SQLite database")?;
let mcp_url = format!("{}/unrelated-mcp", server.uri());
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json", "--all", "--feedback"])
.arg("-c")
.arg(format!("mcp_servers.unrelated.url={mcp_url:?}"))
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert!(output.status.success(), "{report:#}");
let checks = report["checks"].as_object().unwrap();
assert_eq!(
checks.keys().map(String::as_str).collect::<Vec<_>>(),
vec![
"config.load",
"network.env",
"network.provider_reachability",
"network.websocket_reachability",
]
);
assert_eq!(std::fs::read_to_string(database)?, "not a SQLite database");
server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_reports_recoverable_config_warnings_and_effective_config() -> Result<()> {
let (_server, home) = local_provider().await?;
let baseline_output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
.output()?;
let baseline_report: Value = serde_json::from_slice(&baseline_output.stdout)?;
assert!(baseline_output.status.success(), "{baseline_report:#}");
let baseline_warning_count =
baseline_report["checks"]["config.load"]["details"]["startup warnings"]
.as_str()
.unwrap_or("0")
.parse::<usize>()?;
let config_path = home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
config_path,
format!("{config}\n[otel.span_attributes]\n\"\" = \"missing-key\"\n"),
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert!(output.status.success(), "{report:#}");
let config_check = &report["checks"]["config.load"];
let warning_count = config_check["details"]["startup warnings"]
.as_str()
.context("missing startup-warning count")?
.parse::<usize>()?;
let warnings = &config_check["details"]["startup warning"];
let startup_warning = std::iter::once(warnings)
.chain(warnings.as_array().into_iter().flatten())
.filter_map(Value::as_str)
.find(|warning| warning.starts_with("Ignoring invalid `otel.span_attributes` config"))
.context("missing recoverable OTEL config warning")?;
let check_statuses = report["checks"]
.as_object()
.unwrap()
.iter()
.map(|(id, check)| (id.clone(), check["status"].clone()))
.collect::<serde_json::Map<_, _>>();
assert_eq!(
json!({
"overallStatus": report["overallStatus"],
"checkStatuses": check_statuses,
"config": {
"summary": config_check["summary"],
"scope": config_check["details"]["configuration scope"],
"provider": config_check["details"]["model provider"],
"startupWarnings": warning_count,
"startupWarning": startup_warning,
},
}),
json!({
"overallStatus": "warning",
"checkStatuses": {
"config.load": "warning",
"network.env": "ok",
"network.provider_reachability": "ok",
"network.websocket_reachability": "ok",
},
"config": {
"summary": "config loaded",
"scope": "invocation config, including cloud-managed policy",
"provider": "local",
"startupWarnings": baseline_warning_count + 1,
"startupWarning": "Ignoring invalid `otel.span_attributes` config: configured span attribute key must not be empty",
},
})
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_config_failure_does_not_guess_probe_targets() -> Result<()> {
let proxy = MockServer::start().await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"model_provider = sk-config-credential-fixture\n",
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
.env("HTTP_PROXY", proxy.uri())
.env("HTTPS_PROXY", proxy.uri())
.output()?;
assert_eq!(output.status.code(), Some(1));
assert!(!String::from_utf8_lossy(&output.stdout).contains("sk-config-credential-fixture"));
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(report["checks"].as_object().unwrap().len(), 1);
assert_eq!(report["checks"]["config.load"]["status"], "fail");
assert_eq!(
report["checks"]["config.load"]["details"]["network diagnostics"],
"effective network configuration is unavailable"
);
assert!(proxy.received_requests().await.unwrap().is_empty());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_human_output() -> Result<()> {
let (_server, home) = local_provider().await?;
let output = local_command(&home)?
.args([
"doctor",
"--network-only",
"--summary",
"--ascii",
"--no-color",
])
.output()?;
let stdout = String::from_utf8(output.stdout)?;
assert!(output.status.success(), "{stdout}");
insta::assert_snapshot!("network_only_human_output", stdout);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_config_failure_human_output() -> Result<()> {
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"model_provider = sk-config-credential-fixture\n",
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--all", "--ascii", "--no-color"])
.output()?;
let stdout = String::from_utf8(output.stdout)?;
assert_eq!(output.status.code(), Some(1));
assert!(!stdout.contains("sk-config-credential-fixture"));
// Config loading may canonicalize the directory, rendering may shorten it,
// and Windows uses backslashes.
// Normalize the rendered config-file row while retaining its label and filename.
let file_row = Regex::new(r"(?m)^( file +).+[\\/]config\.toml$")?;
assert!(file_row.is_match(&stdout), "{stdout}");
let stdout = file_row.replace_all(&stdout, "${1}<CODEX_HOME>/config.toml");
insta::assert_snapshot!("network_only_config_failure_human_output", stdout);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn doctor_reports_cloud_filesystem_policy_and_rejects_invalid_requirements() -> Result<()> {
for valid_requirements in [true, false] {
let server = MockServer::start().await;
let codex_home = TempDir::new()?;
let workspace = TempDir::new()?;
let workspace_key = serde_json::to_string(workspace.path())?;
let private_path = workspace.path().join("private-doctor-control");
let glob = format!("{}/**/*.doctor-secret", workspace.path().display());
let requirements = if valid_requirements {
format!("[permissions.filesystem]\ndeny_read = [{private_path:?}, {glob:?}]\n")
} else {
"[permissions.filesystem]\ndeny_read = false\n".to_string()
};
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
cli_auth_credentials_store = "ephemeral"
chatgpt_base_url = "{}/backend-api"
model_provider = "local"
[model_providers.local]
name = "local"
base_url = "{}/v1"
wire_api = "responses"
[windows]
sandbox = "elevated"
[projects.{workspace_key}]
trust_level = "trusted"
"#,
server.uri(),
server.uri(),
),
)?;
// Cloud authentication must use the project selected by --cd.
std::fs::create_dir(workspace.path().join(".codex"))?;
std::fs::write(
workspace.path().join(".codex/config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("doctor-test-token")
.account_id("doctor-workspace")
.chatgpt_account_id("doctor-workspace")
.chatgpt_user_id("doctor-user")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"requirements_toml": {
"enterprise_managed": [{
"id": "doctor-policy",
"name": "Doctor policy fixture",
"contents": requirements,
}],
},
})))
.expect(1)
.mount(&server)
.await;
let output = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.current_dir(codex_home.path())
.env("CODEX_HOME", codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.arg("--cd")
.arg(workspace.path())
.args(["doctor", "--json"])
.stdin(Stdio::null())
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
if valid_requirements {
let config = &report["checks"]["config.load"];
let sandbox = &report["checks"]["sandbox.helpers"]["details"];
assert_eq!(config["status"], "ok", "{config:#}");
assert_eq!(
config["details"]["cwd"],
workspace.path().display().to_string()
);
insta::assert_snapshot!(
serde_json::to_string_pretty(&json!({
"scope": config["details"]["configuration scope"],
"activeThreadOverrides": config["details"]["active thread overrides"],
"denyRules": sandbox["denied-read rules"],
"denyGlobs": sandbox["denied-read glob rules"],
"scanDepth": sandbox["glob scan max depth"],
"managedFilesystemSource": sandbox["managed filesystem source"],
}))?,
@r#"
{
"scope": "invocation config, including cloud-managed policy",
"activeThreadOverrides": "not inspected",
"denyRules": "2",
"denyGlobs": "1",
"scanDepth": "unbounded",
"managedFilesystemSource": "cloud"
}
"#
);
let stdout = String::from_utf8(output.stdout)?;
assert!(!stdout.contains("doctor-secret"));
assert!(!stdout.contains("private-doctor-control"));
} else {
assert_eq!(report["checks"]["config.load"]["status"], "fail");
assert!(report["checks"].get("sandbox.helpers").is_none());
}
server.verify().await;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn invalid_custom_ca_falls_back_to_system_roots() -> Result<()> {
let server = MockServer::start().await;
for (request_method, request_path) in [("HEAD", "/v1/responses"), ("GET", "/v1/models")] {
Mock::given(method(request_method))
.and(path(request_path))
.respond_with(ResponseTemplate::new(200))
.expect(2)
.mount(&server)
.await;
}
let codex_home = TempDir::new()?;
let certificate = codex_home.path().join("invalid-ca.pem");
std::fs::write(&certificate, "not a certificate")?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"model_provider = \"local\"\n[model_providers.local]\nname = \"local\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\n",
server.uri()
),
)?;
for sandbox in [None, Some("seatbelt")] {
let mut command = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.args(["doctor", "--json"])
.env("CODEX_HOME", codex_home.path())
.env("CODEX_CA_CERTIFICATE", &certificate)
.stdin(Stdio::null());
if let Some(sandbox) = sandbox {
command
.env("CODEX_SANDBOX", sandbox)
.env("HTTP_PROXY", "http://127.0.0.1:1")
.env("http_proxy", "http://127.0.0.1:1")
.env("HTTPS_PROXY", "http://127.0.0.1:1")
.env("https_proxy", "http://127.0.0.1:1")
.env("NO_PROXY", "")
.env("no_proxy", "");
} else {
command
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost");
}
let output = command
.output()
.context("failed to run the doctor with an invalid custom CA")?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert!(
report["checks"]["network.provider_reachability"]["details"]["local API inference URL"]
.as_str()
.is_some_and(|detail| detail.ends_with("reachable (HTTP 200)"))
);
}
server.verify().await;
Ok(())
}
#[cfg(target_os = "macos")]
#[test]
fn doctor_reports_macos_system_proxy_configuration_and_policy() -> Result<()> {
let codex_home = TempDir::new()?;
let report = doctor_report(codex_home.path())?;
let details = &report["checks"]["network.env"]["details"];
assert_eq!(details["respect system proxy"], json!("disabled"));
assert!(matches!(
details["system proxy"].as_str(),
Some("automatic (PAC)" | "manual" | "direct" | "unavailable")
));
std::fs::write(
codex_home.path().join("config.toml"),
"[features]\nrespect_system_proxy = true\n",
)?;
let report = doctor_report(codex_home.path())?;
assert_eq!(
report["checks"]["network.env"]["details"]["respect system proxy"],
json!("enabled")
);
Ok(())
}
#[cfg(target_os = "macos")]
fn doctor_report(codex_home: &Path) -> Result<Value> {
let output = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.args(["doctor", "--json"])
.env("CODEX_HOME", codex_home)
.stdin(Stdio::null())
.output()
.context("failed to run the doctor")?;
serde_json::from_slice(&output.stdout).context("doctor did not emit a valid json report")
}

Some files were not shown because too many files have changed in this diff Show More