This commit is contained in:
canvrno-oai
2026-06-02 10:14:35 -07:00
parent 4836502ed5
commit 16e78a3c8b
18 changed files with 1244 additions and 33 deletions
+1
View File
@@ -2340,6 +2340,7 @@ dependencies = [
"tracing",
"tracing-opentelemetry",
"tracing-subscriber",
"windows-sys 0.52.0",
"zstd 0.13.3",
]
@@ -327,6 +327,8 @@ impl AccountRequestProcessor {
config.cli_auth_credentials_store_mode,
)
};
let mut opts = opts;
opts.set_network_config(config.network.as_ref());
#[cfg(debug_assertions)]
let opts = {
let mut opts = opts;
+6 -1
View File
@@ -117,13 +117,15 @@ pub async fn login_with_chatgpt(
codex_home: PathBuf,
forced_chatgpt_workspace_id: Option<Vec<String>>,
cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
network: Option<&codex_config::types::NetworkConfigToml>,
) -> std::io::Result<()> {
let opts = ServerOptions::new(
let mut opts = ServerOptions::new(
codex_home,
CLIENT_ID.to_string(),
forced_chatgpt_workspace_id,
cli_auth_credentials_store_mode,
);
opts.set_network_config(network);
let server = run_login_server(opts)?;
print_login_server_start(server.actual_port, &server.auth_url);
@@ -147,6 +149,7 @@ pub async fn run_login_with_chatgpt(cli_config_overrides: CliConfigOverrides) ->
config.codex_home.to_path_buf(),
forced_chatgpt_workspace_id,
config.cli_auth_credentials_store_mode,
config.network.as_ref(),
)
.await
{
@@ -283,6 +286,7 @@ pub async fn run_login_with_device_code(
forced_chatgpt_workspace_id,
config.cli_auth_credentials_store_mode,
);
opts.set_network_config(config.network.as_ref());
if let Some(iss) = issuer_base_url {
opts.issuer = iss;
}
@@ -322,6 +326,7 @@ pub async fn run_login_with_device_code_fallback_to_browser(
forced_chatgpt_workspace_id,
config.cli_auth_credentials_store_mode,
);
opts.set_network_config(config.network.as_ref());
if let Some(iss) = issuer_base_url {
opts.issuer = iss;
}
+6
View File
@@ -25,6 +25,12 @@ tracing-opentelemetry = { workspace = true }
codex-utils-rustls-provider = { workspace = true }
zstd = { workspace = true }
[target.'cfg(target_os = "windows")'.dependencies]
windows-sys = { version = "0.52", features = [
"Win32_Foundation",
"Win32_Networking_WinHttp",
] }
[lints]
workspace = true
+5
View File
@@ -182,6 +182,11 @@ pub fn build_reqwest_client_with_custom_ca(
build_reqwest_client_with_env(&ProcessEnv, builder)
}
/// Returns whether process environment selects a Codex custom CA bundle.
pub(crate) fn custom_ca_env_configured() -> bool {
ProcessEnv.configured_ca_bundle().is_some()
}
/// Builds a rustls client config when a Codex custom CA bundle is configured.
///
/// This is the websocket-facing sibling of [`build_reqwest_client_with_custom_ca`]. When
+5
View File
@@ -3,6 +3,7 @@ mod chatgpt_hosts;
mod custom_ca;
mod default_client;
mod error;
mod outbound_proxy;
mod request;
mod retry;
mod route_diagnostics;
@@ -26,6 +27,10 @@ pub use crate::default_client::CodexHttpClient;
pub use crate::default_client::CodexRequestBuilder;
pub use crate::error::StreamError;
pub use crate::error::TransportError;
pub use crate::outbound_proxy::BuildProxiedHttpClientError;
pub use crate::outbound_proxy::OutboundProxyConfig;
pub use crate::outbound_proxy::OutboundProxyMode;
pub use crate::outbound_proxy::build_reqwest_client_for_route;
pub use crate::request::PreparedRequestBody;
pub use crate::request::Request;
pub use crate::request::RequestBody;
+618
View File
@@ -0,0 +1,618 @@
//! Conservative outbound proxy selection for resolver-aware clients.
//!
//! This module keeps the default path as close as possible to the existing
//! reqwest builder behavior. Explicit environment proxies are delegated back to
//! reqwest so its existing proxy and `NO_PROXY` behavior stays in control. The
//! Windows system resolver is only consulted when there is no explicit env
//! proxy and the caller allows system discovery.
use std::collections::HashMap;
use std::fmt;
use std::io;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::time::Duration;
use std::time::Instant;
use crate::custom_ca::BuildCustomCaTransportError;
use crate::custom_ca::build_reqwest_client_with_custom_ca;
use crate::custom_ca::custom_ca_env_configured;
use crate::route_diagnostics::RouteDiagnostic;
use crate::route_diagnostics::RouteFailureClass;
use crate::route_diagnostics::RouteSource;
use crate::route_diagnostics::RouteTarget;
use crate::route_diagnostics::SystemProxyEnvOverride;
use thiserror::Error;
const SYSTEM_PROXY_CACHE_TTL: Duration = Duration::from_secs(300);
#[cfg(target_os = "windows")]
mod windows;
/// How a resolver-aware client should choose an outbound proxy.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum OutboundProxyMode {
/// Preserve explicit env proxy behavior, then use supported system discovery.
#[default]
Auto,
/// Preserve only the existing reqwest/env proxy path.
Env,
/// Require supported system discovery after explicit config/env handling.
System,
/// Disable proxy use for this client.
Direct,
}
/// Optional route-selection inputs for resolver-aware clients.
#[derive(Default, Clone, PartialEq, Eq)]
pub struct OutboundProxyConfig {
pub mode: OutboundProxyMode,
pub proxy_url: Option<String>,
}
impl fmt::Debug for OutboundProxyConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OutboundProxyConfig")
.field("mode", &self.mode)
.field(
"proxy_url",
&self.proxy_url.as_ref().map(|_| "<redacted-proxy-url>"),
)
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProxyCacheMode {
Use,
Bypass,
}
/// Error while building a resolver-aware reqwest client.
#[derive(Debug, Error)]
pub enum BuildProxiedHttpClientError {
#[error(transparent)]
CustomCa(#[from] BuildCustomCaTransportError),
#[error("Failed to configure outbound proxy selected for {target}")]
InvalidProxyConfig { target: RouteTarget },
#[error("System proxy resolution for {target} failed: {failure}")]
SystemProxyUnavailable {
target: RouteTarget,
failure: RouteFailureClass,
},
}
impl From<BuildProxiedHttpClientError> for io::Error {
fn from(error: BuildProxiedHttpClientError) -> Self {
match error {
BuildProxiedHttpClientError::CustomCa(error) => error.into(),
BuildProxiedHttpClientError::InvalidProxyConfig { .. }
| BuildProxiedHttpClientError::SystemProxyUnavailable { .. } => io::Error::other(error),
}
}
}
/// Builds a reqwest client with conservative route selection and shared CA handling.
pub fn build_reqwest_client_for_route(
builder: reqwest::ClientBuilder,
request_url: &str,
target: RouteTarget,
config: Option<&OutboundProxyConfig>,
) -> Result<reqwest::Client, BuildProxiedHttpClientError> {
let builder =
configure_proxy_for_route(builder, request_url, target, config, ProxyCacheMode::Use)?;
build_reqwest_client_with_custom_ca(builder).map_err(Into::into)
}
fn configure_proxy_for_route(
builder: reqwest::ClientBuilder,
request_url: &str,
target: RouteTarget,
config: Option<&OutboundProxyConfig>,
cache_mode: ProxyCacheMode,
) -> Result<reqwest::ClientBuilder, BuildProxiedHttpClientError> {
let config = config.cloned().unwrap_or_default();
let custom_ca_configured = custom_ca_env_configured();
let origin = RequestOrigin::parse(request_url);
if config.mode == OutboundProxyMode::Direct {
RouteDiagnostic::direct(target, RouteSource::Disabled, custom_ca_configured).emit_opt_in();
return Ok(builder.no_proxy());
}
if origin.as_ref().is_some_and(no_proxy_env_matches_origin) {
RouteDiagnostic::direct(target, RouteSource::Env, custom_ca_configured).emit_opt_in();
return Ok(builder);
}
if let Some(proxy_url) = config
.proxy_url
.as_deref()
.filter(|value| !value.is_empty())
{
return configure_concrete_proxy(
builder,
target,
RouteSource::ConfigOverride,
proxy_url,
custom_ca_configured,
);
}
if let Some(origin) = origin.as_ref()
&& let Some(proxy_url) = env_proxy_for_origin(origin)
{
RouteDiagnostic::proxy(target, RouteSource::Env, &proxy_url, custom_ca_configured)
.emit_opt_in();
return Ok(builder);
}
if conventional_proxy_env_present() {
RouteDiagnostic::direct(target, RouteSource::Env, custom_ca_configured).emit_opt_in();
return Ok(builder);
}
if config.mode == OutboundProxyMode::Env
|| !SystemProxyEnvOverride::from_env().system_discovery_enabled()
{
RouteDiagnostic::direct(target, RouteSource::Disabled, custom_ca_configured).emit_opt_in();
return Ok(builder);
}
if !system_proxy_supported() {
if config.mode == OutboundProxyMode::System {
RouteDiagnostic::unavailable(
target,
RouteSource::Unavailable,
RouteFailureClass::PacUnavailable,
custom_ca_configured,
)
.emit_opt_in();
return Err(BuildProxiedHttpClientError::SystemProxyUnavailable {
target,
failure: RouteFailureClass::PacUnavailable,
});
}
return Ok(builder);
}
let Some(origin) = origin else {
RouteDiagnostic::unavailable(
target,
RouteSource::Error,
RouteFailureClass::InvalidProxyConfig,
custom_ca_configured,
)
.emit_opt_in();
return if config.mode == OutboundProxyMode::System {
Err(BuildProxiedHttpClientError::SystemProxyUnavailable {
target,
failure: RouteFailureClass::InvalidProxyConfig,
})
} else {
Ok(builder)
};
};
match resolve_system_proxy(request_url, &origin, cache_mode) {
SystemProxyDecision::Direct { source } => {
RouteDiagnostic::direct(target, source, custom_ca_configured).emit_opt_in();
Ok(builder)
}
SystemProxyDecision::Proxy { source, url } => {
configure_concrete_proxy(builder, target, source, &url, custom_ca_configured)
}
SystemProxyDecision::Unavailable { source, failure } => {
RouteDiagnostic::unavailable(target, source, failure, custom_ca_configured)
.emit_opt_in();
if config.mode == OutboundProxyMode::System {
Err(BuildProxiedHttpClientError::SystemProxyUnavailable { target, failure })
} else {
Ok(builder)
}
}
}
}
const fn system_proxy_supported() -> bool {
cfg!(target_os = "windows")
}
fn configure_concrete_proxy(
builder: reqwest::ClientBuilder,
target: RouteTarget,
source: RouteSource,
proxy_url: &str,
custom_ca_configured: bool,
) -> Result<reqwest::ClientBuilder, BuildProxiedHttpClientError> {
let proxy = match reqwest::Proxy::all(proxy_url) {
Ok(proxy) => proxy,
Err(_source) => {
RouteDiagnostic::unavailable(
target,
source,
RouteFailureClass::InvalidProxyConfig,
custom_ca_configured,
)
.emit_opt_in();
return Err(BuildProxiedHttpClientError::InvalidProxyConfig { target });
}
};
RouteDiagnostic::proxy(target, source, proxy_url, custom_ca_configured).emit_opt_in();
Ok(builder.proxy(proxy))
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct RequestOrigin {
scheme: String,
host: String,
port: u16,
}
impl RequestOrigin {
fn parse(request_url: &str) -> Option<Self> {
let uri = request_url.parse::<http::Uri>().ok()?;
let scheme = uri.scheme_str()?.to_ascii_lowercase();
let host = uri.host()?.trim_matches(['[', ']']).to_ascii_lowercase();
let port = uri
.port_u16()
.or_else(|| default_port_for_scheme(&scheme))?;
Some(Self { scheme, host, port })
}
fn cache_key(&self) -> String {
format!("{}://{}:{}", self.scheme, self.host, self.port)
}
}
fn default_port_for_scheme(scheme: &str) -> Option<u16> {
match scheme {
"http" => Some(80),
"https" => Some(443),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum SystemProxyDecision {
Direct {
source: RouteSource,
},
Proxy {
source: RouteSource,
url: String,
},
Unavailable {
source: RouteSource,
failure: RouteFailureClass,
},
}
fn resolve_system_proxy(
request_url: &str,
origin: &RequestOrigin,
cache_mode: ProxyCacheMode,
) -> SystemProxyDecision {
if cache_mode == ProxyCacheMode::Use
&& let Some(decision) = cached_system_proxy_decision(origin)
{
return decision;
}
let decision = resolve_platform_system_proxy(request_url, origin);
cache_system_proxy_decision(origin, decision.clone());
decision
}
#[cfg(target_os = "windows")]
fn resolve_platform_system_proxy(request_url: &str, origin: &RequestOrigin) -> SystemProxyDecision {
windows::resolve(request_url, origin)
}
#[cfg(not(target_os = "windows"))]
fn resolve_platform_system_proxy(
_request_url: &str,
_origin: &RequestOrigin,
) -> SystemProxyDecision {
SystemProxyDecision::Unavailable {
source: RouteSource::Unavailable,
failure: RouteFailureClass::PacUnavailable,
}
}
#[derive(Debug, Clone)]
struct CachedSystemProxyDecision {
decision: SystemProxyDecision,
expires_at: Instant,
}
static SYSTEM_PROXY_CACHE: OnceLock<Mutex<HashMap<String, CachedSystemProxyDecision>>> =
OnceLock::new();
fn cached_system_proxy_decision(origin: &RequestOrigin) -> Option<SystemProxyDecision> {
let cache = SYSTEM_PROXY_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let mut cache = cache.lock().ok()?;
let key = origin.cache_key();
let cached = cache.get(&key)?;
if cached.expires_at > Instant::now() {
return Some(cached.decision.clone());
}
cache.remove(&key);
None
}
fn cache_system_proxy_decision(origin: &RequestOrigin, decision: SystemProxyDecision) {
let cache = SYSTEM_PROXY_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
if let Ok(mut cache) = cache.lock() {
cache.insert(
origin.cache_key(),
CachedSystemProxyDecision {
decision,
expires_at: Instant::now() + SYSTEM_PROXY_CACHE_TTL,
},
);
}
}
fn conventional_proxy_env_present() -> bool {
proxy_env_value("HTTPS_PROXY").is_some()
|| proxy_env_value("HTTP_PROXY").is_some()
|| proxy_env_value("ALL_PROXY").is_some()
}
fn env_proxy_for_origin(origin: &RequestOrigin) -> Option<String> {
if origin.scheme == "https" {
proxy_env_value("HTTPS_PROXY").or_else(|| proxy_env_value("ALL_PROXY"))
} else if origin.scheme == "http" {
proxy_env_value("HTTP_PROXY").or_else(|| proxy_env_value("ALL_PROXY"))
} else {
proxy_env_value("ALL_PROXY")
}
}
fn proxy_env_value(upper: &str) -> Option<String> {
let lower = upper.to_ascii_lowercase();
std::env::var(upper)
.ok()
.filter(|value| !value.is_empty())
.or_else(|| std::env::var(lower).ok().filter(|value| !value.is_empty()))
}
fn no_proxy_env_matches_origin(origin: &RequestOrigin) -> bool {
let Some(no_proxy) = proxy_env_value("NO_PROXY") else {
return false;
};
no_proxy_matches_origin(&no_proxy, origin)
}
fn no_proxy_matches_origin(no_proxy: &str, origin: &RequestOrigin) -> bool {
no_proxy
.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.any(|entry| no_proxy_entry_matches_origin(entry, origin))
}
fn no_proxy_entry_matches_origin(entry: &str, origin: &RequestOrigin) -> bool {
if entry == "*" {
return true;
}
let mut entry = entry
.strip_prefix("http://")
.or_else(|| entry.strip_prefix("https://"))
.unwrap_or(entry)
.trim_matches(['[', ']'])
.to_ascii_lowercase();
let mut port = None;
let parsed_host_port = entry.rsplit_once(':').and_then(|(host, candidate_port)| {
if host.contains(':') {
return None;
}
candidate_port
.parse::<u16>()
.ok()
.map(|parsed_port| (host.to_string(), parsed_port))
});
if let Some((host, parsed_port)) = parsed_host_port {
entry = host;
port = Some(parsed_port);
}
if port.is_some_and(|port| port != origin.port) {
return false;
}
if let Some(suffix) = entry.strip_prefix('.') {
return origin.host == suffix || origin.host.ends_with(&format!(".{suffix}"));
}
if entry.contains('*') {
return wildcard_host_match(&entry, &origin.host);
}
origin.host == entry || origin.host.ends_with(&format!(".{entry}"))
}
fn wildcard_host_match(pattern: &str, host: &str) -> bool {
let mut remaining = host;
let mut first = true;
for part in pattern.split('*') {
if part.is_empty() {
continue;
}
if first && !pattern.starts_with('*') {
let Some(stripped) = remaining.strip_prefix(part) else {
return false;
};
remaining = stripped;
} else {
let Some(index) = remaining.find(part) else {
return false;
};
remaining = &remaining[index + part.len()..];
}
first = false;
}
pattern.ends_with('*') || remaining.is_empty()
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum ParsedProxyListDecision {
Direct,
Proxy(String),
UnsupportedScheme,
Unavailable,
}
fn parse_proxy_list(input: &str, target_scheme: &str) -> ParsedProxyListDecision {
let mut saw_unsupported = false;
let mut http_fallback = None;
for token in input
.split(';')
.map(str::trim)
.filter(|token| !token.is_empty())
{
if target_scheme == "https"
&& http_fallback.is_none()
&& let Some(ParsedProxyListDecision::Proxy(url)) = parse_proxy_key_token(token, "http")
{
http_fallback = Some(url);
}
match parse_proxy_token(token, target_scheme) {
ParsedProxyListDecision::Direct => return ParsedProxyListDecision::Direct,
ParsedProxyListDecision::Proxy(url) => return ParsedProxyListDecision::Proxy(url),
ParsedProxyListDecision::UnsupportedScheme => saw_unsupported = true,
ParsedProxyListDecision::Unavailable => {}
}
}
if let Some(url) = http_fallback {
ParsedProxyListDecision::Proxy(url)
} else if saw_unsupported {
ParsedProxyListDecision::UnsupportedScheme
} else {
ParsedProxyListDecision::Unavailable
}
}
fn parse_proxy_token(token: &str, target_scheme: &str) -> ParsedProxyListDecision {
if token.eq_ignore_ascii_case("DIRECT") {
return ParsedProxyListDecision::Direct;
}
if let Some(decision) = parse_proxy_key_token(token, target_scheme) {
return decision;
}
if token.contains('=') {
return ParsedProxyListDecision::Unavailable;
}
if let Some((scheme, hostport)) = token.split_once(' ') {
let scheme = scheme.trim().to_ascii_lowercase();
let hostport = hostport.trim();
return match scheme.as_str() {
"proxy" | "http" => proxy_url_from_hostport("http", hostport),
"https" => proxy_url_from_hostport("https", hostport),
"socks" | "socks4" | "socks5" => ParsedProxyListDecision::UnsupportedScheme,
_ => ParsedProxyListDecision::Unavailable,
};
}
proxy_url_from_hostport("http", token)
}
fn parse_proxy_key_token(token: &str, target_scheme: &str) -> Option<ParsedProxyListDecision> {
let (key, value) = token.split_once('=')?;
if key.trim().eq_ignore_ascii_case(target_scheme) {
Some(proxy_url_from_hostport("http", value.trim()))
} else {
Some(ParsedProxyListDecision::Unavailable)
}
}
fn proxy_url_from_hostport(proxy_scheme: &str, hostport: &str) -> ParsedProxyListDecision {
if hostport.is_empty() {
return ParsedProxyListDecision::Unavailable;
}
if hostport.contains("://") {
return ParsedProxyListDecision::Proxy(hostport.to_string());
}
ParsedProxyListDecision::Proxy(format!("{proxy_scheme}://{hostport}"))
}
impl fmt::Display for ParsedProxyListDecision {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Direct => f.write_str("direct"),
Self::Proxy(_) => f.write_str("proxy"),
Self::UnsupportedScheme => f.write_str("unsupported_scheme"),
Self::Unavailable => f.write_str("unavailable"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn parses_pac_proxy_tokens() {
assert_eq!(
parse_proxy_list("PROXY proxy.internal:8080; DIRECT", "https"),
ParsedProxyListDecision::Proxy("http://proxy.internal:8080".to_string())
);
assert_eq!(
parse_proxy_list("HTTPS proxy.internal:8443", "https"),
ParsedProxyListDecision::Proxy("https://proxy.internal:8443".to_string())
);
}
#[test]
fn parses_static_winhttp_proxy_entries_for_target_scheme() {
assert_eq!(
parse_proxy_list("http=web-proxy:8080;https=secure-proxy:8443", "https"),
ParsedProxyListDecision::Proxy("http://secure-proxy:8443".to_string())
);
assert_eq!(
parse_proxy_list("proxy.internal:8080", "https"),
ParsedProxyListDecision::Proxy("http://proxy.internal:8080".to_string())
);
}
#[test]
fn reports_direct_and_unsupported_proxy_tokens() {
assert_eq!(
parse_proxy_list("PROXY proxy.internal:8080; DIRECT", "https"),
ParsedProxyListDecision::Proxy("http://proxy.internal:8080".to_string())
);
assert_eq!(
parse_proxy_list("DIRECT; PROXY proxy.internal:8080", "https"),
ParsedProxyListDecision::Direct
);
assert_eq!(
parse_proxy_list("DIRECT", "https"),
ParsedProxyListDecision::Direct
);
assert_eq!(
parse_proxy_list("SOCKS proxy.internal:1080", "https"),
ParsedProxyListDecision::UnsupportedScheme
);
}
#[test]
fn no_proxy_matches_exact_suffix_wildcard_and_port() {
let origin = RequestOrigin {
scheme: "https".to_string(),
host: "auth.openai.com".to_string(),
port: 443,
};
assert!(no_proxy_matches_origin("auth.openai.com", &origin));
assert!(no_proxy_matches_origin(".openai.com", &origin));
assert!(no_proxy_matches_origin("*.openai.com", &origin));
assert!(no_proxy_matches_origin("auth.openai.com:443", &origin));
assert!(!no_proxy_matches_origin("auth.openai.com:8443", &origin));
}
}
@@ -0,0 +1,366 @@
use std::ffi::c_void;
use std::ptr;
use super::ParsedProxyListDecision;
use super::RequestOrigin;
use super::SystemProxyDecision;
use super::no_proxy_matches_origin;
use super::parse_proxy_list;
use crate::route_diagnostics::RouteFailureClass;
use crate::route_diagnostics::RouteSource;
use windows_sys::Win32::Foundation::FALSE;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::GlobalFree;
use windows_sys::Win32::Foundation::TRUE;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_AUTODETECTION_FAILED;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_CANNOT_CONNECT;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_CONNECTION_ERROR;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_INVALID_URL;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_LOGIN_FAILURE;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_NAME_NOT_RESOLVED;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SCRIPT_EXECUTION_ERROR;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SECURE_CERT_REVOKED;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SECURE_FAILURE;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SECURE_INVALID_CA;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_SECURE_INVALID_CERT;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_TIMEOUT;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_UNHANDLED_SCRIPT_TYPE;
use windows_sys::Win32::Networking::WinHttp::ERROR_WINHTTP_UNRECOGNIZED_SCHEME;
use windows_sys::Win32::Networking::WinHttp::WINHTTP_ACCESS_TYPE_NAMED_PROXY;
use windows_sys::Win32::Networking::WinHttp::WINHTTP_ACCESS_TYPE_NO_PROXY;
use windows_sys::Win32::Networking::WinHttp::WINHTTP_AUTO_DETECT_TYPE_DHCP;
use windows_sys::Win32::Networking::WinHttp::WINHTTP_AUTO_DETECT_TYPE_DNS_A;
use windows_sys::Win32::Networking::WinHttp::WINHTTP_AUTOPROXY_AUTO_DETECT;
use windows_sys::Win32::Networking::WinHttp::WINHTTP_AUTOPROXY_CONFIG_URL;
use windows_sys::Win32::Networking::WinHttp::WINHTTP_AUTOPROXY_OPTIONS;
use windows_sys::Win32::Networking::WinHttp::WINHTTP_CURRENT_USER_IE_PROXY_CONFIG;
use windows_sys::Win32::Networking::WinHttp::WINHTTP_PROXY_INFO;
use windows_sys::Win32::Networking::WinHttp::WinHttpCloseHandle;
use windows_sys::Win32::Networking::WinHttp::WinHttpGetIEProxyConfigForCurrentUser;
use windows_sys::Win32::Networking::WinHttp::WinHttpGetProxyForUrl;
use windows_sys::Win32::Networking::WinHttp::WinHttpOpen;
use windows_sys::core::PWSTR;
pub(super) fn resolve(request_url: &str, origin: &RequestOrigin) -> SystemProxyDecision {
let ie_config = match current_user_ie_proxy_config() {
Ok(config) => config,
Err(failure) => {
return SystemProxyDecision::Unavailable {
source: RouteSource::Error,
failure,
};
}
};
if let Some(pac_url) = ie_config.auto_config_url.as_deref() {
let decision = resolve_with_pac_url(request_url, origin, pac_url);
if !matches!(decision, SystemProxyDecision::Unavailable { .. }) {
return decision;
}
}
if ie_config.auto_detect {
let decision = resolve_with_auto_detect(request_url, origin);
if !matches!(decision, SystemProxyDecision::Unavailable { .. }) {
return decision;
}
}
if let Some(proxy) = ie_config.static_proxy.as_deref() {
if ie_config
.proxy_bypass
.as_deref()
.is_some_and(|bypass| proxy_bypass_matches_origin(bypass, origin))
{
return SystemProxyDecision::Direct {
source: RouteSource::WindowsStatic,
};
}
return proxy_list_decision(proxy, origin, RouteSource::WindowsStatic);
}
if ie_config.auto_config_url.is_some() || ie_config.auto_detect {
SystemProxyDecision::Unavailable {
source: RouteSource::WindowsWinHttpPac,
failure: RouteFailureClass::PacUnavailable,
}
} else {
SystemProxyDecision::Direct {
source: RouteSource::Direct,
}
}
}
fn resolve_with_pac_url(
request_url: &str,
origin: &RequestOrigin,
pac_url: &str,
) -> SystemProxyDecision {
let pac_url = wide_null(pac_url);
let options = WINHTTP_AUTOPROXY_OPTIONS {
dwFlags: WINHTTP_AUTOPROXY_CONFIG_URL,
dwAutoDetectFlags: 0,
lpszAutoConfigUrl: pac_url.as_ptr(),
lpvReserved: ptr::null_mut(),
dwReserved: 0,
fAutoLogonIfChallenged: TRUE,
};
resolve_with_winhttp_options(request_url, origin, options)
}
fn resolve_with_auto_detect(request_url: &str, origin: &RequestOrigin) -> SystemProxyDecision {
let options = WINHTTP_AUTOPROXY_OPTIONS {
dwFlags: WINHTTP_AUTOPROXY_AUTO_DETECT,
dwAutoDetectFlags: WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A,
lpszAutoConfigUrl: ptr::null(),
lpvReserved: ptr::null_mut(),
dwReserved: 0,
fAutoLogonIfChallenged: TRUE,
};
resolve_with_winhttp_options(request_url, origin, options)
}
fn resolve_with_winhttp_options(
request_url: &str,
origin: &RequestOrigin,
mut options: WINHTTP_AUTOPROXY_OPTIONS,
) -> SystemProxyDecision {
let Some(session) = WinHttpSession::open() else {
return SystemProxyDecision::Unavailable {
source: RouteSource::WindowsWinHttpPac,
failure: classify_winhttp_error(last_error()),
};
};
let request_url = wide_null(request_url);
let mut proxy_info = WINHTTP_PROXY_INFO {
dwAccessType: WINHTTP_ACCESS_TYPE_NO_PROXY,
lpszProxy: ptr::null_mut(),
lpszProxyBypass: ptr::null_mut(),
};
let ok = unsafe {
WinHttpGetProxyForUrl(
session.0,
request_url.as_ptr(),
&mut options,
&mut proxy_info,
)
};
if ok == FALSE {
return SystemProxyDecision::Unavailable {
source: RouteSource::WindowsWinHttpPac,
failure: classify_winhttp_error(last_error()),
};
}
let proxy_info = ProxyInfo::from_raw(proxy_info);
if proxy_info.access_type == WINHTTP_ACCESS_TYPE_NO_PROXY {
return SystemProxyDecision::Direct {
source: RouteSource::WindowsWinHttpPac,
};
}
if proxy_info.access_type != WINHTTP_ACCESS_TYPE_NAMED_PROXY {
return SystemProxyDecision::Unavailable {
source: RouteSource::WindowsWinHttpPac,
failure: RouteFailureClass::PacUnavailable,
};
}
let Some(proxy) = proxy_info.proxy.as_deref() else {
return SystemProxyDecision::Unavailable {
source: RouteSource::WindowsWinHttpPac,
failure: RouteFailureClass::PacUnavailable,
};
};
proxy_list_decision(proxy, origin, RouteSource::WindowsWinHttpPac)
}
fn proxy_list_decision(
proxy_list: &str,
origin: &RequestOrigin,
source: RouteSource,
) -> SystemProxyDecision {
match parse_proxy_list(proxy_list, &origin.scheme) {
ParsedProxyListDecision::Direct => SystemProxyDecision::Direct { source },
ParsedProxyListDecision::Proxy(url) => SystemProxyDecision::Proxy { source, url },
ParsedProxyListDecision::UnsupportedScheme => SystemProxyDecision::Unavailable {
source,
failure: RouteFailureClass::UnsupportedProxyScheme,
},
ParsedProxyListDecision::Unavailable => SystemProxyDecision::Unavailable {
source,
failure: RouteFailureClass::PacUnavailable,
},
}
}
fn current_user_ie_proxy_config() -> Result<IeProxyConfig, RouteFailureClass> {
let mut raw = WINHTTP_CURRENT_USER_IE_PROXY_CONFIG {
fAutoDetect: FALSE,
lpszAutoConfigUrl: ptr::null_mut(),
lpszProxy: ptr::null_mut(),
lpszProxyBypass: ptr::null_mut(),
};
let ok = unsafe { WinHttpGetIEProxyConfigForCurrentUser(&mut raw) };
if ok == FALSE {
return Err(classify_winhttp_error(last_error()));
}
let auto_config_url = GlobalWideString::from_raw(raw.lpszAutoConfigUrl).into_string();
let static_proxy = GlobalWideString::from_raw(raw.lpszProxy).into_string();
let proxy_bypass = GlobalWideString::from_raw(raw.lpszProxyBypass).into_string();
Ok(IeProxyConfig {
auto_detect: raw.fAutoDetect != FALSE,
auto_config_url,
static_proxy,
proxy_bypass,
})
}
#[derive(Debug)]
struct IeProxyConfig {
auto_detect: bool,
auto_config_url: Option<String>,
static_proxy: Option<String>,
proxy_bypass: Option<String>,
}
struct ProxyInfo {
access_type: u32,
proxy: Option<String>,
_proxy_bypass: Option<String>,
}
impl ProxyInfo {
fn from_raw(raw: WINHTTP_PROXY_INFO) -> Self {
Self {
access_type: raw.dwAccessType,
proxy: GlobalWideString::from_raw(raw.lpszProxy).into_string(),
_proxy_bypass: GlobalWideString::from_raw(raw.lpszProxyBypass).into_string(),
}
}
}
struct GlobalWideString(PWSTR);
impl GlobalWideString {
fn from_raw(ptr: PWSTR) -> Self {
Self(ptr)
}
fn into_string(self) -> Option<String> {
if self.0.is_null() {
return None;
}
let string = unsafe { wide_ptr_to_string(self.0) };
if string.is_empty() {
None
} else {
Some(string)
}
}
}
impl Drop for GlobalWideString {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe {
GlobalFree(self.0.cast::<c_void>());
}
}
}
}
struct WinHttpSession(*mut c_void);
impl WinHttpSession {
fn open() -> Option<Self> {
let agent = wide_null("Codex");
let handle = unsafe {
WinHttpOpen(
agent.as_ptr(),
WINHTTP_ACCESS_TYPE_NO_PROXY,
ptr::null(),
ptr::null(),
0,
)
};
if handle.is_null() {
None
} else {
Some(Self(handle))
}
}
}
impl Drop for WinHttpSession {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe {
WinHttpCloseHandle(self.0);
}
}
}
}
fn proxy_bypass_matches_origin(proxy_bypass: &str, origin: &RequestOrigin) -> bool {
proxy_bypass.split([';', ',']).map(str::trim).any(|entry| {
if entry.eq_ignore_ascii_case("<local>") {
!origin.host.contains('.')
} else {
no_proxy_matches_origin(entry, origin)
}
})
}
fn wide_null(value: &str) -> Vec<u16> {
value.encode_utf16().chain(std::iter::once(0)).collect()
}
unsafe fn wide_ptr_to_string(ptr: PWSTR) -> String {
let mut len = 0;
while unsafe { *ptr.add(len) } != 0 {
len += 1;
}
let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
String::from_utf16_lossy(slice)
}
fn last_error() -> u32 {
unsafe { GetLastError() }
}
fn classify_winhttp_error(code: u32) -> RouteFailureClass {
match code {
ERROR_WINHTTP_TIMEOUT => RouteFailureClass::ConnectTimeout,
ERROR_WINHTTP_LOGIN_FAILURE => RouteFailureClass::ProxyAuthenticationRequired,
ERROR_WINHTTP_AUTODETECTION_FAILED
| ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT
| ERROR_WINHTTP_SCRIPT_EXECUTION_ERROR
| ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT
| ERROR_WINHTTP_UNHANDLED_SCRIPT_TYPE => RouteFailureClass::PacUnavailable,
ERROR_WINHTTP_SECURE_CERT_CN_INVALID
| ERROR_WINHTTP_SECURE_CERT_DATE_INVALID
| ERROR_WINHTTP_SECURE_CERT_REVOKED
| ERROR_WINHTTP_SECURE_CERT_REV_FAILED
| ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE
| ERROR_WINHTTP_SECURE_CHANNEL_ERROR
| ERROR_WINHTTP_SECURE_FAILURE
| ERROR_WINHTTP_SECURE_INVALID_CA
| ERROR_WINHTTP_SECURE_INVALID_CERT => RouteFailureClass::TlsError,
ERROR_WINHTTP_INVALID_URL | ERROR_WINHTTP_UNRECOGNIZED_SCHEME => {
RouteFailureClass::InvalidProxyConfig
}
ERROR_WINHTTP_CANNOT_CONNECT
| ERROR_WINHTTP_CONNECTION_ERROR
| ERROR_WINHTTP_NAME_NOT_RESOLVED => RouteFailureClass::ResolverError,
_ => RouteFailureClass::ResolverError,
}
}
@@ -187,9 +187,12 @@ pub enum RouteSource {
ConfigOverride,
Env,
System,
WindowsWinHttpPac,
WindowsStatic,
Direct,
Disabled,
Unavailable,
Error,
}
impl fmt::Display for RouteSource {
@@ -198,9 +201,12 @@ impl fmt::Display for RouteSource {
Self::ConfigOverride => "config_override",
Self::Env => "env",
Self::System => "system",
Self::WindowsWinHttpPac => "windows_winhttp_pac",
Self::WindowsStatic => "windows_static",
Self::Direct => "direct",
Self::Disabled => "disabled",
Self::Unavailable => "unavailable",
Self::Error => "error",
})
}
}
@@ -401,6 +407,25 @@ impl RouteDiagnostic {
"outbound route diagnostic"
);
}
/// Emit a redacted structured info event when diagnostics are explicitly enabled.
pub fn emit_opt_in(&self) {
if !network_diagnostics_enabled() {
return;
}
let failure = self
.failure
.map(|failure| failure.to_string())
.unwrap_or_else(|| "none".to_string());
tracing::info!(
route_target = %self.target,
source = %self.source,
decision = %self.decision,
failure = %failure,
custom_ca_configured = self.custom_ca_configured,
"opt-in outbound route diagnostic"
);
}
}
#[cfg(test)]
+9
View File
@@ -43,6 +43,7 @@ use codex_config::types::McpServerDisabledReason;
use codex_config::types::McpServerTransportConfig;
use codex_config::types::MemoriesConfig;
use codex_config::types::ModelAvailabilityNuxConfig;
use codex_config::types::NetworkConfigToml;
use codex_config::types::Notice;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_config::types::SessionPickerViewMode;
@@ -928,6 +929,9 @@ pub struct Config {
/// Base URL for requests to ChatGPT (as opposed to the OpenAI API).
pub chatgpt_base_url: String,
/// Host outbound proxy selection settings for resolver-aware clients.
pub network: Option<NetworkConfigToml>,
/// Optional path override for the host-owned apps MCP server.
pub apps_mcp_path_override: Option<String>,
@@ -1103,6 +1107,10 @@ impl AuthManagerConfig for Config {
fn chatgpt_base_url(&self) -> String {
self.chatgpt_base_url.clone()
}
fn network_config(&self) -> Option<NetworkConfigToml> {
self.network.clone()
}
}
#[derive(Clone, Default)]
@@ -3527,6 +3535,7 @@ impl Config {
chatgpt_base_url: cfg
.chatgpt_base_url
.unwrap_or("https://chatgpt.com/backend-api/".to_string()),
network: cfg.network,
apps_mcp_path_override,
apps_mcp_product_sku: cfg.apps_mcp_product_sku.clone(),
realtime_audio: cfg
+38 -5
View File
@@ -4,9 +4,12 @@
//! Use [`crate::default_client`] or [`codex_login::default_client`] from other crates in this
//! workspace.
use codex_client::BuildCustomCaTransportError;
use codex_client::BuildProxiedHttpClientError;
use codex_client::CodexHttpClient;
pub use codex_client::CodexRequestBuilder;
use codex_client::OutboundProxyConfig;
use codex_client::RouteTarget;
use codex_client::build_reqwest_client_for_route;
use codex_client::build_reqwest_client_with_custom_ca;
use codex_client::with_chatgpt_cloudflare_cookie_store;
use codex_terminal_detection::user_agent;
@@ -36,6 +39,7 @@ pub static USER_AGENT_SUFFIX: LazyLock<Mutex<Option<String>>> = LazyLock::new(||
pub const DEFAULT_ORIGINATOR: &str = "codex_cli_rs";
pub const CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR: &str = "CODEX_INTERNAL_ORIGINATOR_OVERRIDE";
pub const RESIDENCY_HEADER_NAME: &str = "x-openai-internal-codex-residency";
const DEFAULT_AUTH_ROUTE_URL: &str = "https://auth.openai.com/oauth/token";
pub use codex_config::ResidencyRequirement;
@@ -194,6 +198,13 @@ pub fn create_client() -> CodexHttpClient {
CodexHttpClient::new(inner)
}
pub fn create_client_with_proxy_config(
outbound_proxy_config: Option<&OutboundProxyConfig>,
) -> CodexHttpClient {
let inner = build_reqwest_client_with_proxy_config(outbound_proxy_config);
CodexHttpClient::new(inner)
}
/// Builds the default reqwest client used for ordinary Codex HTTP traffic.
///
/// This starts from the standard Codex user agent, default headers, and sandbox-specific proxy
@@ -201,7 +212,13 @@ pub fn create_client() -> CodexHttpClient {
/// `SSL_CERT_FILE`. The function remains infallible for compatibility with existing call sites, so
/// a custom-CA or builder failure is logged and falls back to `reqwest::Client::new()`.
pub fn build_reqwest_client() -> reqwest::Client {
try_build_reqwest_client().unwrap_or_else(|error| {
build_reqwest_client_with_proxy_config(/*outbound_proxy_config*/ None)
}
pub fn build_reqwest_client_with_proxy_config(
outbound_proxy_config: Option<&OutboundProxyConfig>,
) -> reqwest::Client {
try_build_reqwest_client_with_proxy_config(outbound_proxy_config).unwrap_or_else(|error| {
tracing::warn!(error = %error, "failed to build default reqwest client");
with_chatgpt_cloudflare_cookie_store(reqwest::Client::builder())
.build()
@@ -219,14 +236,30 @@ pub fn build_reqwest_client() -> reqwest::Client {
///
/// Callers that need a structured CA-loading failure instead of the legacy logged fallback can use
/// this method directly.
pub fn try_build_reqwest_client() -> Result<reqwest::Client, BuildCustomCaTransportError> {
pub fn try_build_reqwest_client() -> Result<reqwest::Client, BuildProxiedHttpClientError> {
try_build_reqwest_client_with_proxy_config(/*outbound_proxy_config*/ None)
}
pub fn try_build_reqwest_client_with_proxy_config(
outbound_proxy_config: Option<&OutboundProxyConfig>,
) -> Result<reqwest::Client, BuildProxiedHttpClientError> {
let mut builder = reqwest::Client::builder().default_headers(default_headers());
if is_sandboxed() {
let sandboxed = is_sandboxed();
if sandboxed {
builder = builder.no_proxy();
}
builder = with_chatgpt_cloudflare_cookie_store(builder);
build_reqwest_client_with_custom_ca(builder)
if sandboxed {
return build_reqwest_client_with_custom_ca(builder).map_err(Into::into);
}
build_reqwest_client_for_route(
builder,
DEFAULT_AUTH_ROUTE_URL,
RouteTarget::Auth,
outbound_proxy_config,
)
}
pub fn default_headers() -> HeaderMap {
+61 -9
View File
@@ -26,6 +26,7 @@ use codex_protocol::config_types::ModelProviderAuthInfo;
use super::external_bearer::BearerTokenRefresher;
use super::revoke::revoke_auth_tokens;
use super::revoke::revoke_auth_tokens_with_proxy_config;
pub use crate::auth::agent_identity::AgentIdentityAuth;
pub use crate::auth::storage::AgentIdentityAuthRecord;
pub use crate::auth::storage::AuthDotJson;
@@ -34,11 +35,15 @@ use crate::auth::storage::create_auth_storage;
use crate::auth::util::try_parse_error_message;
use crate::default_client::build_reqwest_client;
use crate::default_client::create_client;
use crate::default_client::create_client_with_proxy_config;
use crate::outbound_proxy::outbound_proxy_config_from_network_config;
use crate::token_data::TokenData;
use crate::token_data::parse_chatgpt_jwt_claims;
use crate::token_data::parse_jwt_expiration;
use codex_client::CodexHttpClient;
use codex_client::OutboundProxyConfig;
use codex_config::types::AuthCredentialsStoreMode;
use codex_config::types::NetworkConfigToml;
use codex_protocol::account::PlanType as AccountPlanType;
use codex_protocol::auth::PlanType as InternalPlanType;
use codex_protocol::auth::RefreshTokenFailedError;
@@ -203,9 +208,10 @@ impl CodexAuth {
auth_dot_json: AuthDotJson,
auth_credentials_store_mode: AuthCredentialsStoreMode,
chatgpt_base_url: Option<&str>,
outbound_proxy_config: Option<&OutboundProxyConfig>,
) -> std::io::Result<Self> {
let auth_mode = auth_dot_json.resolved_mode();
let client = create_client();
let client = create_client_with_proxy_config(outbound_proxy_config);
if auth_mode == ApiAuthMode::ApiKey {
let Some(api_key) = auth_dot_json.openai_api_key.as_deref() else {
return Err(std::io::Error::other("API key auth is missing a key."));
@@ -250,6 +256,7 @@ impl CodexAuth {
/*enable_codex_api_key_env*/ false,
auth_credentials_store_mode,
chatgpt_base_url,
/*outbound_proxy_config*/ None,
)
.await
}
@@ -622,6 +629,7 @@ pub async fn enforce_login_restrictions(config: &AuthConfig) -> std::io::Result<
/*enable_codex_api_key_env*/ true,
config.auth_credentials_store_mode,
config.chatgpt_base_url.as_deref(),
/*outbound_proxy_config*/ None,
)
.await?
else {
@@ -735,6 +743,7 @@ async fn load_auth(
enable_codex_api_key_env: bool,
auth_credentials_store_mode: AuthCredentialsStoreMode,
chatgpt_base_url: Option<&str>,
outbound_proxy_config: Option<&OutboundProxyConfig>,
) -> std::io::Result<Option<CodexAuth>> {
// API key via env var takes precedence over any other auth method.
if enable_codex_api_key_env && let Some(api_key) = read_codex_api_key_from_env() {
@@ -753,6 +762,7 @@ async fn load_auth(
auth_dot_json,
AuthCredentialsStoreMode::Ephemeral,
chatgpt_base_url,
outbound_proxy_config,
)
.await?;
return Ok(Some(auth));
@@ -781,6 +791,7 @@ async fn load_auth(
auth_dot_json,
auth_credentials_store_mode,
chatgpt_base_url,
outbound_proxy_config,
)
.await?;
Ok(Some(auth))
@@ -1261,6 +1272,7 @@ pub struct AuthManager {
chatgpt_base_url: Option<String>,
refresh_lock: Semaphore,
external_auth: RwLock<Option<Arc<dyn ExternalAuth>>>,
outbound_proxy_config: Option<OutboundProxyConfig>,
}
/// Configuration view required to construct a shared [`AuthManager`].
@@ -1281,6 +1293,11 @@ pub trait AuthManagerConfig {
/// Returns the ChatGPT backend base URL used for first-party backend authorization.
fn chatgpt_base_url(&self) -> String;
/// Returns host outbound proxy settings for auth-owned HTTP clients.
fn network_config(&self) -> Option<NetworkConfigToml> {
None
}
}
impl Debug for AuthManager {
@@ -1298,6 +1315,7 @@ impl Debug for AuthManager {
&self.forced_chatgpt_workspace_id,
)
.field("chatgpt_base_url", &self.chatgpt_base_url)
.field("outbound_proxy_config", &self.outbound_proxy_config)
.field("has_external_auth", &self.has_external_auth())
.finish_non_exhaustive()
}
@@ -1313,12 +1331,30 @@ impl AuthManager {
enable_codex_api_key_env: bool,
auth_credentials_store_mode: AuthCredentialsStoreMode,
chatgpt_base_url: Option<String>,
) -> Self {
Self::new_with_proxy_config(
codex_home,
enable_codex_api_key_env,
auth_credentials_store_mode,
chatgpt_base_url,
/*outbound_proxy_config*/ None,
)
.await
}
pub async fn new_with_proxy_config(
codex_home: PathBuf,
enable_codex_api_key_env: bool,
auth_credentials_store_mode: AuthCredentialsStoreMode,
chatgpt_base_url: Option<String>,
outbound_proxy_config: Option<OutboundProxyConfig>,
) -> Self {
let managed_auth = load_auth(
&codex_home,
enable_codex_api_key_env,
auth_credentials_store_mode,
chatgpt_base_url.as_deref(),
outbound_proxy_config.as_ref(),
)
.await
.ok()
@@ -1337,6 +1373,7 @@ impl AuthManager {
chatgpt_base_url,
refresh_lock: Semaphore::new(/*permits*/ 1),
external_auth: RwLock::new(None),
outbound_proxy_config,
}
}
@@ -1358,6 +1395,7 @@ impl AuthManager {
chatgpt_base_url: None,
refresh_lock: Semaphore::new(/*permits*/ 1),
external_auth: RwLock::new(None),
outbound_proxy_config: None,
})
}
@@ -1378,6 +1416,7 @@ impl AuthManager {
chatgpt_base_url: None,
refresh_lock: Semaphore::new(/*permits*/ 1),
external_auth: RwLock::new(None),
outbound_proxy_config: None,
})
}
@@ -1398,6 +1437,7 @@ impl AuthManager {
external_auth: RwLock::new(Some(
Arc::new(BearerTokenRefresher::new(config)) as Arc<dyn ExternalAuth>
)),
outbound_proxy_config: None,
})
}
@@ -1536,6 +1576,7 @@ impl AuthManager {
self.enable_codex_api_key_env,
self.auth_credentials_store_mode,
self.chatgpt_base_url.as_deref(),
self.outbound_proxy_config.as_ref(),
)
.await
.ok()
@@ -1626,13 +1667,19 @@ impl AuthManager {
config: &impl AuthManagerConfig,
enable_codex_api_key_env: bool,
) -> Arc<Self> {
let auth_manager = Self::shared(
config.codex_home(),
enable_codex_api_key_env,
config.cli_auth_credentials_store_mode(),
Some(config.chatgpt_base_url()),
)
.await;
let auth_manager = Arc::new(
Self::new_with_proxy_config(
config.codex_home(),
enable_codex_api_key_env,
config.cli_auth_credentials_store_mode(),
Some(config.chatgpt_base_url()),
config
.network_config()
.as_ref()
.map(outbound_proxy_config_from_network_config),
)
.await,
);
auth_manager.set_forced_chatgpt_workspace_id(config.forced_chatgpt_workspace_id());
auth_manager
}
@@ -1779,7 +1826,12 @@ impl AuthManager {
let auth_dot_json = self
.auth_cached()
.and_then(|auth| auth.get_current_auth_json());
if let Err(err) = revoke_auth_tokens(auth_dot_json.as_ref()).await {
if let Err(err) = revoke_auth_tokens_with_proxy_config(
auth_dot_json.as_ref(),
self.outbound_proxy_config.as_ref(),
)
.await
{
tracing::warn!("failed to revoke auth tokens during logout: {err}");
}
let result = logout_all_stores(&self.codex_home, self.auth_credentials_store_mode)?;
+1
View File
@@ -12,4 +12,5 @@ pub use error::RefreshTokenFailedError;
pub use error::RefreshTokenFailedReason;
pub use manager::*;
pub(crate) use revoke::revoke_auth_tokens;
pub(crate) use revoke::revoke_auth_tokens_with_proxy_config;
pub(crate) use revoke::should_revoke_auth_tokens;
+10 -2
View File
@@ -10,6 +10,7 @@ use std::time::Duration;
use codex_app_server_protocol::AuthMode as ApiAuthMode;
use codex_client::CodexHttpClient;
use codex_client::OutboundProxyConfig;
use super::manager::CLIENT_ID;
use super::manager::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR;
@@ -17,7 +18,7 @@ use super::manager::REVOKE_TOKEN_URL;
use super::manager::REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR;
use super::storage::AuthDotJson;
use super::util::try_parse_error_message;
use crate::default_client::create_client;
use crate::default_client::create_client_with_proxy_config;
use crate::token_data::TokenData;
const REVOKE_HTTP_TIMEOUT: Duration = Duration::from_secs(10);
@@ -54,12 +55,19 @@ struct RevokeTokenRequest<'a> {
pub(crate) async fn revoke_auth_tokens(
auth_dot_json: Option<&AuthDotJson>,
) -> Result<(), std::io::Error> {
revoke_auth_tokens_with_proxy_config(auth_dot_json, /*outbound_proxy_config*/ None).await
}
pub(crate) async fn revoke_auth_tokens_with_proxy_config(
auth_dot_json: Option<&AuthDotJson>,
outbound_proxy_config: Option<&OutboundProxyConfig>,
) -> Result<(), std::io::Error> {
let Some((token, kind)) = auth_dot_json.and_then(revocable_token) else {
return Ok(());
};
let client = create_client();
let client = create_client_with_proxy_config(outbound_proxy_config);
let endpoint = revoke_token_endpoint();
revoke_oauth_token(&client, endpoint.as_str(), token, kind, REVOKE_HTTP_TIMEOUT).await
}
+18 -3
View File
@@ -8,7 +8,8 @@ use std::time::Instant;
use crate::pkce::PkceCodes;
use crate::server::ServerOptions;
use codex_client::build_reqwest_client_with_custom_ca;
use codex_client::RouteTarget;
use codex_client::build_reqwest_client_for_route;
use std::io;
const ANSI_BLUE: &str = "\x1b[94m";
@@ -157,9 +158,15 @@ fn print_device_code_prompt(verification_url: &str, code: &str) {
}
pub async fn request_device_code(opts: &ServerOptions) -> std::io::Result<DeviceCode> {
let client = build_reqwest_client_with_custom_ca(reqwest::Client::builder())?;
let base_url = opts.issuer.trim_end_matches('/');
let api_base_url = format!("{base_url}/api/accounts");
let user_code_endpoint = format!("{api_base_url}/deviceauth/usercode");
let client = build_reqwest_client_for_route(
reqwest::Client::builder(),
&user_code_endpoint,
RouteTarget::Auth,
opts.outbound_proxy_config.as_ref(),
)?;
let uc = request_user_code(&client, &api_base_url, &opts.client_id).await?;
Ok(DeviceCode {
@@ -174,9 +181,15 @@ pub async fn complete_device_code_login(
opts: ServerOptions,
device_code: DeviceCode,
) -> std::io::Result<()> {
let client = build_reqwest_client_with_custom_ca(reqwest::Client::builder())?;
let base_url = opts.issuer.trim_end_matches('/');
let api_base_url = format!("{base_url}/api/accounts");
let token_endpoint = format!("{api_base_url}/deviceauth/token");
let client = build_reqwest_client_for_route(
reqwest::Client::builder(),
&token_endpoint,
RouteTarget::Auth,
opts.outbound_proxy_config.as_ref(),
)?;
let code_resp = poll_for_token(
&client,
@@ -199,6 +212,7 @@ pub async fn complete_device_code_login(
&redirect_uri,
&pkce,
&code_resp.authorization_code,
opts.outbound_proxy_config.as_ref(),
)
.await
.map_err(|err| std::io::Error::other(format!("device code exchange failed: {err}")))?;
@@ -217,6 +231,7 @@ pub async fn complete_device_code_login(
tokens.access_token,
tokens.refresh_token,
opts.cli_auth_credentials_store_mode,
opts.outbound_proxy_config.as_ref(),
)
.await
}
+2 -1
View File
@@ -3,10 +3,11 @@ pub mod auth_env_telemetry;
pub mod token_data;
mod device_code_auth;
mod outbound_proxy;
mod pkce;
mod server;
pub use codex_client::BuildCustomCaTransportError as BuildLoginHttpClientError;
pub use codex_client::BuildProxiedHttpClientError as BuildLoginHttpClientError;
pub use codex_config::types::AuthCredentialsStoreMode;
pub use device_code_auth::DeviceCode;
pub use device_code_auth::complete_device_code_login;
+19
View File
@@ -0,0 +1,19 @@
use codex_client::OutboundProxyConfig;
use codex_client::OutboundProxyMode;
use codex_config::types::NetworkConfigToml;
use codex_config::types::NetworkProxyMode;
pub(crate) fn outbound_proxy_config_from_network_config(
network: &NetworkConfigToml,
) -> OutboundProxyConfig {
let mode = match network.proxy_mode.unwrap_or_default() {
NetworkProxyMode::Auto => OutboundProxyMode::Auto,
NetworkProxyMode::Env => OutboundProxyMode::Env,
NetworkProxyMode::System => OutboundProxyMode::System,
NetworkProxyMode::Direct => OutboundProxyMode::Direct,
};
OutboundProxyConfig {
mode,
proxy_url: network.proxy_url.clone(),
}
}
+52 -12
View File
@@ -26,10 +26,11 @@ use std::time::Duration;
use crate::auth::AuthDotJson;
use crate::auth::load_auth_dot_json;
use crate::auth::revoke_auth_tokens;
use crate::auth::revoke_auth_tokens_with_proxy_config;
use crate::auth::save_auth;
use crate::auth::should_revoke_auth_tokens;
use crate::default_client::originator;
use crate::outbound_proxy::outbound_proxy_config_from_network_config;
use crate::pkce::PkceCodes;
use crate::pkce::generate_pkce;
use crate::token_data::TokenData;
@@ -37,11 +38,14 @@ use crate::token_data::parse_chatgpt_jwt_claims;
use base64::Engine;
use chrono::Utc;
use codex_app_server_protocol::AuthMode;
use codex_client::build_reqwest_client_with_custom_ca;
use codex_client::OutboundProxyConfig;
use codex_client::RouteTarget;
use codex_client::build_reqwest_client_for_route;
use codex_client::emit_auth_http_status;
use codex_client::emit_auth_network_environment_snapshot;
use codex_client::emit_auth_transport_failure;
use codex_config::types::AuthCredentialsStoreMode;
use codex_config::types::NetworkConfigToml;
use codex_utils_template::Template;
use rand::RngCore;
use serde_json::Value as JsonValue;
@@ -75,6 +79,7 @@ pub struct ServerOptions {
pub forced_chatgpt_workspace_id: Option<Vec<String>>,
pub codex_streamlined_login: bool,
pub cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
pub outbound_proxy_config: Option<OutboundProxyConfig>,
}
impl ServerOptions {
@@ -95,8 +100,13 @@ impl ServerOptions {
forced_chatgpt_workspace_id,
codex_streamlined_login: false,
cli_auth_credentials_store_mode,
outbound_proxy_config: None,
}
}
pub fn set_network_config(&mut self, network: Option<&NetworkConfigToml>) {
self.outbound_proxy_config = network.map(outbound_proxy_config_from_network_config);
}
}
/// Handle for a running login callback server.
@@ -338,8 +348,15 @@ async fn process_request(
}
};
match exchange_code_for_tokens(&opts.issuer, &opts.client_id, redirect_uri, pkce, &code)
.await
match exchange_code_for_tokens(
&opts.issuer,
&opts.client_id,
redirect_uri,
pkce,
&code,
opts.outbound_proxy_config.as_ref(),
)
.await
{
Ok(tokens) => {
if let Err(message) = ensure_workspace_allowed(
@@ -355,9 +372,14 @@ async fn process_request(
);
}
// Obtain API key via token-exchange and persist
let api_key = obtain_api_key(&opts.issuer, &opts.client_id, &tokens.id_token)
.await
.ok();
let api_key = obtain_api_key(
&opts.issuer,
&opts.client_id,
&tokens.id_token,
opts.outbound_proxy_config.as_ref(),
)
.await
.ok();
if let Err(err) = persist_tokens_async(
&opts.codex_home,
api_key.clone(),
@@ -365,6 +387,7 @@ async fn process_request(
tokens.access_token.clone(),
tokens.refresh_token.clone(),
opts.cli_auth_credentials_store_mode,
opts.outbound_proxy_config.as_ref(),
)
.await
{
@@ -720,6 +743,7 @@ pub(crate) async fn exchange_code_for_tokens(
redirect_uri: &str,
pkce: &PkceCodes,
code: &str,
outbound_proxy_config: Option<&OutboundProxyConfig>,
) -> io::Result<ExchangedTokens> {
#[derive(serde::Deserialize)]
struct TokenResponse {
@@ -728,9 +752,14 @@ pub(crate) async fn exchange_code_for_tokens(
refresh_token: String,
}
emit_auth_network_environment_snapshot(/*operation*/ "oauth_token_exchange");
let client = build_reqwest_client_with_custom_ca(reqwest::Client::builder())?;
let token_endpoint = format!("{}/oauth/token", issuer.trim_end_matches('/'));
emit_auth_network_environment_snapshot(/*operation*/ "oauth_token_exchange");
let client = build_reqwest_client_for_route(
reqwest::Client::builder(),
&token_endpoint,
RouteTarget::Auth,
outbound_proxy_config,
)?;
info!(
issuer = %sanitize_url_for_logging(issuer),
token_endpoint = %sanitize_url_for_logging(&token_endpoint),
@@ -799,6 +828,7 @@ pub(crate) async fn persist_tokens_async(
access_token: String,
refresh_token: String,
auth_credentials_store_mode: AuthCredentialsStoreMode,
outbound_proxy_config: Option<&OutboundProxyConfig>,
) -> io::Result<()> {
// Reuse existing synchronous logic but run it off the async runtime.
let codex_home = codex_home.to_path_buf();
@@ -836,7 +866,9 @@ pub(crate) async fn persist_tokens_async(
.map_err(|e| io::Error::other(format!("persist task failed: {e}")))??;
if should_revoke_auth_tokens(previous_auth.as_ref(), &auth)
&& let Err(err) = revoke_auth_tokens(previous_auth.as_ref()).await
&& let Err(err) =
revoke_auth_tokens_with_proxy_config(previous_auth.as_ref(), outbound_proxy_config)
.await
{
warn!("failed to revoke superseded auth tokens after login: {err}");
}
@@ -1128,15 +1160,21 @@ pub(crate) async fn obtain_api_key(
issuer: &str,
client_id: &str,
id_token: &str,
outbound_proxy_config: Option<&OutboundProxyConfig>,
) -> io::Result<String> {
// Token exchange for an API key access token
#[derive(serde::Deserialize)]
struct ExchangeResp {
access_token: String,
}
emit_auth_network_environment_snapshot(/*operation*/ "api_key_exchange");
let client = build_reqwest_client_with_custom_ca(reqwest::Client::builder())?;
let token_endpoint = format!("{}/oauth/token", issuer.trim_end_matches('/'));
emit_auth_network_environment_snapshot(/*operation*/ "api_key_exchange");
let client = build_reqwest_client_for_route(
reqwest::Client::builder(),
&token_endpoint,
RouteTarget::Auth,
outbound_proxy_config,
)?;
let resp = client
.post(token_endpoint)
.header("Content-Type", "application/x-www-form-urlencoded")
@@ -1241,6 +1279,7 @@ mod tests {
"new-access".to_string(),
"new-refresh".to_string(),
AuthCredentialsStoreMode::File,
/*outbound_proxy_config*/ None,
)
.await?;
@@ -1301,6 +1340,7 @@ mod tests {
"new-access".to_string(),
"shared-refresh".to_string(),
AuthCredentialsStoreMode::File,
/*outbound_proxy_config*/ None,
)
.await?;