Improve codex doctor network diagnostics (#38918)

## What changed

- Probe the configured Responses inference endpoint with Codex's route-aware HTTP client, including configured proxy and custom CA behavior.
- Classify TLS, proxy authentication, proxy configuration, resolution, and timeout failures into actionable diagnostics.
- Report privacy-safe macOS system proxy state and suggest enabling `respect_system_proxy` when a configured proxy is otherwise unused.
- Preserve system-root fallback when a custom CA is invalid, and account for provider-specific API key configuration when selecting the probe route.

## Testing

- Cover inference endpoint selection, invalid custom CA fallback, proxy authentication failures, TLS classification, and macOS proxy reporting.

GitOrigin-RevId: c30a3ca5a332119e2b2f8c65341ef9b2251a28a2
This commit is contained in:
chess authored and copyberry committed 2026-08-17 00:09:44 +00:00
1 parent 772e88c8ae
commit c8ddb210d2
12 files changed
+677 -93

No files matched your search

+152 -93
View File
@@ -39,6 +39,10 @@ use codex_core::config::ConfigBuilder;
use codex_core::config::ConfigOverrides;
use codex_core::config::find_codex_home;
use codex_features::FEATURES;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::RouteAwareClientPool;
use codex_install_context::CodexPackageLayout;
use codex_install_context::InstallContext;
use codex_install_context::InstallMethod;
@@ -63,12 +67,14 @@ use codex_tui::Cli as TuiCli;
use codex_utils_cli::CliConfigOverrides;
use http::HeaderMap;
use http::HeaderValue;
use http::Method;
use serde::Serialize;
use supports_color::Stream;
mod background;
mod disk;
mod git;
mod network;
mod output;
mod progress;
mod runtime;
@@ -376,6 +382,11 @@ async fn build_report(
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ true).await;
let auth_manager = auth_manager_result.as_ref().ok().cloned();
let reachability_plan = provider_reachability_plan(config);
#[cfg(target_os = "macos")]
let reachability_url = reachability_plan
.endpoints
.first()
.map(|endpoint| endpoint.url.clone());
let (
config_check,
auth_check,
@@ -409,7 +420,9 @@ async fn build_report(
})
},
async { run_sync_check("updates", progress.clone(), || updates_check(config)) },
async { run_sync_check("network", progress.clone(), network_check) },
async {
run_sync_check("network", progress.clone(), || network::check(Some(config)))
},
run_async_check(
"websocket",
progress.clone(),
@@ -449,6 +462,12 @@ async fn build_report(
provider_reachability_check(reachability_plan),
),
);
#[cfg(target_os = "macos")]
let reachability_check = network::with_system_proxy_remediation(
reachability_check,
config,
reachability_url.as_deref(),
);
checks.extend([
config_check,
auth_check,
@@ -488,7 +507,11 @@ async fn build_report(
.remediation("Fix the reported config error, then rerun codex doctor.")
})
},
async { run_sync_check("network", progress.clone(), network_check) },
async {
run_sync_check("network", progress.clone(), || {
network::check(/*config*/ None)
})
},
async {
run_sync_check("terminal", progress.clone(), || {
terminal_check(command.no_color)
@@ -1472,42 +1495,6 @@ fn stored_auth_issues(
issues
}
fn network_check() -> DoctorCheck {
let mut details = Vec::new();
push_proxy_env_details(&mut details);
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(err) = read_probe_file(&path) {
status = CheckStatus::Warning;
summary = "custom CA env var points at an unreadable file".to_string();
details.push(format!("{name}: {} ({err})", 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(err) => {
status = CheckStatus::Warning;
summary = "custom CA env var points at an unreadable path".to_string();
details.push(format!("{name}: {} ({err})", path.display()));
}
}
}
}
DoctorCheck::new("network.env", "network", status, summary).details(details)
}
fn push_proxy_env_details(details: &mut Vec<String>) {
let present_proxy_vars = PROXY_ENV_VARS
.iter()
@@ -2579,6 +2566,7 @@ fn fallback_state_check() -> DoctorCheck {
struct ReachabilityPlan {
description: String,
endpoints: Vec<ReachabilityEndpoint>,
http_client_factory: HttpClientFactory,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -2616,10 +2604,12 @@ fn provider_reachability_plan(config: &Config) -> ReachabilityPlan {
.flatten();
let mode = provider_auth_reachability_mode_from_auth(
config.model_provider.requires_openai_auth,
config.model_provider.env_key.as_deref(),
config.model_provider.base_url.as_deref(),
env_var_present,
stored_auth.as_ref(),
);
provider_reachability_plan_from_parts(
let mut plan = provider_reachability_plan_from_parts(
mode,
&config.model_provider_id,
&config.model_provider.name,
@@ -2627,7 +2617,9 @@ fn provider_reachability_plan(config: &Config) -> ReachabilityPlan {
config.model_provider.query_params.as_ref(),
config.model_provider.is_amazon_bedrock(),
&config.chatgpt_base_url,
)
);
plan.http_client_factory = config.http_client_factory();
plan
}
fn default_reachability_plan() -> ReachabilityPlan {
@@ -2644,13 +2636,19 @@ fn default_reachability_plan() -> ReachabilityPlan {
fn provider_auth_reachability_mode_from_auth(
requires_openai_auth: bool,
provider_env_key: Option<&str>,
provider_base_url: Option<&str>,
env_var_present: impl Fn(&str) -> bool,
stored_auth: Option<&AuthDotJson>,
) -> ProviderAuthReachabilityMode {
if !requires_openai_auth {
return ProviderAuthReachabilityMode::NotRequired;
}
if env_var_present(OPENAI_API_KEY_ENV_VAR) || env_var_present(CODEX_API_KEY_ENV_VAR) {
if provider_base_url.is_some_and(|url| !url.trim().is_empty())
&& provider_env_key
.is_some_and(|env_key| !env_key.trim().is_empty() && env_var_present(env_key))
|| env_var_present(CODEX_API_KEY_ENV_VAR)
{
return ProviderAuthReachabilityMode::ApiKey;
}
if env_var_present(CODEX_ACCESS_TOKEN_ENV_VAR) {
@@ -2686,35 +2684,29 @@ fn provider_reachability_plan_from_parts(
should_probe_models_route(provider_name, url, is_amazon_bedrock)
.then(|| provider_url_for_path(url, "models", provider_query_params))
});
let endpoints = match mode {
ProviderAuthReachabilityMode::ApiKey => vec![ReachabilityEndpoint {
let endpoints = match (mode, provider_base_url) {
(ProviderAuthReachabilityMode::ApiKey, _) | (_, Some(_)) => vec![ReachabilityEndpoint {
label: format!("{provider_id} API"),
url: provider_base_url
.unwrap_or("https://api.openai.com/v1")
.to_string(),
url: provider_url_for_path(
provider_base_url.unwrap_or("https://api.openai.com/v1"),
"responses",
provider_query_params,
),
required: true,
route_probe_url: provider_route_probe_url,
}],
ProviderAuthReachabilityMode::Chatgpt => vec![ReachabilityEndpoint {
(ProviderAuthReachabilityMode::Chatgpt, None) => vec![ReachabilityEndpoint {
label: "ChatGPT".to_string(),
url: chatgpt_base_url.to_string(),
url: provider_url_for_path(chatgpt_base_url, "codex/responses", provider_query_params),
required: true,
route_probe_url: None,
}],
ProviderAuthReachabilityMode::NotRequired => provider_base_url
.map(|url| {
vec![ReachabilityEndpoint {
label: format!("{provider_id} API"),
url: url.to_string(),
required: true,
route_probe_url: provider_route_probe_url,
}]
})
.unwrap_or_default(),
(ProviderAuthReachabilityMode::NotRequired, None) => Vec::new(),
};
ReachabilityPlan {
description: mode.description().to_string(),
endpoints,
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
}
}
@@ -2765,15 +2757,20 @@ async fn provider_reachability_check(plan: ReachabilityPlan) -> DoctorCheck {
.details(details);
}
let client = RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging(
plan.http_client_factory,
ClientRouteClass::Api,
)
.with_legacy_custom_ca_fallback();
let mut failures = Vec::new();
let mut optional_failures = Vec::new();
let mut route_failures = Vec::new();
let mut route_warnings = Vec::new();
let mut issues = Vec::new();
for endpoint in plan.endpoints {
match http_probe_url(&endpoint.url).await {
match network::probe_status(&client, &endpoint.url, Method::HEAD, default_headers()).await {
Ok(status) => details.push(format!(
"{} base URL: {} reachable ({status})",
"{} inference URL: {} reachable (HTTP {status})",
endpoint.label, endpoint.url
)),
Err(err) => {
@@ -2783,7 +2780,7 @@ async fn provider_reachability_check(plan: ReachabilityPlan) -> DoctorCheck {
"optional"
};
details.push(format!(
"{} base URL: {} {err} ({requirement})",
"{} inference URL: {} {err} ({requirement})",
endpoint.label, endpoint.url
));
if endpoint.required {
@@ -2798,7 +2795,7 @@ async fn provider_reachability_check(plan: ReachabilityPlan) -> DoctorCheck {
let Some(route_probe_url) = endpoint.route_probe_url.as_deref() else {
continue;
};
match provider_route_probe_url(route_probe_url).await {
match provider_route_probe_url(&client, route_probe_url).await {
RouteProbeOutcome::Ok(status) => {
details.push(format!(
"{} route probe: {route_probe_url} route exists ({status})",
@@ -2876,8 +2873,8 @@ enum RouteProbeOutcome {
TransportError(String),
}
async fn provider_route_probe_url(url: &str) -> RouteProbeOutcome {
match http_get_probe_status_with_timeout(url, Duration::from_secs(3)).await {
async fn provider_route_probe_url(client: &RouteAwareClientPool, url: &str) -> RouteProbeOutcome {
match network::probe_status(client, url, Method::GET, default_headers()).await {
Ok(status) if (200..300).contains(&status) || matches!(status, 401 | 403) => {
RouteProbeOutcome::Ok(format!("HTTP {status}"))
}
@@ -2907,10 +2904,6 @@ fn provider_reachability_outcome(
}
}
async fn http_probe_url(url: &str) -> Result<String, String> {
http_probe_url_with_timeout(url, Duration::from_secs(3)).await
}
async fn mcp_http_probe_url(url: &str) -> Result<String, String> {
mcp_http_probe_url_with_timeout(url, Duration::from_secs(3)).await
}
@@ -3652,6 +3645,8 @@ mod tests {
assert_eq!(
provider_auth_reachability_mode_from_auth(
/*requires_openai_auth*/ true,
/*provider_env_key*/ None,
/*provider_base_url*/ None,
|_| false,
Some(&api_key_auth),
),
@@ -3660,11 +3655,49 @@ mod tests {
assert_eq!(
provider_auth_reachability_mode_from_auth(
/*requires_openai_auth*/ true,
|name| name == OPENAI_API_KEY_ENV_VAR,
/*provider_env_key*/ None,
/*provider_base_url*/ None,
|name| name == CODEX_API_KEY_ENV_VAR,
/*stored_auth*/ None,
),
ProviderAuthReachabilityMode::ApiKey
);
let chatgpt_auth = AuthDotJson {
auth_mode: Some(AuthMode::Chatgpt),
openai_api_key: None,
..api_key_auth
};
assert_eq!(
provider_auth_reachability_mode_from_auth(
/*requires_openai_auth*/ true,
/*provider_env_key*/ None,
Some("https://custom.example/v1"),
|name| name == OPENAI_API_KEY_ENV_VAR,
Some(&chatgpt_auth),
),
ProviderAuthReachabilityMode::Chatgpt
);
assert_eq!(
provider_auth_reachability_mode_from_auth(
/*requires_openai_auth*/ true,
Some(OPENAI_API_KEY_ENV_VAR),
Some("https://custom.example/v1"),
|name| name == OPENAI_API_KEY_ENV_VAR,
Some(&chatgpt_auth),
),
ProviderAuthReachabilityMode::ApiKey
);
assert_eq!(
provider_auth_reachability_mode_from_auth(
/*requires_openai_auth*/ true,
/*provider_env_key*/ None,
/*provider_base_url*/ None,
|name| name == CODEX_API_KEY_ENV_VAR,
Some(&chatgpt_auth),
),
ProviderAuthReachabilityMode::ApiKey
);
}
#[test]
@@ -3683,10 +3716,11 @@ mod tests {
description: "provider auth".to_string(),
endpoints: vec![ReachabilityEndpoint {
label: "azure API".to_string(),
url: "https://example.openai.azure.com/openai/v1".to_string(),
url: "https://example.openai.azure.com/openai/v1/responses".to_string(),
required: true,
route_probe_url: None,
}],
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
}
);
}
@@ -3695,28 +3729,38 @@ mod tests {
fn provider_reachability_adds_models_route_probe_for_openai_compatible_base_urls() {
let query_params = HashMap::from([("api-version".to_string(), "2026-01-01".to_string())]);
assert_eq!(
provider_reachability_plan_from_parts(
ProviderAuthReachabilityMode::NotRequired,
"custom",
"Custom",
Some("https://example.com/openai/v1/"),
Some(&query_params),
/*is_amazon_bedrock*/ false,
"https://chatgpt.com/backend-api/",
),
ReachabilityPlan {
description: "provider auth".to_string(),
endpoints: vec![ReachabilityEndpoint {
label: "custom API".to_string(),
url: "https://example.com/openai/v1/".to_string(),
required: true,
route_probe_url: Some(
"https://example.com/openai/v1/models?api-version=2026-01-01".to_string()
for (mode, description) in [
(ProviderAuthReachabilityMode::NotRequired, "provider auth"),
(ProviderAuthReachabilityMode::Chatgpt, "ChatGPT auth"),
] {
assert_eq!(
provider_reachability_plan_from_parts(
mode,
"custom",
"Custom",
Some("https://example.com/openai/v1/"),
Some(&query_params),
/*is_amazon_bedrock*/ false,
"https://chatgpt.com/backend-api/",
),
ReachabilityPlan {
description: description.to_string(),
endpoints: vec![ReachabilityEndpoint {
label: "custom API".to_string(),
url: "https://example.com/openai/v1/responses?api-version=2026-01-01"
.to_string(),
required: true,
route_probe_url: Some(
"https://example.com/openai/v1/models?api-version=2026-01-01"
.to_string()
),
}],
http_client_factory: HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault
),
}],
}
);
}
);
}
}
#[test]
@@ -3750,13 +3794,26 @@ mod tests {
plan.endpoints,
vec![ReachabilityEndpoint {
label: "openai API".to_string(),
url: "https://api.openai.com/v1".to_string(),
url: "https://api.openai.com/v1/responses".to_string(),
required: true,
route_probe_url: Some("https://api.openai.com/v1/models".to_string()),
}]
);
}
#[test]
fn provider_reachability_chatgpt_uses_inference_endpoint() {
assert_eq!(
default_reachability_plan().endpoints,
vec![ReachabilityEndpoint {
label: "ChatGPT".to_string(),
url: "https://chatgpt.com/backend-api/codex/responses".to_string(),
required: true,
route_probe_url: None,
}]
);
}
#[test]
fn provider_reachability_outcome_reports_required_failures() {
assert_eq!(
@@ -3892,7 +3949,9 @@ mod tests {
.expect("write response");
});
let status = http_probe_url(&format!("http://{addr}/mcp")).await;
let status =
http_probe_url_with_timeout(&format!("http://{addr}/mcp"), Duration::from_secs(3))
.await;
server.join().expect("probe server thread should finish");
assert_eq!(status, Ok("HTTP 405".to_string()));