Base: codex-main originale (prima del fork aKode)
This commit is contained in:
365
codex-rs/cli/src/doctor/background.rs
Normal file
365
codex-rs/cli/src/doctor/background.rs
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
320
codex-rs/cli/src/doctor/desktop.rs
Normal file
320
codex-rs/cli/src/doctor/desktop.rs
Normal 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()
|
||||
}
|
||||
236
codex-rs/cli/src/doctor/desktop/macos_security.rs
Normal file
236
codex-rs/cli/src/doctor/desktop/macos_security.rs
Normal 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;
|
||||
67
codex-rs/cli/src/doctor/desktop/macos_security_tests.rs
Normal file
67
codex-rs/cli/src/doctor/desktop/macos_security_tests.rs
Normal 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))
|
||||
);
|
||||
}
|
||||
}
|
||||
283
codex-rs/cli/src/doctor/desktop/platform.rs
Normal file
283
codex-rs/cli/src/doctor/desktop/platform.rs
Normal 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,
|
||||
}))
|
||||
}
|
||||
232
codex-rs/cli/src/doctor/desktop/windows_security.rs
Normal file
232
codex-rs/cli/src/doctor/desktop/windows_security.rs
Normal 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;
|
||||
85
codex-rs/cli/src/doctor/desktop/windows_security_tests.rs
Normal file
85
codex-rs/cli/src/doctor/desktop/windows_security_tests.rs
Normal 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>"
|
||||
)
|
||||
}
|
||||
97
codex-rs/cli/src/doctor/desktop_tests.rs
Normal file
97
codex-rs/cli/src/doctor/desktop_tests.rs
Normal 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");
|
||||
}
|
||||
178
codex-rs/cli/src/doctor/disk.rs
Normal file
178
codex-rs/cli/src/doctor/disk.rs
Normal 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;
|
||||
160
codex-rs/cli/src/doctor/disk_tests.rs
Normal file
160
codex-rs/cli/src/doctor/disk_tests.rs
Normal 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()]
|
||||
);
|
||||
}
|
||||
385
codex-rs/cli/src/doctor/filesystem_paths.rs
Normal file
385
codex-rs/cli/src/doctor/filesystem_paths.rs
Normal 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;
|
||||
286
codex-rs/cli/src/doctor/filesystem_paths_tests.rs
Normal file
286
codex-rs/cli/src/doctor/filesystem_paths_tests.rs
Normal 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()
|
||||
)
|
||||
);
|
||||
}
|
||||
160
codex-rs/cli/src/doctor/git.rs
Normal file
160
codex-rs/cli/src/doctor/git.rs
Normal 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,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
224
codex-rs/cli/src/doctor/network.rs
Normal file
224
codex-rs/cli/src/doctor/network.rs
Normal 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;
|
||||
37
codex-rs/cli/src/doctor/network_tests.rs
Normal file
37
codex-rs/cli/src/doctor/network_tests.rs
Normal 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)")
|
||||
);
|
||||
}
|
||||
2017
codex-rs/cli/src/doctor/output.rs
Normal file
2017
codex-rs/cli/src/doctor/output.rs
Normal file
File diff suppressed because it is too large
Load Diff
791
codex-rs/cli/src/doctor/output/detail.rs
Normal file
791
codex-rs/cli/src/doctor/output/detail.rs
Normal 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" | "—" | "-"
|
||||
)
|
||||
}
|
||||
139
codex-rs/cli/src/doctor/progress.rs
Normal file
139
codex-rs/cli/src/doctor/progress.rs
Normal 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,
|
||||
));
|
||||
}
|
||||
}
|
||||
145
codex-rs/cli/src/doctor/runtime.rs
Normal file
145
codex-rs/cli/src/doctor/runtime.rs
Normal 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")
|
||||
}
|
||||
357
codex-rs/cli/src/doctor/sandbox.rs
Normal file
357
codex-rs/cli/src/doctor/sandbox.rs
Normal 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;
|
||||
160
codex-rs/cli/src/doctor/sandbox_tests.rs
Normal file
160
codex-rs/cli/src/doctor/sandbox_tests.rs
Normal 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());
|
||||
}
|
||||
254
codex-rs/cli/src/doctor/security.rs
Normal file
254
codex-rs/cli/src/doctor/security.rs
Normal 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;
|
||||
184
codex-rs/cli/src/doctor/security_tests.rs
Normal file
184
codex-rs/cli/src/doctor/security_tests.rs
Normal 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);
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
182
codex-rs/cli/src/doctor/system.rs
Normal file
182
codex-rs/cli/src/doctor/system.rs
Normal 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",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
1434
codex-rs/cli/src/doctor/thread_inventory.rs
Normal file
1434
codex-rs/cli/src/doctor/thread_inventory.rs
Normal file
File diff suppressed because it is too large
Load Diff
424
codex-rs/cli/src/doctor/title.rs
Normal file
424
codex-rs/cli/src/doctor/title.rs
Normal 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())
|
||||
);
|
||||
}
|
||||
}
|
||||
711
codex-rs/cli/src/doctor/updates.rs
Normal file
711
codex-rs/cli/src/doctor/updates.rs
Normal 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"
|
||||
);
|
||||
}
|
||||
}
|
||||
160
codex-rs/cli/src/doctor/windows_dev_drive.rs
Normal file
160
codex-rs/cli/src/doctor/windows_dev_drive.rs
Normal 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;
|
||||
16
codex-rs/cli/src/doctor/windows_dev_drive_tests.rs
Normal file
16
codex-rs/cli/src/doctor/windows_dev_drive_tests.rs
Normal 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);
|
||||
}
|
||||
Reference in New Issue
Block a user