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

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

View File

@@ -0,0 +1,100 @@
//! Helper binary for exercising shared custom CA environment handling in tests.
//!
//! The shared reqwest client honors `CODEX_CA_CERTIFICATE` and `SSL_CERT_FILE`, but those
//! environment variables are process-global and unsafe to mutate in parallel test execution. This
//! probe keeps the behavior under test while letting integration tests (`tests/ca_env.rs`) set
//! env vars per-process, proving:
//!
//! - env precedence is respected,
//! - multi-cert PEM bundles load,
//! - error messages guide users when CA files are invalid.
//! - optional HTTPS probes can complete a request through the constructed client.
//!
//! The detailed explanation of what "hermetic" means here lives in `codex_http_client::custom_ca`.
//! This binary exists so the tests can exercise
//! [`codex_http_client::build_reqwest_client_for_subprocess_tests`] in a separate process without
//! duplicating client-construction logic.
use std::env;
use std::process;
use std::time::Duration;
const PROBE_TLS13_ENV: &str = "CODEX_CUSTOM_CA_PROBE_TLS13";
const PROBE_PROXY_ENV: &str = "CODEX_CUSTOM_CA_PROBE_PROXY";
const PROBE_URL_ENV: &str = "CODEX_CUSTOM_CA_PROBE_URL";
fn main() {
let runtime = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(runtime) => runtime,
Err(error) => {
eprintln!("failed to create probe runtime: {error}");
process::exit(1);
}
};
match runtime.block_on(run_probe()) {
Ok(()) => println!("ok"),
Err(error) => {
eprintln!("{error}");
process::exit(1);
}
}
}
async fn run_probe() -> Result<(), String> {
let proxy_url = env::var(PROBE_PROXY_ENV).ok();
let target_url = env::var(PROBE_URL_ENV).ok();
let mut builder = reqwest::Client::builder();
if target_url.is_some() {
builder = builder.timeout(Duration::from_secs(5));
}
if env::var_os(PROBE_TLS13_ENV).is_some() {
builder = builder.min_tls_version(reqwest::tls::Version::TLS_1_3);
}
let client = build_probe_client(builder, proxy_url.as_deref())?;
if let Some(url) = target_url {
post_probe_request(&client, &url).await?;
}
Ok(())
}
fn build_probe_client(
builder: reqwest::ClientBuilder,
proxy_url: Option<&str>,
) -> Result<reqwest::Client, String> {
if let Some(proxy_url) = proxy_url {
let proxy = reqwest::Proxy::https(proxy_url)
.map_err(|error| format!("failed to configure probe proxy {proxy_url}: {error}"))?;
return codex_http_client::build_reqwest_client_with_custom_ca(builder.proxy(proxy))
.map_err(|error| error.to_string());
}
codex_http_client::build_reqwest_client_for_subprocess_tests(builder)
.map_err(|error| error.to_string())
}
async fn post_probe_request(client: &reqwest::Client, url: &str) -> Result<(), String> {
let response = client
.post(url)
.header("Content-Type", "application/x-www-form-urlencoded")
.body("grant_type=authorization_code&code=test")
.send()
.await
.map_err(|error| format!("probe request failed: {error:?}"))?;
let status = response.status();
let body = response
.text()
.await
.map_err(|error| format!("failed to read probe response body: {error}"))?;
if !status.is_success() {
return Err(format!("probe request returned {status}: {body}"));
}
if body != "ok" {
return Err(format!("probe response body mismatch: {body}"));
}
Ok(())
}

View File

@@ -0,0 +1,491 @@
//! ChatGPT cookies shared by HTTP and WebSocket transports. Only infrastructure cookies may be
//! stored globally; configured cookies remain scoped to their factory.
use std::sync::Arc;
use std::sync::LazyLock;
use http::HeaderMap;
use http::HeaderValue;
use http::Uri;
use http::header::SET_COOKIE;
use reqwest::cookie::CookieStore;
use reqwest::cookie::Jar;
use crate::HttpClientFactory;
use crate::chatgpt_hosts::is_allowed_chatgpt_host;
// WARNING: this HTTP cookie store is process-global and may be shared across auth contexts.
// It must only ever contain Cloudflare infrastructure cookies and the `__oailb`
// routing cookie. Never extend this store to persist ChatGPT account, session,
// auth, or other user-specific cookie data.
static SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE: LazyLock<Arc<ChatGptCloudflareCookieStore>> =
LazyLock::new(|| Arc::new(ChatGptCloudflareCookieStore::default()));
#[derive(Debug, Default)]
struct ChatGptCloudflareCookieStore {
jar: Jar,
}
pub(crate) struct ChatGptCookieStore {
cloudflare: Arc<ChatGptCloudflareCookieStore>,
cookies: Vec<HeaderValue>,
}
impl ChatGptCookieStore {
pub(crate) fn new(cookies: Vec<HeaderValue>) -> Self {
Self {
cloudflare: Arc::clone(&SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE),
cookies,
}
}
pub(crate) fn configured_cookies(&self) -> &[HeaderValue] {
&self.cookies
}
}
impl CookieStore for ChatGptCloudflareCookieStore {
fn set_cookies(
&self,
cookie_headers: &mut dyn Iterator<Item = &HeaderValue>,
url: &reqwest::Url,
) {
if !is_chatgpt_cookie_url(url) {
return;
}
let mut cloudflare_cookie_headers =
cookie_headers.filter(|header| is_allowed_cloudflare_set_cookie_header(header));
self.jar.set_cookies(&mut cloudflare_cookie_headers, url);
}
fn cookies(&self, url: &reqwest::Url) -> Option<HeaderValue> {
if is_chatgpt_cookie_url(url) {
self.jar.cookies(url).and_then(only_cloudflare_cookies)
} else {
None
}
}
}
impl CookieStore for ChatGptCookieStore {
fn set_cookies(
&self,
cookie_headers: &mut dyn Iterator<Item = &HeaderValue>,
url: &reqwest::Url,
) {
self.cloudflare.set_cookies(cookie_headers, url);
}
fn cookies(&self, url: &reqwest::Url) -> Option<HeaderValue> {
if !is_chatgpt_cookie_url(url) {
return self.cloudflare.cookies(url);
}
let cloudflare = self.cloudflare.cookies(url);
let mut sensitive = cloudflare.as_ref().is_some_and(HeaderValue::is_sensitive);
let mut cookies = cloudflare
.map(|cloudflare| cloudflare.as_bytes().to_vec())
.unwrap_or_default();
for cookie in &self.cookies {
sensitive |= cookie.is_sensitive();
if !cookies.is_empty() {
cookies.extend_from_slice(b"; ");
}
cookies.extend_from_slice(cookie.as_bytes());
}
if cookies.is_empty() {
None
} else {
let mut header = HeaderValue::from_bytes(&cookies).ok()?;
header.set_sensitive(sensitive);
Some(header)
}
}
}
impl HttpClientFactory {
/// Returns cookies for a ChatGPT HTTPS or WSS request, using the same store as HTTP clients.
/// Explicit request Cookie headers should take precedence over this value.
pub fn chatgpt_cookie_header(&self, uri: &Uri) -> Option<HeaderValue> {
let url = chatgpt_cookie_url(uri)?;
let mut cookies = match self.chatgpt_cookie_store() {
Some(store) => store.cookies(&url),
None => SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE.cookies(&url),
}?;
cookies.set_sensitive(true);
Some(cookies)
}
/// Retains only allowlisted infrastructure cookies from a ChatGPT HTTPS or WSS response.
/// Account and session cookies are never added to the shared store.
pub fn store_chatgpt_response_cookies(&self, uri: &Uri, headers: &HeaderMap) {
if let Some(url) = chatgpt_cookie_url(uri) {
SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE
.set_cookies(&mut headers.get_all(SET_COOKIE).iter(), &url);
}
}
}
pub(crate) fn chatgpt_cookie_url(uri: &Uri) -> Option<reqwest::Url> {
let mut url = reqwest::Url::parse(&uri.to_string()).ok()?;
// A secure WebSocket handshake has the same cookie scope as HTTPS.
if url.scheme() == "wss" {
url.set_scheme("https").ok()?;
}
is_chatgpt_cookie_url(&url).then_some(url)
}
/// Adds the process-local ChatGPT infrastructure cookie jar used by Codex HTTP clients.
///
/// WARNING: this jar is global within the process. It is only acceptable because it hardcodes a
/// small allowlist of Cloudflare cookie names plus `__oailb` for routing, and refuses all other
/// ChatGPT cookies. Do not store ChatGPT account, session, auth, or other user-specific cookies
/// here. If a future caller needs those cookies, the store must be scoped to the auth/session
/// owner instead of shared globally.
pub fn with_chatgpt_cloudflare_cookie_store(
builder: reqwest::ClientBuilder,
) -> reqwest::ClientBuilder {
builder.cookie_provider(Arc::clone(&SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE))
}
fn is_chatgpt_cookie_url(url: &reqwest::Url) -> bool {
match url.scheme() {
"https" => {}
_ => return false,
}
let Some(host) = url.host_str() else {
return false;
};
is_allowed_chatgpt_host(host)
}
fn is_allowed_cloudflare_set_cookie_header(header: &HeaderValue) -> bool {
header
.to_str()
.ok()
.and_then(set_cookie_name)
.is_some_and(is_allowed_cloudflare_cookie_name)
}
fn set_cookie_name(header: &str) -> Option<&str> {
let (name, _) = header.split_once('=')?;
let name = name.trim();
(!name.is_empty()).then_some(name)
}
fn only_cloudflare_cookies(header: HeaderValue) -> Option<HeaderValue> {
let header = header.to_str().ok()?;
let cookies = header
.split(';')
.filter_map(|cookie| {
let cookie = cookie.trim();
let name = cookie.split_once('=')?.0.trim();
is_allowed_cloudflare_cookie_name(name).then_some(cookie)
})
.collect::<Vec<_>>()
.join("; ");
if cookies.is_empty() {
None
} else {
HeaderValue::from_str(&cookies).ok()
}
}
fn is_allowed_cloudflare_cookie_name(name: &str) -> bool {
// `__oailb` is an OpenAI infrastructure routing cookie, not an authentication cookie.
// Keep this allowlist aligned with Cloudflare's documented service cookies:
// https://developers.cloudflare.com/fundamentals/reference/policies-compliances/cloudflare-cookies/
matches!(
name,
"__cf_bm"
| "__cflb"
| "__cfruid"
| "__cfseq"
| "__cfwaitingroom"
| "__oailb"
| "_cfuvid"
| "cf_clearance"
| "cf_ob_info"
| "cf_use_ob"
) || name.starts_with("cf_chl_")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use reqwest::cookie::CookieStore;
#[test]
fn http_and_websocket_cookies_share_the_factory_store() {
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_chatgpt_cookies([HeaderValue::from_static("configured=owner")]);
let store = factory.chatgpt_cookie_store().unwrap();
let https = reqwest::Url::parse("https://http-websocket-cookies.chatgpt.com/api").unwrap();
let wss: Uri = "wss://http-websocket-cookies.chatgpt.com/api"
.parse()
.unwrap();
let cookie = HeaderValue::from_static("__oailb=from-http; Path=/; Secure");
store.set_cookies(&mut std::iter::once(&cookie), &https);
let header = factory.chatgpt_cookie_header(&wss).unwrap();
assert_eq!(header, "__oailb=from-http; configured=owner");
assert!(header.is_sensitive());
let mut response_headers = HeaderMap::new();
response_headers.insert(
SET_COOKIE,
HeaderValue::from_static("__oailb=from-wss; Path=/; Secure"),
);
factory.store_chatgpt_response_cookies(&wss, &response_headers);
assert_eq!(
store.cookies(&https),
Some(HeaderValue::from_static(
"__oailb=from-wss; configured=owner"
))
);
assert_eq!(
factory.chatgpt_cookie_header(
&"ws://http-websocket-cookies.chatgpt.com/api"
.parse()
.unwrap()
),
None
);
assert_eq!(
factory.chatgpt_cookie_header(&"wss://api.openai.com/api".parse().unwrap()),
None
);
}
#[test]
fn additional_cookies_use_current_path_scoped_cloudflare_cookies() {
let cloudflare = Arc::new(ChatGptCloudflareCookieStore::default());
let mut sensitive_cookie = HeaderValue::from_static("additional=true");
sensitive_cookie.set_sensitive(true);
let store = ChatGptCookieStore {
cloudflare: Arc::clone(&cloudflare),
cookies: vec![
sensitive_cookie,
HeaderValue::from_static("another=enabled"),
],
};
let first_url = reqwest::Url::parse("https://cookies.chatgpt.com/a").unwrap();
let second_url = reqwest::Url::parse("https://cookies.chatgpt.com/b").unwrap();
let affinity = HeaderValue::from_static("__cflb=current; Path=/a; Secure");
cloudflare.set_cookies(&mut std::iter::once(&affinity), &first_url);
assert_eq!(
store.cookies(&first_url),
Some(HeaderValue::from_static(
"__cflb=current; additional=true; another=enabled"
))
);
assert!(store.cookies(&first_url).unwrap().is_sensitive());
assert_eq!(
store.cookies(&second_url),
Some(HeaderValue::from_static("additional=true; another=enabled"))
);
let expired = HeaderValue::from_static("__cflb=; Max-Age=0; Path=/a; Secure");
store.set_cookies(&mut std::iter::once(&expired), &first_url);
assert_eq!(
store.cookies(&first_url),
Some(HeaderValue::from_static("additional=true; another=enabled"))
);
}
#[test]
fn additional_cookies_are_restricted_to_https_chatgpt_hosts() {
let store = ChatGptCookieStore {
cloudflare: Arc::new(ChatGptCloudflareCookieStore::default()),
cookies: vec![HeaderValue::from_static("additional=true")],
};
for url in ["http://chatgpt.com/a", "https://api.openai.com/a"] {
let url = reqwest::Url::parse(url).unwrap();
assert_eq!(store.cookies(&url), None);
}
let url = reqwest::Url::parse("https://chatgpt.com/a").unwrap();
assert_eq!(
store.cookies(&url),
Some(HeaderValue::from_static("additional=true"))
);
assert!(!store.cookies(&url).unwrap().is_sensitive());
}
#[test]
fn stores_and_returns_cloudflare_cookies_for_chatgpt_hosts() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let load_balancer = HeaderValue::from_static("__cflb=west; Path=/; Secure; HttpOnly");
let cfuvid = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
let clearance =
HeaderValue::from_static("cf_clearance=clearance; Path=/; Secure; HttpOnly");
store.set_cookies(&mut [&load_balancer, &cfuvid, &clearance].into_iter(), &url);
let mut cookies = store
.cookies(&url)
.and_then(|value| value.to_str().ok().map(str::to_string))
.map(|header| {
header
.split("; ")
.map(str::to_string)
.collect::<Vec<String>>()
})
.unwrap_or_default();
cookies.sort();
assert_eq!(
cookies,
vec![
"__cflb=west".to_string(),
"_cfuvid=visitor".to_string(),
"cf_clearance=clearance".to_string()
]
);
}
#[test]
fn oailb_cookies_are_replayed_with_scope_and_expiration() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let cookie = HeaderValue::from_static(
"__oailb=route; Path=/backend-api; Max-Age=3600; Secure; HttpOnly; SameSite=Lax",
);
store.set_cookies(&mut std::iter::once(&cookie), &url);
let followup_url = reqwest::Url::parse("https://chatgpt.com/backend-api/ps/mcp").unwrap();
assert_eq!(
store.cookies(&followup_url),
Some(HeaderValue::from_static("__oailb=route"))
);
for outside_scope in [
"https://chatgpt.com/",
"https://other.chatgpt.com/backend-api/ps/mcp",
"https://api.openai.com/backend-api/ps/mcp",
"http://chatgpt.com/backend-api/ps/mcp",
] {
let outside_scope = reqwest::Url::parse(outside_scope).unwrap();
assert_eq!(store.cookies(&outside_scope), None);
}
let expired = HeaderValue::from_static(
"__oailb=; Path=/backend-api; Max-Age=0; Secure; HttpOnly; SameSite=Lax",
);
store.set_cookies(&mut std::iter::once(&expired), &url);
assert_eq!(store.cookies(&followup_url), None);
}
#[test]
fn ignores_non_chatgpt_cookies() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://api.openai.com/v1/responses").unwrap();
let set_cookie = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
store.set_cookies(&mut std::iter::once(&set_cookie), &url);
assert_eq!(store.cookies(&url), None);
}
#[test]
fn ignores_non_cloudflare_cookies_for_chatgpt_hosts() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let set_cookie = HeaderValue::from_static(
"__Secure-next-auth.session-token=secret; Path=/; Secure; HttpOnly",
);
store.set_cookies(&mut std::iter::once(&set_cookie), &url);
assert_eq!(store.cookies(&url), None);
}
#[test]
fn ignores_mixed_non_cloudflare_cookies_for_chatgpt_hosts() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let cfuvid = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
let account_cookie =
HeaderValue::from_static("chatgpt_session=secret; Path=/; Secure; HttpOnly");
store.set_cookies(&mut [&cfuvid, &account_cookie].into_iter(), &url);
assert_eq!(
store
.cookies(&url)
.and_then(|value| value.to_str().ok().map(str::to_string)),
Some("_cfuvid=visitor".to_string())
);
}
#[test]
fn does_not_return_chatgpt_cloudflare_cookies_for_other_hosts() {
let store = ChatGptCloudflareCookieStore::default();
let chatgpt_url =
reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let api_url = reqwest::Url::parse("https://api.openai.com/v1/responses").unwrap();
let set_cookie = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
store.set_cookies(&mut std::iter::once(&set_cookie), &chatgpt_url);
assert_eq!(store.cookies(&api_url), None);
}
#[test]
fn rejects_plain_http_chatgpt_cookie_urls() {
let store = ChatGptCloudflareCookieStore::default();
let http_url = reqwest::Url::parse("http://chatgpt.com/backend-api/codex/responses")
.expect("URL should parse");
let https_url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses")
.expect("URL should parse");
let set_cookie = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
store.set_cookies(&mut std::iter::once(&set_cookie), &http_url);
assert_eq!(store.cookies(&http_url), None);
assert_eq!(store.cookies(&https_url), None);
}
#[test]
fn only_allows_https_urls() {
let url = reqwest::Url::parse("http://chatgpt.com/backend-api/codex/responses").unwrap();
assert!(!is_chatgpt_cookie_url(&url));
let url = reqwest::Url::parse("wss://chatgpt.com/backend-api/codex/responses").unwrap();
assert!(!is_chatgpt_cookie_url(&url));
}
#[test]
fn allows_only_known_cloudflare_cookie_names() {
for name in [
"__cf_bm",
"__cflb",
"__cfruid",
"__cfseq",
"__cfwaitingroom",
"_cfuvid",
"cf_clearance",
"cf_ob_info",
"cf_use_ob",
"cf_chl_rc_i",
] {
assert!(is_allowed_cloudflare_cookie_name(name));
}
for name in [
"__Secure-next-auth.session-token",
"chatgpt_session",
"oai-auth-token",
"not_cf_clearance",
] {
assert!(!is_allowed_cloudflare_cookie_name(name));
}
}
}

View File

@@ -0,0 +1,39 @@
/// Returns whether `host` is one of the ChatGPT hosts Codex is allowed to treat
/// as first-party ChatGPT HTTP traffic.
pub fn is_allowed_chatgpt_host(host: &str) -> bool {
const EXACT_HOSTS: &[&str] = &["chatgpt.com", "chat.openai.com", "chatgpt-staging.com"];
const SUBDOMAIN_SUFFIXES: &[&str] = &[".chatgpt.com", ".chatgpt-staging.com"];
EXACT_HOSTS.contains(&host)
|| SUBDOMAIN_SUFFIXES
.iter()
.any(|suffix| host.ends_with(suffix))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn recognizes_chatgpt_hosts_without_suffix_tricks() {
for host in [
"chatgpt.com",
"foo.chatgpt.com",
"staging.chatgpt.com",
"chat.openai.com",
"chatgpt-staging.com",
"api.chatgpt-staging.com",
] {
assert!(is_allowed_chatgpt_host(host));
}
for host in [
"evilchatgpt.com",
"chatgpt.com.evil.example",
"api.openai.com",
"foo.chat.openai.com",
] {
assert!(!is_allowed_chatgpt_host(host));
}
}
}

View File

@@ -0,0 +1,115 @@
//! Connection-owned ChatGPT routing pins. Keep only the handshake's routing cookies,
//! with their original expiry, and never forward them outside the original endpoint.
use std::sync::Arc;
use http::HeaderMap;
use http::HeaderValue;
use http::Uri;
use http::header::SET_COOKIE;
use reqwest::cookie::CookieStore;
use reqwest::cookie::Jar;
use url::Url;
use crate::chatgpt_cloudflare_cookies::chatgpt_cookie_url;
const ROUTING_COOKIE_NAMES: [&str; 2] = ["__oailb", "__cflb"];
/// A routing pin returned by one connection, independent of the process-wide cookie jar.
/// This is a best-effort hint: the edge still validates the cookie and may fail over.
/// Equality identifies the captured connection, independently of cookie expiry, so a live
/// colocated reviewer socket need not be disconnected when its handshake cookie expires.
#[derive(Clone)]
pub struct ChatGptRoutingAffinity {
url: Url,
jar: Arc<Jar>,
}
impl std::fmt::Debug for ChatGptRoutingAffinity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChatGptRoutingAffinity")
.finish_non_exhaustive()
}
}
impl PartialEq for ChatGptRoutingAffinity {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.jar, &other.jar)
}
}
impl Eq for ChatGptRoutingAffinity {}
impl ChatGptRoutingAffinity {
/// Captures valid `__oailb` and Cloudflare's native `__cflb` response cookies.
/// Ambiguous or oversized cookies reject the pin; request cookies alone cannot establish
/// where failover landed. Cookie scope and expiry remain owned by the private jar.
pub fn from_response(uri: &Uri, headers: &HeaderMap) -> Option<Self> {
let url = chatgpt_cookie_url(uri)?;
let mut cookies = Vec::with_capacity(2);
for name in ROUTING_COOKIE_NAMES {
let mut matches = headers.get_all(SET_COOKIE).iter().filter(|header| {
header
.to_str()
.ok()
.and_then(|value| value.split_once('='))
.is_some_and(|(cookie_name, _)| cookie_name.trim() == name)
});
if let Some(cookie) = matches.next() {
if cookie.as_bytes().len() > 8192 || matches.next().is_some() {
return None;
}
cookies.push(cookie);
}
}
let jar = Jar::default();
jar.set_cookies(&mut cookies.into_iter(), &url);
jar.cookies(&url)?;
Some(Self {
url,
jar: Arc::new(jar),
})
}
/// Returns the still-valid pin only for the same secure ChatGPT origin and endpoint path.
/// The private jar retains Max-Age/Expires and is never refreshed by unrelated traffic.
pub fn cookie_header(&self, uri: &Uri) -> Option<HeaderValue> {
let url = chatgpt_cookie_url(uri)?;
if url.origin() != self.url.origin() || url.path() != self.url.path() {
return None;
}
let mut cookie = self.jar.cookies(&url)?;
cookie.set_sensitive(true);
Some(cookie)
}
/// Replaces routing cookies with the scoped pin while preserving unrelated cookies.
/// Returns `None` when the pin is no longer valid for this endpoint.
pub fn merge_cookie_header(
&self,
uri: &Uri,
existing: Option<&HeaderValue>,
) -> Option<HeaderValue> {
let pin = self.cookie_header(uri)?;
let mut parts = existing
.and_then(|value| value.to_str().ok())
.into_iter()
.flat_map(|value| value.split(';'))
.map(str::trim)
.filter(|part| {
!part.is_empty()
&& !part
.split_once('=')
.is_some_and(|(name, _)| ROUTING_COOKIE_NAMES.contains(&name.trim()))
})
.collect::<Vec<_>>();
parts.push(pin.to_str().ok()?);
let mut cookies = HeaderValue::from_str(&parts.join("; ")).ok()?;
cookies.set_sensitive(true);
Some(cookies)
}
}
#[cfg(test)]
#[path = "chatgpt_routing_affinity_tests.rs"]
mod tests;

View File

@@ -0,0 +1,100 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn affinity_retains_only_the_response_pin_with_its_cookie_scope_and_expiry() {
let uri: Uri = "wss://affinity.chatgpt.com/backend-api/codex/responses"
.parse()
.unwrap();
let mut headers = HeaderMap::new();
headers.append(
SET_COOKIE,
HeaderValue::from_static("__oailb=parent; Path=/backend-api; Max-Age=3600; Secure"),
);
headers.append(
SET_COOKIE,
HeaderValue::from_static("__cflb=parent-native; Path=/backend-api; Max-Age=3600; Secure"),
);
headers.append(
SET_COOKIE,
HeaderValue::from_static("chatgpt_session=secret; Path=/; Secure"),
);
let affinity = ChatGptRoutingAffinity::from_response(&uri, &headers).unwrap();
let pin = affinity.cookie_header(&uri).unwrap();
let mut cookies = pin.to_str().unwrap().split("; ").collect::<Vec<_>>();
cookies.sort_unstable();
assert_eq!(cookies, ["__cflb=parent-native", "__oailb=parent"]);
assert!(pin.is_sensitive());
let existing = HeaderValue::from_static(
"__oailb=old; cf_clearance=keep; __cflb=old-native; configured=keep",
);
let merged = affinity.merge_cookie_header(&uri, Some(&existing)).unwrap();
let mut cookies = merged.to_str().unwrap().split("; ").collect::<Vec<_>>();
cookies.sort_unstable();
assert_eq!(
cookies,
[
"__cflb=parent-native",
"__oailb=parent",
"cf_clearance=keep",
"configured=keep",
]
);
assert!(merged.is_sensitive());
assert_eq!(
affinity.merge_cookie_header(&uri, /*existing*/ None),
Some(pin.clone())
);
assert_eq!(format!("{affinity:?}"), "ChatGptRoutingAffinity { .. }");
for outside_scope in [
"ws://affinity.chatgpt.com/backend-api/codex/responses",
"wss://other.chatgpt.com/backend-api/codex/responses",
"wss://affinity.chatgpt.com:444/backend-api/codex/responses",
"wss://affinity.chatgpt.com/backend-api/codex/other",
"wss://api.openai.com/backend-api/codex/responses",
] {
assert_eq!(
affinity.cookie_header(&outside_scope.parse().unwrap()),
None
);
assert_eq!(
affinity.merge_cookie_header(&outside_scope.parse().unwrap(), Some(&existing)),
None
);
}
for name in ["__oailb", "__cflb"] {
headers.insert(
SET_COOKIE,
HeaderValue::from_str(&format!("{name}=only; Path=/; Secure")).unwrap(),
);
assert_eq!(
ChatGptRoutingAffinity::from_response(&uri, &headers)
.unwrap()
.cookie_header(&uri),
Some(HeaderValue::from_str(&format!("{name}=only")).unwrap())
);
for invalid in [
"__oailb=deleted; Path=/; Max-Age=0; Secure",
"__oailb=expired; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure",
"__oailb=wrong-path; Path=/elsewhere; Secure",
"__oailb=wrong-domain; Domain=other.chatgpt.com; Path=/; Secure",
"chatgpt_session=secret; Path=/; Secure",
] {
headers.insert(
SET_COOKIE,
HeaderValue::from_str(&invalid.replace("__oailb", name)).unwrap(),
);
assert!(ChatGptRoutingAffinity::from_response(&uri, &headers).is_none());
}
headers.insert(
SET_COOKIE,
HeaderValue::from_str(&format!("{name}=one; Path=/; Secure")).unwrap(),
);
headers.append(
SET_COOKIE,
HeaderValue::from_str(&format!("{name}=two; Path=/; Secure")).unwrap(),
);
assert!(ChatGptRoutingAffinity::from_response(&uri, &headers).is_none());
}
assert_eq!(affinity.cookie_header(&uri), Some(pin));
}

View File

@@ -0,0 +1,299 @@
//! Selects direct or routed HTTP execution and owns transport diagnostics.
use http::HeaderMap;
use http::HeaderName;
use http::HeaderValue;
use opentelemetry::global;
use opentelemetry::propagation::Injector;
use reqwest::IntoUrl;
use reqwest::Method;
use std::sync::Arc;
use tracing::Span;
use tracing_opentelemetry::OpenTelemetrySpanExt;
use crate::RequestBuilder;
use crate::RouteAwareClientPool;
pub type HttpError = crate::RouteAwareRequestError;
/// Reusable HTTP client with shared tracing and request diagnostics.
///
/// Product callers should obtain this through [`crate::HttpClientFactory`] for a fixed
/// destination or use [`crate::RouteAwareClientPool`] when request and redirect URLs can vary.
#[derive(Clone, Debug)]
pub struct HttpClient {
pub(crate) backend: HttpClientBackend,
}
#[derive(Clone, Debug)]
pub(crate) enum HttpClientBackend {
Direct(TransportClient),
Routed(Arc<RouteAwareClientPool>),
}
/// A resolved transport used by direct clients and the route cache.
#[derive(Clone)]
pub(crate) struct TransportClient {
pub(crate) inner: reqwest::Client,
pub(crate) request_logging: RequestLogging,
default_headers: Arc<HeaderMap>,
}
impl std::fmt::Debug for TransportClient {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("TransportClient")
.field("request_logging", &self.request_logging)
.finish_non_exhaustive()
}
}
impl HttpClient {
pub fn new(inner: reqwest::Client) -> Self {
Self {
backend: HttpClientBackend::Direct(TransportClient {
inner,
request_logging: RequestLogging::Enabled,
default_headers: Arc::new(HeaderMap::new()),
}),
}
}
/// Suppresses diagnostics for endpoints whose URLs or headers may contain credentials.
pub fn new_without_request_logging(inner: reqwest::Client) -> Self {
Self::new(inner).without_request_logging()
}
/// Suppresses URL and response-header diagnostics while preserving this client's routing.
pub fn without_request_logging(mut self) -> Self {
match &mut self.backend {
HttpClientBackend::Direct(client) => client.request_logging = RequestLogging::Disabled,
HttpClientBackend::Routed(pool) => {
Arc::make_mut(pool).client_builder.request_logging = RequestLogging::Disabled;
}
}
self
}
pub(crate) fn from_parts(
inner: reqwest::Client,
request_logging: RequestLogging,
default_headers: HeaderMap,
) -> Self {
Self {
backend: HttpClientBackend::Direct(TransportClient::new(
inner,
request_logging,
default_headers,
)),
}
}
pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.request(Method::GET, url)
}
pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.request(Method::HEAD, url)
}
pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.request(Method::POST, url)
}
pub fn delete<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.request(Method::DELETE, url)
}
pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
match &self.backend {
HttpClientBackend::Direct(client) => RequestBuilder::direct(client, method, url),
HttpClientBackend::Routed(pool) => {
RequestBuilder::routed(Arc::clone(pool), method, url)
}
}
}
pub(crate) fn request_logging_enabled(&self) -> bool {
match &self.backend {
HttpClientBackend::Direct(client) => client.request_logging == RequestLogging::Enabled,
HttpClientBackend::Routed(pool) => {
pool.client_builder.request_logging == RequestLogging::Enabled
}
}
}
}
pub(crate) fn apply_default_headers(headers: &mut HeaderMap, defaults: &HeaderMap) {
for name in defaults.keys() {
if !headers.contains_key(name) {
for value in defaults.get_all(name) {
headers.append(name.clone(), value.clone());
}
}
}
}
impl TransportClient {
pub(crate) fn new(
inner: reqwest::Client,
request_logging: RequestLogging,
default_headers: HeaderMap,
) -> Self {
Self {
inner,
request_logging,
default_headers: Arc::new(default_headers),
}
}
pub(crate) async fn execute(
&self,
request: reqwest::Request,
) -> Result<reqwest::Response, reqwest::Error> {
let method = request.method().clone();
let url = request.url().to_string();
let result = self.execute_without_request_logging(request).await;
match result {
Ok(response) => {
self.log_response(&method, &url, &response);
Ok(response)
}
Err(error) => {
self.log_error(&method, &url, &error);
Err(error)
}
}
}
pub(crate) async fn execute_without_request_logging(
&self,
mut request: reqwest::Request,
) -> Result<reqwest::Response, reqwest::Error> {
apply_default_headers(request.headers_mut(), &self.default_headers);
request.headers_mut().extend(trace_headers());
self.inner.execute(request).await
}
pub(crate) fn log_response(&self, method: &Method, url: &str, response: &reqwest::Response) {
if self.request_logging == RequestLogging::Enabled {
tracing::debug!(
method = %method,
url = %url,
status = %response.status(),
headers = ?response.headers(),
version = ?response.version(),
"Request completed"
);
}
}
pub(crate) fn log_error(&self, method: &Method, url: &str, error: &reqwest::Error) {
if self.request_logging == RequestLogging::Enabled {
tracing::debug!(
method = %method,
url = %url,
status = error.status().map(|status| status.as_u16()),
error = %error,
"Request failed"
);
}
}
pub(crate) fn log_error_summary(&self, method: &Method, url: &str, error: &reqwest::Error) {
if self.request_logging == RequestLogging::Enabled {
tracing::debug!(
method = %method,
url = %url,
status = error.status().map(|status| status.as_u16()),
is_timeout = error.is_timeout(),
is_connect = error.is_connect(),
"Request failed"
);
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum RequestLogging {
#[default]
Enabled,
Disabled,
}
struct HeaderMapInjector<'a>(&'a mut HeaderMap);
impl<'a> Injector for HeaderMapInjector<'a> {
fn set(&mut self, key: &str, value: String) {
if let (Ok(name), Ok(val)) = (
HeaderName::from_bytes(key.as_bytes()),
HeaderValue::from_str(&value),
) {
self.0.insert(name, val);
}
}
}
pub(crate) fn trace_headers() -> HeaderMap {
let mut headers = HeaderMap::new();
global::get_text_map_propagator(|prop| {
prop.inject_context(
&Span::current().context(),
&mut HeaderMapInjector(&mut headers),
);
});
headers
}
#[cfg(test)]
mod tests {
use super::*;
use opentelemetry::propagation::Extractor;
use opentelemetry::propagation::TextMapPropagator;
use opentelemetry::trace::TraceContextExt;
use opentelemetry::trace::TracerProvider;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use opentelemetry_sdk::trace::SdkTracerProvider;
use pretty_assertions::assert_eq;
use tracing::trace_span;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
#[test]
fn inject_trace_headers_uses_current_span_context() {
global::set_text_map_propagator(TraceContextPropagator::new());
let provider = SdkTracerProvider::builder().build();
let tracer = provider.tracer("test-tracer");
let subscriber =
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer));
let _guard = subscriber.set_default();
let span = trace_span!("client_request");
let _entered = span.enter();
let span_context = span.context().span().span_context().clone();
let headers = trace_headers();
let extractor = HeaderMapExtractor(&headers);
let extracted = TraceContextPropagator::new().extract(&extractor);
let extracted_span = extracted.span();
let extracted_context = extracted_span.span_context();
assert!(extracted_context.is_valid());
assert_eq!(extracted_context.trace_id(), span_context.trace_id());
assert_eq!(extracted_context.span_id(), span_context.span_id());
}
struct HeaderMapExtractor<'a>(&'a HeaderMap);
impl<'a> Extractor for HeaderMapExtractor<'a> {
fn get(&self, key: &str) -> Option<&str> {
self.0.get(key).and_then(|value| value.to_str().ok())
}
fn keys(&self) -> Vec<&str> {
self.0.keys().map(HeaderName::as_str).collect()
}
}
}

View File

@@ -0,0 +1,464 @@
//! HTTP client construction that makes outbound proxy policy explicit.
//!
//! Product traffic should normally enter through [`HttpClientFactory`] for a fixed destination or
//! [`crate::RouteAwareClientPool`] when request and redirect URLs can vary. The direct and
//! transport-default terminal methods exist only for narrow exceptional or legacy compatibility
//! paths.
use http::HeaderMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
use crate::BuildCustomCaTransportError;
use crate::BuildRouteAwareHttpClientError;
use crate::ClientRouteClass;
use crate::HttpClient;
use crate::HttpClientFactory;
use crate::HttpClientTlsConfig;
use crate::OutboundProxyRoute;
use crate::chatgpt_cloudflare_cookies::ChatGptCookieStore;
use crate::client::HttpClientBackend;
use crate::client::RequestLogging;
use crate::client::TransportClient;
use crate::custom_ca::build_reqwest_client_with_custom_ca;
use crate::with_chatgpt_cloudflare_cookie_store;
/// Configures an [`HttpClient`] without exposing the underlying HTTP implementation.
///
/// Product traffic should prefer [`HttpClientFactory::build_client`] or finish this builder with
/// [`Self::build_respecting_outbound_proxy_policy`]. The other terminal methods deliberately
/// bypass the factory and are restricted to documented exceptional or legacy compatibility paths.
#[derive(Clone)]
pub struct HttpClientBuilder {
http2_prior_knowledge: bool,
disable_pool_idle_timeout: bool,
pub(crate) default_headers: Option<HeaderMap>,
follow_redirects: bool,
pub(crate) redirect_observed: Option<Arc<AtomicBool>>,
pub(crate) connect_timeout: Option<Duration>,
chatgpt_cloudflare_cookie_store: bool,
chatgpt_cookie_store: Option<Arc<ChatGptCookieStore>>,
pub(crate) request_logging: RequestLogging,
tls_backend: TlsBackend,
pub(crate) tls: HttpClientTlsConfig,
#[cfg(windows)]
windows_proxy_pipe_path: Option<std::path::PathBuf>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
enum TlsBackend {
#[default]
TransportDefault,
Rustls,
}
impl HttpClientFactory {
/// Builds an HTTP client for one fixed destination using the configured proxy policy.
///
/// This is the preferred construction path for product traffic that uses a fixed destination.
/// Use [`crate::RouteAwareClientPool`] instead when request or redirect URLs can vary.
pub fn build_client(
&self,
request_url: &str,
route_class: ClientRouteClass,
) -> Result<HttpClient, BuildRouteAwareHttpClientError> {
HttpClientBuilder::new().build_respecting_outbound_proxy_policy(
self,
request_url,
route_class,
)
}
/// Builds a policy-aware client without request URL or response-header diagnostics.
///
/// This has the same routing guidance as [`Self::build_client`].
pub fn build_client_without_request_logging(
&self,
request_url: &str,
route_class: ClientRouteClass,
) -> Result<HttpClient, BuildRouteAwareHttpClientError> {
HttpClientBuilder::new()
.without_request_logging()
.build_respecting_outbound_proxy_policy(self, request_url, route_class)
}
}
impl HttpClientBuilder {
/// Builds a strict pooled client with explicit TLS settings and the factory's proxy policy.
/// Route and transport construction failures are returned when sending a request.
pub fn build_with_tls(
mut self,
http_client_factory: &HttpClientFactory,
route_class: ClientRouteClass,
tls: HttpClientTlsConfig,
) -> HttpClient {
self.tls = tls;
crate::RouteAwareClientPool::with_builder(http_client_factory.clone(), route_class, self)
.with_tls_backend_fallback()
.into_client()
}
/// Uses HTTP/2 for SDKs such as gRPC that require framed bidirectional bodies.
pub fn http2_prior_knowledge(mut self) -> Self {
// Native TLS may lack ALPN support; HTTPS HTTP/2 requires advertising h2.
self.tls_backend = TlsBackend::Rustls;
self.http2_prior_knowledge = true;
self
}
/// Keep pooled connections reusable during long gaps between requests.
pub fn without_pool_idle_timeout(mut self) -> Self {
self.disable_pool_idle_timeout = true;
self
}
pub fn new() -> Self {
Self::default()
}
/// Applies every configured value unless the request sets that header explicitly.
pub fn default_headers(mut self, headers: HeaderMap) -> Self {
self.default_headers = Some(headers);
self
}
pub fn without_redirects(mut self) -> Self {
self.follow_redirects = false;
self
}
/// Marks the supplied flag when a redirect is encountered, preserving the default policy.
/// Use a fresh flag for each operation whose retry safety depends on its redirect history.
pub fn with_redirect_tracking(mut self, redirect_observed: Arc<AtomicBool>) -> Self {
self.redirect_observed = Some(redirect_observed);
self
}
pub(crate) fn follows_redirects(&self) -> bool {
self.follow_redirects
}
pub(crate) fn request_logging_enabled(&self) -> bool {
self.request_logging == RequestLogging::Enabled
}
pub(crate) fn with_rustls_tls(mut self) -> Self {
self.tls_backend = TlsBackend::Rustls;
self
}
/// Limits only connection establishment, not the request as a whole.
pub fn connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = Some(timeout);
self
}
pub fn with_chatgpt_cloudflare_cookie_store(mut self) -> Self {
self.chatgpt_cloudflare_cookie_store = true;
self
}
/// Uses the factory's configured ChatGPT cookies without changing proxy behavior.
pub fn with_chatgpt_cookies(mut self, http_client_factory: &HttpClientFactory) -> Self {
self.chatgpt_cloudflare_cookie_store = true;
self.chatgpt_cookie_store = http_client_factory.chatgpt_cookie_store();
self
}
/// Suppresses request URL and response-header diagnostics.
pub fn without_request_logging(mut self) -> Self {
self.request_logging = RequestLogging::Disabled;
self
}
/// Builds a client that honors the [`HttpClientFactory`] outbound proxy policy.
///
/// This is the preferred terminal method for product traffic. The request URL is used to
/// resolve a concrete direct or proxy route when the factory is configured with
/// [`crate::OutboundProxyPolicy::RespectSystemProxy`].
pub fn build_respecting_outbound_proxy_policy(
mut self,
http_client_factory: &HttpClientFactory,
request_url: &str,
route_class: ClientRouteClass,
) -> Result<HttpClient, BuildRouteAwareHttpClientError> {
if http_client_factory.network_policy().is_managed()
|| http_client_factory.protects_sensitive_headers()
{
return Ok(crate::RouteAwareClientPool::with_builder(
http_client_factory.clone(),
route_class,
self,
)
.into_client());
}
let route = http_client_factory.resolve_proxy_route(request_url);
#[cfg(windows)]
if crate::windows_proxy_auth::can_authenticate_route(request_url, &route) {
return Ok(crate::RouteAwareClientPool::with_builder_and_initial_route(
http_client_factory.clone(),
route_class,
self,
route,
)?
.into_client());
}
self.chatgpt_cookie_store = http_client_factory.chatgpt_cookie_store();
let (builder, request_logging, default_headers) = self.into_reqwest_parts();
let inner =
crate::outbound_proxy::build_reqwest_client_for_route(builder, route_class, &route)?;
Ok(HttpClient::from_parts(
inner,
request_logging,
default_headers,
))
}
/// Builds a client for a route that was already resolved by a route-aware caller.
pub(crate) fn build_for_resolved_route(
mut self,
http_client_factory: &HttpClientFactory,
route_class: ClientRouteClass,
route: &OutboundProxyRoute,
) -> Result<TransportClient, BuildRouteAwareHttpClientError> {
self.chatgpt_cookie_store = http_client_factory.chatgpt_cookie_store();
let explicit_roots = self.tls.root_certificate.is_some();
let (builder, request_logging, default_headers) = self.into_reqwest_parts();
let inner = if explicit_roots {
crate::outbound_proxy::configure_builder_for_resolved_route(
builder,
route_class,
route,
)?
.build()
.map_err(BuildRouteAwareHttpClientError::ExplicitTls)?
} else {
crate::outbound_proxy::build_reqwest_client_for_route(builder, route_class, route)?
};
Ok(TransportClient::new(
inner,
request_logging,
default_headers,
))
}
#[cfg(windows)]
pub(crate) fn with_windows_proxy_pipe(
mut self,
pipe: &crate::windows_proxy_auth::ProxyPipe,
) -> Self {
self.windows_proxy_pipe_path = Some(pipe.path().to_owned());
self
}
/// Builds a client using the transport's default proxy behavior.
///
/// # Legacy compatibility only
///
/// This bypasses [`HttpClientFactory`] and therefore does not honor its configured outbound
/// proxy policy. New product traffic must use [`Self::build_respecting_outbound_proxy_policy`]
/// or [`HttpClientFactory::build_client`].
#[deprecated(
note = "legacy compatibility only; use HttpClientFactory::build_client or build_respecting_outbound_proxy_policy"
)]
pub fn build_with_transport_default_proxy(
self,
) -> Result<HttpClient, BuildCustomCaTransportError> {
self.build_with_proxy_routing(ProxyRouting::TransportDefault)
}
/// Builds a client that connects directly without using a proxy.
///
/// # Exceptional use only
///
/// This bypasses [`HttpClientFactory`] and is appropriate only when bypassing proxy discovery
/// is itself required: for example, a hermetic local test fixture, a localhost callback, or
/// sandbox traffic whose egress routing is handled separately. Ordinary outbound product
/// traffic must use [`Self::build_respecting_outbound_proxy_policy`] or
/// [`HttpClientFactory::build_client`].
pub fn build_direct(self) -> Result<HttpClient, BuildCustomCaTransportError> {
self.build_with_proxy_routing(ProxyRouting::Direct)
}
/// Builds a transport-default client while preserving the legacy custom-CA fallback.
///
/// # Legacy compatibility only
///
/// This preserves call sites that historically logged a custom-CA error and continued with
/// system roots. New product traffic must propagate construction errors through
/// [`Self::build_respecting_outbound_proxy_policy`] or [`HttpClientFactory::build_client`].
#[deprecated(
note = "legacy custom-CA fallback only; use HttpClientFactory::build_client or build_respecting_outbound_proxy_policy"
)]
pub fn build_with_transport_default_proxy_and_custom_ca_fallback(self) -> HttpClient {
HttpClient {
backend: HttpClientBackend::Direct(
self.build_with_custom_ca_fallback(ProxyRouting::TransportDefault),
),
}
}
/// Builds a direct client while preserving the legacy custom-CA fallback.
///
/// # Legacy compatibility only
///
/// This combines the exceptional proxy bypass described by [`Self::build_direct`] with the
/// historical behavior of logging a custom-CA error and continuing with system roots.
#[deprecated(
note = "legacy custom-CA fallback only; use build_direct and propagate construction errors"
)]
pub fn build_direct_with_custom_ca_fallback(self) -> HttpClient {
HttpClient {
backend: HttpClientBackend::Direct(
self.build_with_custom_ca_fallback(ProxyRouting::Direct),
),
}
}
fn build_with_proxy_routing(
mut self,
proxy_routing: ProxyRouting,
) -> Result<HttpClient, BuildCustomCaTransportError> {
let request_logging = self.request_logging;
let default_headers = self.default_headers.take().unwrap_or_default();
build_reqwest_client_with_custom_ca(self.reqwest_builder(proxy_routing))
.map(|inner| HttpClient::from_parts(inner, request_logging, default_headers))
}
pub(crate) fn build_with_custom_ca_fallback(
self,
proxy_routing: ProxyRouting,
) -> TransportClient {
self.build_with_custom_ca_fallback_using(proxy_routing, build_reqwest_client_with_custom_ca)
}
fn build_with_custom_ca_fallback_using(
mut self,
proxy_routing: ProxyRouting,
build_with_custom_ca: impl FnOnce(
reqwest::ClientBuilder,
)
-> Result<reqwest::Client, BuildCustomCaTransportError>,
) -> TransportClient {
let request_logging = self.request_logging;
let default_headers = self.default_headers.take().unwrap_or_default();
let inner = match build_with_custom_ca(self.clone().reqwest_builder(proxy_routing)) {
Ok(inner) => inner,
Err(error) => {
tracing::event!(
target: "codex_otel.log_only",
tracing::Level::WARN,
event.name = "codex.http_client.custom_ca_fallback",
"HTTP client fell back to system root certificates"
);
tracing::warn!(error = %error, "failed to build HTTP client with custom CA");
self.reqwest_builder(proxy_routing)
.build()
.unwrap_or_else(|fallback_error| {
tracing::warn!(
error = %fallback_error,
"failed to build fallback HTTP client"
);
reqwest::Client::new()
})
}
};
TransportClient::new(inner, request_logging, default_headers)
}
fn into_reqwest_parts(mut self) -> (reqwest::ClientBuilder, RequestLogging, HeaderMap) {
let request_logging = self.request_logging;
let default_headers = self.default_headers.take().unwrap_or_default();
(
self.base_reqwest_builder(),
request_logging,
default_headers,
)
}
fn reqwest_builder(self, proxy_routing: ProxyRouting) -> reqwest::ClientBuilder {
let builder = self.base_reqwest_builder();
match proxy_routing {
ProxyRouting::TransportDefault => builder,
ProxyRouting::Direct => builder.no_proxy(),
}
}
fn base_reqwest_builder(self) -> reqwest::ClientBuilder {
let mut builder = reqwest::Client::builder();
#[cfg(windows)]
if let Some(path) = self.windows_proxy_pipe_path {
builder = builder.windows_named_pipe(path);
}
if self.disable_pool_idle_timeout {
builder = builder.pool_idle_timeout(None);
}
if self.http2_prior_knowledge {
builder = builder.http2_prior_knowledge();
}
if self.tls_backend == TlsBackend::Rustls || self.tls.client_identity.is_some() {
ensure_rustls_crypto_provider();
builder = builder.use_rustls_tls();
}
if let Some(certificate) = self.tls.root_certificate {
builder = builder
.tls_built_in_root_certs(false)
.add_root_certificate(certificate.reqwest);
}
if let Some(identity) = self.tls.client_identity {
builder = builder.identity(identity.reqwest).https_only(true);
}
if !self.follow_redirects {
builder = builder.redirect(reqwest::redirect::Policy::none());
} else if let Some(redirect_observed) = self.redirect_observed {
builder = builder.redirect(reqwest::redirect::Policy::custom(move |attempt| {
redirect_observed.store(/*val*/ true, Ordering::Relaxed);
reqwest::redirect::Policy::default().redirect(attempt)
}));
}
if let Some(connect_timeout) = self.connect_timeout {
builder = builder.connect_timeout(connect_timeout);
}
if self.chatgpt_cloudflare_cookie_store {
builder = match self.chatgpt_cookie_store {
Some(store) => builder.cookie_provider(store),
None => with_chatgpt_cloudflare_cookie_store(builder),
};
}
builder
}
}
impl Default for HttpClientBuilder {
fn default() -> Self {
Self {
http2_prior_knowledge: false,
disable_pool_idle_timeout: false,
default_headers: None,
follow_redirects: true,
redirect_observed: None,
connect_timeout: None,
chatgpt_cloudflare_cookie_store: false,
chatgpt_cookie_store: None,
request_logging: RequestLogging::Enabled,
tls_backend: TlsBackend::TransportDefault,
tls: HttpClientTlsConfig::default(),
#[cfg(windows)]
windows_proxy_pipe_path: None,
}
}
}
#[derive(Clone, Copy)]
pub(crate) enum ProxyRouting {
TransportDefault,
Direct,
}
#[cfg(test)]
#[path = "client_builder_tests.rs"]
mod tests;

View File

@@ -0,0 +1,116 @@
use super::*;
use http::HeaderValue;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
#[tokio::test]
async fn custom_ca_fallback_preserves_builder_configuration() {
let listener =
std::net::TcpListener::bind(("127.0.0.1", 0)).expect("HTTP listener should bind");
let address = listener
.local_addr()
.expect("HTTP listener should have an address");
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("HTTP listener should accept");
let mut request = Vec::new();
let mut chunk = [0_u8; 1024];
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
let bytes_read = stream.read(&mut chunk).expect("HTTP request should read");
assert!(bytes_read > 0, "HTTP request should include headers");
request.extend_from_slice(&chunk[..bytes_read]);
}
stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.expect("HTTP listener should write response");
String::from_utf8(request).expect("HTTP request should be UTF-8")
});
let mut headers = HeaderMap::new();
headers.insert("x-builder-test", HeaderValue::from_static("preserved"));
let client = HttpClientBuilder::new()
.default_headers(headers)
.build_with_custom_ca_fallback_using(ProxyRouting::Direct, |_| {
Err(BuildCustomCaTransportError::InvalidCaFile {
source_env: "TEST_CA_ENV",
path: PathBuf::from("invalid-test-ca.pem"),
detail: "synthetic invalid CA".to_string(),
})
});
let client = HttpClient {
backend: HttpClientBackend::Direct(client),
};
let response = client
.get(format!("http://{address}/fallback"))
.send()
.await
.expect("fallback client should send request");
assert!(response.status().is_success());
let request = server.join().expect("HTTP listener should finish");
assert!(
request
.lines()
.any(|line| line.eq_ignore_ascii_case("x-builder-test: preserved"))
);
}
/// A server cannot keep a connection reusable after the caller requests closure.
#[tokio::test]
async fn connection_close_prevents_reuse_when_server_ignores_it()
-> Result<(), Box<dyn std::error::Error>> {
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await?;
let url = format!("http://{}/", listener.local_addr()?);
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await?;
let mut headers = Vec::new();
while !headers.ends_with(b"\r\n\r\n") {
headers.push(stream.read_u8().await?);
}
// Deliberately ignore the request's Connection: close header.
let response = b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n";
stream.write_all(response).await?;
let mut byte = [0];
let reused = tokio::select! {
read = stream.read(&mut byte) => {
if read? == 0 {
stream = listener.accept().await?.0;
false
} else {
true
}
}
accepted = listener.accept() => {
stream = accepted?.0;
false
}
};
headers.clear();
if reused {
headers.push(byte[0]);
}
while !headers.ends_with(b"\r\n\r\n") {
headers.push(stream.read_u8().await?);
}
stream.write_all(response).await?;
Ok::<bool, std::io::Error>(reused)
});
let client = HttpClientBuilder::new().build_direct()?;
for _ in 0..2 {
client
.get(&url)
.header(http::header::CONNECTION, HeaderValue::from_static("close"))
.send()
.await?
.bytes()
.await?;
}
assert!(
!server.await??,
"the server reused a connection marked closed"
);
Ok(())
}

View File

@@ -0,0 +1,113 @@
//! Validated TLS material for strict, route-aware HTTP clients.
//! Explicit roots replace shared environment roots; PEM identities require HTTPS and rustls.
use std::fmt;
#[cfg(windows)]
use std::io;
#[cfg(windows)]
use std::sync::Arc;
#[cfg(windows)]
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
#[cfg(windows)]
use rustls::ClientConfig;
#[cfg(windows)]
use rustls::RootCertStore;
#[cfg(windows)]
use rustls_pki_types::CertificateDer;
#[cfg(windows)]
use rustls_pki_types::PrivateKeyDer;
#[cfg(windows)]
use rustls_pki_types::pem::PemObject;
use crate::HttpError;
#[cfg(windows)]
use crate::WindowsProxyTls;
/// TLS configuration consumed by [`crate::HttpClientBuilder::build_with_tls`].
/// Keeping this separate from the builder prevents combining it with legacy fallback APIs.
#[derive(Clone, Default)]
pub struct HttpClientTlsConfig {
pub(crate) root_certificate: Option<TlsMaterial<reqwest::Certificate>>,
pub(crate) client_identity: Option<TlsMaterial<reqwest::Identity>>,
}
#[derive(Clone)]
pub(crate) struct TlsMaterial<T> {
pub(crate) reqwest: T,
// Reqwest does not expose its TLS material to the Windows proxy connector.
#[cfg(windows)]
pem: Arc<[u8]>,
}
impl<T> TlsMaterial<T> {
fn from_pem(
pem: &[u8],
parse: impl FnOnce(&[u8]) -> Result<T, reqwest::Error>,
) -> Result<Self, HttpError> {
Ok(Self {
reqwest: parse(pem)?,
#[cfg(windows)]
pem: pem.into(),
})
}
}
impl fmt::Debug for HttpClientTlsConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpClientTlsConfig")
.field("explicit_root", &self.root_certificate.is_some())
.field("client_identity", &self.client_identity.is_some())
.finish()
}
}
impl HttpClientTlsConfig {
/// Trusts this PEM certificate instead of system or environment-provided roots.
pub fn with_root_certificate_pem(mut self, pem: &[u8]) -> Result<Self, HttpError> {
self.root_certificate = Some(TlsMaterial::from_pem(pem, reqwest::Certificate::from_pem)?);
Ok(self)
}
/// Installs a PEM certificate chain and private key and requires HTTPS requests.
pub fn with_client_identity_pem(mut self, pem: &[u8]) -> Result<Self, HttpError> {
self.client_identity = Some(TlsMaterial::from_pem(pem, reqwest::Identity::from_pem)?);
Ok(self)
}
#[cfg(windows)]
pub(crate) fn windows_proxy_tls(&self) -> io::Result<WindowsProxyTls> {
if self.root_certificate.is_none() && self.client_identity.is_none() {
return Ok(WindowsProxyTls::Default);
}
let roots = if let Some(root) = &self.root_certificate {
let mut roots = RootCertStore::empty();
for certificate in CertificateDer::pem_slice_iter(&root.pem) {
roots
.add(certificate.map_err(io::Error::other)?)
.map_err(io::Error::other)?;
}
roots
} else {
crate::custom_ca::build_rustls_root_store_with_custom_ca().map_err(io::Error::other)?
};
ensure_rustls_crypto_provider();
let builder = ClientConfig::builder().with_root_certificates(roots);
let config = if let Some(identity) = &self.client_identity {
let certificates = CertificateDer::pem_slice_iter(&identity.pem)
.collect::<Result<Vec<_>, _>>()
.map_err(io::Error::other)?;
let key = PrivateKeyDer::pem_slice_iter(&identity.pem)
.last()
.transpose()
.map_err(io::Error::other)?
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing private key"))?;
builder
.with_client_auth_cert(certificates, key)
.map_err(io::Error::other)?
} else {
builder.with_no_client_auth()
};
Ok(WindowsProxyTls::Custom(Arc::new(config)))
}
}

View File

@@ -0,0 +1,828 @@
//! Custom CA handling shared by Codex outbound HTTP and websocket clients.
//!
//! Codex constructs outbound reqwest clients and secure websocket connections in a few crates, but
//! they all need the same trust-store policy when enterprise proxies or gateways intercept TLS.
//! This module centralizes that policy so callers can start from an ordinary
//! `reqwest::ClientBuilder` or rustls client config, layer in custom CA support, and either get
//! back a configured transport or a user-facing error that explains how to fix a misconfigured CA
//! bundle.
//! Concurrent native-root reads may share one in-flight load; later builds reload trust, and
//! custom CA files are read independently for every build.
//!
//! The module intentionally has a narrow responsibility:
//!
//! - read CA material from `CODEX_CA_CERTIFICATE`, falling back to `SSL_CERT_FILE`
//! - normalize PEM variants that show up in real deployments, including OpenSSL-style
//! `TRUSTED CERTIFICATE` labels and bundles that also contain CRLs
//! - return user-facing errors that explain how to fix misconfigured CA files
//!
//! Its production contract is narrow: produce a transport configuration whose root store contains
//! every parseable certificate block from the configured PEM bundle, or fail early with a precise
//! error before the caller starts network traffic.
//!
//! In this module's test setup, a hermetic test is one whose result depends only on the CA file
//! and environment variables that the test chose for itself. That matters here because the normal
//! reqwest client-construction path is not hermetic enough for environment-sensitive tests:
//!
//! - on macOS seatbelt runs, `reqwest::Client::builder().build()` can panic inside
//! `system-configuration` while probing platform proxy settings, which means the process can die
//! before the custom-CA code reports success or a structured error. That matters in practice
//! because Codex itself commonly runs spawned test processes under seatbelt, so this is not just
//! a hypothetical CI edge case.
//! - child processes inherit CA-related environment variables by default, which lets developer
//! shell state or CI configuration affect a test unless the test scrubs those variables first
//!
//! The tests in this crate therefore stay split across two layers:
//!
//! - unit tests in this module cover env-selection logic without constructing a real client
//! - subprocess integration tests under `tests/` cover real client construction through
//! [`build_reqwest_client_for_subprocess_tests`], which disables reqwest proxy autodetection so
//! the tests can observe custom-CA success and failure directly, including one TLS handshake
//! through a local HTTPS server
//! - those subprocess tests also scrub inherited CA environment variables before launch so their
//! result depends only on the test fixtures and env vars set by the test itself
use std::env;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
use rustls::ClientConfig;
use rustls::RootCertStore;
use rustls_pki_types::CertificateDer;
use rustls_pki_types::pem::PemObject;
use rustls_pki_types::pem::SectionKind;
use rustls_pki_types::pem::{self};
use thiserror::Error;
use tracing::info;
use tracing::warn;
pub const CODEX_CA_CERT_ENV: &str = "CODEX_CA_CERTIFICATE";
pub const SSL_CERT_FILE_ENV: &str = "SSL_CERT_FILE";
const CA_CERT_HINT: &str = "If you set CODEX_CA_CERTIFICATE or SSL_CERT_FILE, ensure it points to a PEM file containing one or more CERTIFICATE blocks, or unset it to use system roots.";
type PemSection = (SectionKind, Vec<u8>);
/// Describes why a transport using shared custom CA support could not be constructed.
///
/// These failure modes apply to both reqwest client construction and websocket TLS
/// configuration. A build can fail because the configured CA file could not be read, could not be
/// parsed as certificates, contained certs that the target TLS stack refused to register, or
/// because the final reqwest client builder failed. Callers that do not care about the
/// distinction can rely on the `From<BuildCustomCaTransportError> for io::Error` conversion.
#[derive(Debug, Error)]
pub enum BuildCustomCaTransportError {
/// Reading the selected CA file from disk failed before any PEM parsing could happen.
#[error(
"Failed to read CA certificate file {} selected by {}: {source}. {hint}",
path.display(),
source_env,
hint = CA_CERT_HINT
)]
ReadCaFile {
source_env: &'static str,
path: PathBuf,
source: io::Error,
},
/// The selected CA file was readable, but did not produce usable certificate material.
#[error(
"Failed to load CA certificates from {} selected by {}: {detail}. {hint}",
path.display(),
source_env,
hint = CA_CERT_HINT
)]
InvalidCaFile {
source_env: &'static str,
path: PathBuf,
detail: String,
},
/// One parsed certificate block could not be registered with the reqwest client builder.
#[error(
"Failed to parse certificate #{certificate_index} from {} selected by {}: {source}. {hint}",
path.display(),
source_env,
hint = CA_CERT_HINT
)]
RegisterCertificate {
source_env: &'static str,
path: PathBuf,
certificate_index: usize,
source: reqwest::Error,
},
/// Reqwest rejected the final client configuration after a custom CA bundle was loaded.
#[error(
"Failed to build HTTP client while using CA bundle from {} ({}): {source}",
source_env,
path.display()
)]
BuildClientWithCustomCa {
source_env: &'static str,
path: PathBuf,
#[source]
source: reqwest::Error,
},
/// Reqwest rejected the final client configuration while using only system roots.
#[error("Failed to build HTTP client while using system root certificates: {0}")]
BuildClientWithSystemRoots(#[source] reqwest::Error),
/// One parsed certificate block could not be registered with the websocket TLS root store.
#[error(
"Failed to register certificate #{certificate_index} from {} selected by {} in rustls root store: {source}. {hint}",
path.display(),
source_env,
hint = CA_CERT_HINT
)]
RegisterRustlsCertificate {
source_env: &'static str,
path: PathBuf,
certificate_index: usize,
source: rustls::Error,
},
}
impl From<BuildCustomCaTransportError> for io::Error {
fn from(error: BuildCustomCaTransportError) -> Self {
match error {
BuildCustomCaTransportError::ReadCaFile { ref source, .. } => {
io::Error::new(source.kind(), error)
}
BuildCustomCaTransportError::InvalidCaFile { .. }
| BuildCustomCaTransportError::RegisterCertificate { .. }
| BuildCustomCaTransportError::RegisterRustlsCertificate { .. } => {
io::Error::new(io::ErrorKind::InvalidData, error)
}
BuildCustomCaTransportError::BuildClientWithCustomCa { .. }
| BuildCustomCaTransportError::BuildClientWithSystemRoots(_) => io::Error::other(error),
}
}
}
/// Builds a reqwest client that honors Codex custom CA environment variables.
///
/// Callers supply the baseline builder configuration they need, and this helper layers in custom
/// CA handling before finally constructing the client. `CODEX_CA_CERTIFICATE` takes precedence
/// over `SSL_CERT_FILE`, and empty values for either are treated as unset so callers do not
/// accidentally turn `VAR=""` into a bogus path lookup.
///
/// Callers that build a raw `reqwest::Client` directly bypass this policy entirely. That is an
/// easy mistake to make when adding a new outbound Codex HTTP path, and the resulting bug only
/// shows up in environments where a proxy or gateway requires a custom root CA.
///
/// # Errors
///
/// Returns a [`BuildCustomCaTransportError`] when the configured CA file is unreadable,
/// malformed, or contains a certificate block that `reqwest` cannot register as a root.
pub fn build_reqwest_client_with_custom_ca(
builder: reqwest::ClientBuilder,
) -> Result<reqwest::Client, BuildCustomCaTransportError> {
build_reqwest_client_with_env(&ProcessEnv, builder)
}
/// 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
/// `CODEX_CA_CERTIFICATE` or `SSL_CERT_FILE` selects a CA bundle, the returned config starts from
/// the platform native roots and then adds the configured custom CA certificates. When no custom
/// CA env var is set, this returns `Ok(None)` so websocket callers can keep using their ordinary
/// default connector path.
///
/// Callers that let tungstenite build its default TLS connector directly bypass this policy
/// entirely. That bug only shows up in environments where secure websocket traffic needs the same
/// enterprise root CA bundle as HTTPS traffic.
pub fn maybe_build_rustls_client_config_with_custom_ca()
-> Result<Option<Arc<ClientConfig>>, BuildCustomCaTransportError> {
maybe_build_rustls_client_config_with_env(&ProcessEnv)
}
/// Builds a rustls client config using native roots and any configured Codex custom CA bundle.
///
/// Unlike [`maybe_build_rustls_client_config_with_custom_ca`], this always returns a config. Use
/// this when the caller must perform TLS itself instead of delegating default configuration to a
/// transport library.
pub fn build_rustls_client_config_with_custom_ca()
-> Result<Arc<ClientConfig>, BuildCustomCaTransportError> {
build_rustls_client_config_with_env(&ProcessEnv)
}
/// Builds a reqwest client for spawned subprocess tests that exercise CA behavior.
///
/// This is the test-only client-construction path used by the subprocess coverage in `tests/`.
/// The module-level docs explain the hermeticity problem in full; this helper only addresses the
/// reqwest proxy-discovery panic side of that problem by disabling proxy autodetection. The tests
/// still scrub inherited CA environment variables themselves. Normal production callers should use
/// [`build_reqwest_client_with_custom_ca`] so test-only proxy behavior does not leak into
/// ordinary client construction.
pub fn build_reqwest_client_for_subprocess_tests(
builder: reqwest::ClientBuilder,
) -> Result<reqwest::Client, BuildCustomCaTransportError> {
build_reqwest_client_with_env(&ProcessEnv, builder.no_proxy())
}
fn maybe_build_rustls_client_config_with_env(
env_source: &dyn EnvSource,
) -> Result<Option<Arc<ClientConfig>>, BuildCustomCaTransportError> {
let Some(bundle) = env_source.configured_ca_bundle() else {
return Ok(None);
};
build_rustls_client_config(Some(&bundle)).map(Some)
}
fn build_rustls_client_config_with_env(
env_source: &dyn EnvSource,
) -> Result<Arc<ClientConfig>, BuildCustomCaTransportError> {
let bundle = env_source.configured_ca_bundle();
build_rustls_client_config(bundle.as_ref())
}
fn build_rustls_client_config(
bundle: Option<&ConfiguredCaBundle>,
) -> Result<Arc<ClientConfig>, BuildCustomCaTransportError> {
ensure_rustls_crypto_provider();
Ok(Arc::new(
ClientConfig::builder()
.with_root_certificates(build_rustls_root_store(bundle)?)
.with_no_client_auth(),
))
}
#[cfg(windows)]
pub(crate) fn build_rustls_root_store_with_custom_ca()
-> Result<RootCertStore, BuildCustomCaTransportError> {
build_rustls_root_store(ProcessEnv.configured_ca_bundle().as_ref())
}
fn build_rustls_root_store(
bundle: Option<&ConfiguredCaBundle>,
) -> Result<RootCertStore, BuildCustomCaTransportError> {
// Start from the platform roots so websocket callers keep the same baseline trust behavior
// they would get from tungstenite's default rustls connector, then layer in the Codex custom
// CA bundle on top when configured.
let mut root_store = (*crate::native_roots::load()).clone();
if let Some(bundle) = bundle {
let certificates = bundle.load_certificates()?;
for (idx, cert) in certificates.into_iter().enumerate() {
if let Err(source) = root_store.add(cert) {
warn!(
source_env = bundle.source_env,
ca_path = %bundle.path.display(),
certificate_index = idx + 1,
error = %source,
"failed to register CA certificate in rustls root store"
);
return Err(BuildCustomCaTransportError::RegisterRustlsCertificate {
source_env: bundle.source_env,
path: bundle.path.clone(),
certificate_index: idx + 1,
source,
});
}
}
}
Ok(root_store)
}
/// Builds a reqwest client using an injected environment source and reqwest builder.
///
/// This exists so tests can exercise precedence behavior deterministically without mutating the
/// real process environment. It selects the CA bundle, delegates file parsing to
/// [`ConfiguredCaBundle::load_certificates`], preserves the caller's chosen `reqwest` builder
/// configuration, forces rustls when a custom CA is configured, and finally registers each parsed
/// certificate with that builder.
fn build_reqwest_client_with_env(
env_source: &dyn EnvSource,
mut builder: reqwest::ClientBuilder,
) -> Result<reqwest::Client, BuildCustomCaTransportError> {
if let Some(bundle) = env_source.configured_ca_bundle() {
ensure_rustls_crypto_provider();
info!(
source_env = bundle.source_env,
ca_path = %bundle.path.display(),
"building HTTP client with rustls backend for custom CA bundle"
);
builder = builder.use_rustls_tls();
let certificates = bundle.load_certificates()?;
for (idx, cert) in certificates.iter().enumerate() {
let certificate = match reqwest::Certificate::from_der(cert.as_ref()) {
Ok(certificate) => certificate,
Err(source) => {
warn!(
source_env = bundle.source_env,
ca_path = %bundle.path.display(),
certificate_index = idx + 1,
error = %source,
"failed to register CA certificate"
);
return Err(BuildCustomCaTransportError::RegisterCertificate {
source_env: bundle.source_env,
path: bundle.path.clone(),
certificate_index: idx + 1,
source,
});
}
};
builder = builder.add_root_certificate(certificate);
}
return match builder.build() {
Ok(client) => Ok(client),
Err(source) => {
warn!(
source_env = bundle.source_env,
ca_path = %bundle.path.display(),
error = %source,
"failed to build client after loading custom CA bundle"
);
Err(BuildCustomCaTransportError::BuildClientWithCustomCa {
source_env: bundle.source_env,
path: bundle.path.clone(),
source,
})
}
};
}
info!(
codex_ca_certificate_configured = false,
ssl_cert_file_configured = false,
"using system root certificates because no CA override environment variable was selected"
);
match builder.build() {
Ok(client) => Ok(client),
Err(source) => {
warn!(
error = %source,
"failed to build client while using system root certificates"
);
Err(BuildCustomCaTransportError::BuildClientWithSystemRoots(
source,
))
}
}
}
/// Abstracts environment access so tests can cover precedence rules without mutating process-wide
/// variables.
trait EnvSource {
/// Returns the environment variable value for `key`, if this source considers it set.
///
/// Implementations should return `None` for absent values and may also collapse unreadable
/// process-environment states into `None`, because the custom CA logic treats both cases as
/// "no override configured". Callers build precedence and empty-string handling on top of this
/// method, so implementations should not trim or normalize the returned string.
fn var(&self, key: &str) -> Option<String>;
/// Returns a non-empty environment variable value interpreted as a filesystem path.
///
/// Empty strings are treated as unset because presence here acts as a boolean "custom CA
/// override requested" signal. This keeps the precedence logic from treating `VAR=""` as an
/// attempt to open the current working directory or some other platform-specific oddity once
/// it is converted into a path.
fn non_empty_path(&self, key: &str) -> Option<PathBuf> {
self.var(key)
.filter(|value| !value.is_empty())
.map(PathBuf::from)
}
/// Returns the configured CA bundle and which environment variable selected it.
///
/// `CODEX_CA_CERTIFICATE` wins over `SSL_CERT_FILE` because it is the Codex-specific override.
/// Keeping the winning variable name with the path lets later logging explain not only which
/// file was used but also why that file was chosen.
fn configured_ca_bundle(&self) -> Option<ConfiguredCaBundle> {
self.non_empty_path(CODEX_CA_CERT_ENV)
.map(|path| ConfiguredCaBundle {
source_env: CODEX_CA_CERT_ENV,
path,
})
.or_else(|| {
self.non_empty_path(SSL_CERT_FILE_ENV)
.map(|path| ConfiguredCaBundle {
source_env: SSL_CERT_FILE_ENV,
path,
})
})
}
}
/// Reads CA configuration from the real process environment.
///
/// This is the production `EnvSource` implementation used by
/// [`build_reqwest_client_with_custom_ca`]. Tests substitute in-memory env maps so they can
/// exercise precedence and empty-value behavior without mutating process-global variables.
struct ProcessEnv;
impl EnvSource for ProcessEnv {
fn var(&self, key: &str) -> Option<String> {
env::var(key).ok()
}
}
/// Identifies the CA bundle selected for a client and the policy decision that selected it.
///
/// This is the concrete output of the environment-precedence logic. Callers use `source_env` for
/// logging and diagnostics, while `path` is the bundle that will actually be loaded.
struct ConfiguredCaBundle {
/// The environment variable that won the precedence check for this bundle.
source_env: &'static str,
/// The filesystem path that should be read as PEM certificate input.
path: PathBuf,
}
impl ConfiguredCaBundle {
/// Loads certificates from this selected CA bundle.
///
/// The bundle already represents the output of environment-precedence selection, so this is
/// the natural point where the file-loading phase begins. The method owns the high-level
/// success/failure logs for that phase and keeps the source env and path together for lower-
/// level parsing and error shaping.
fn load_certificates(
&self,
) -> Result<Vec<CertificateDer<'static>>, BuildCustomCaTransportError> {
match self.parse_certificates() {
Ok(certificates) => {
info!(
source_env = self.source_env,
ca_path = %self.path.display(),
certificate_count = certificates.len(),
"loaded certificates from custom CA bundle"
);
Ok(certificates)
}
Err(error) => {
warn!(
source_env = self.source_env,
ca_path = %self.path.display(),
error = %error,
"failed to load custom CA bundle"
);
Err(error)
}
}
}
/// Loads every certificate block from a PEM file intended for Codex CA overrides.
///
/// This accepts a few common real-world variants so Codex behaves like other CA-aware tooling:
/// leading comments are preserved, `TRUSTED CERTIFICATE` labels are normalized to standard
/// certificate labels, and embedded CRLs are ignored when they are well-formed enough for the
/// section iterator to classify them.
fn parse_certificates(
&self,
) -> Result<Vec<CertificateDer<'static>>, BuildCustomCaTransportError> {
let pem_data = self.read_pem_data()?;
let normalized_pem = NormalizedPem::from_pem_data(self.source_env, &self.path, &pem_data);
let mut certificates = Vec::new();
let mut logged_crl_presence = false;
for section_result in normalized_pem.sections() {
// Known limitation: if `rustls-pki-types` fails while parsing a malformed CRL section,
// that error is reported here before we can classify the block as ignorable. A bundle
// containing valid certificates plus a malformed `X509 CRL` therefore still fails to
// load today, even though well-formed CRLs are ignored.
let (section_kind, der) = match section_result {
Ok(section) => section,
Err(error) => return Err(self.pem_parse_error(&error)),
};
match section_kind {
SectionKind::Certificate => {
// Standard CERTIFICATE blocks already decode to the exact DER bytes reqwest
// wants. Only OpenSSL TRUSTED CERTIFICATE blocks need trimming to drop any
// trailing X509_AUX trust metadata before registration.
let cert_der = normalized_pem.certificate_der(&der).ok_or_else(|| {
self.invalid_ca_file(
"failed to extract certificate data from TRUSTED CERTIFICATE: invalid DER length",
)
})?;
certificates.push(CertificateDer::from(cert_der.to_vec()));
}
SectionKind::Crl if !logged_crl_presence => {
info!(
source_env = self.source_env,
ca_path = %self.path.display(),
"ignoring X509 CRL entries found in custom CA bundle"
);
logged_crl_presence = true;
}
_ => {}
}
}
if certificates.is_empty() {
return Err(self.pem_parse_error(&pem::Error::NoItemsFound));
}
Ok(certificates)
}
/// Reads the CA bundle bytes while preserving the original filesystem error kind.
///
/// The caller wants a user-facing error that includes the bundle path and remediation hint, but
/// higher-level surfaces still benefit from distinguishing "not found" from other I/O
/// failures. This helper keeps both pieces together.
fn read_pem_data(&self) -> Result<Vec<u8>, BuildCustomCaTransportError> {
fs::read(&self.path).map_err(|source| BuildCustomCaTransportError::ReadCaFile {
source_env: self.source_env,
path: self.path.clone(),
source,
})
}
/// Rewrites PEM parsing failures into user-facing configuration errors.
///
/// The underlying parser knows whether the file was empty, malformed, or contained unsupported
/// PEM content, but callers need a message that also points them back to the relevant
/// environment variables and the expected remediation.
fn pem_parse_error(&self, error: &pem::Error) -> BuildCustomCaTransportError {
let detail = match error {
pem::Error::NoItemsFound => "no certificates found in PEM file".to_string(),
_ => format!("failed to parse PEM file: {error}"),
};
self.invalid_ca_file(detail)
}
/// Creates an invalid-CA error tied to this file path.
///
/// Most parse-time failures in this module eventually collapse to "the configured CA bundle is
/// not usable", but the detailed reason still matters for operator debugging. Centralizing that
/// formatting keeps the path and hint text consistent across the different parser branches.
fn invalid_ca_file(&self, detail: impl std::fmt::Display) -> BuildCustomCaTransportError {
BuildCustomCaTransportError::InvalidCaFile {
source_env: self.source_env,
path: self.path.clone(),
detail: detail.to_string(),
}
}
}
/// The PEM text shape after OpenSSL compatibility normalization.
///
/// `Standard` means the input already used ordinary PEM certificate labels. `TrustedCertificate`
/// means the input used OpenSSL's `TRUSTED CERTIFICATE` labels, so callers must also be prepared
/// to trim trailing `X509_AUX` bytes from decoded certificate sections.
enum NormalizedPem {
/// PEM contents that already used ordinary `CERTIFICATE` labels.
Standard(String),
/// PEM contents rewritten from OpenSSL `TRUSTED CERTIFICATE` labels to `CERTIFICATE`.
TrustedCertificate(String),
}
impl NormalizedPem {
/// Normalizes PEM text from a CA bundle into the label shape this module expects.
///
/// Codex only needs certificate DER bytes to seed `reqwest`'s root store, but operators may
/// point it at CA files that came from OpenSSL tooling rather than from a minimal certificate
/// bundle. OpenSSL's `TRUSTED CERTIFICATE` form is one such variant: it is still certificate
/// material, but it uses a different PEM label and may carry auxiliary trust metadata that
/// this crate does not consume. This constructor rewrites only the PEM labels so the mixed-
/// section parser can keep treating the file as certificate input. The rustls ecosystem does
/// not currently accept `TRUSTED CERTIFICATE` as a standard certificate label upstream, so
/// this remains a local compatibility shim rather than behavior delegated to
/// `rustls-pki-types`.
///
/// See also:
/// - rustls/pemfile issue #52, closed as not planned, documenting that
/// `BEGIN TRUSTED CERTIFICATE` blocks are ignored upstream:
/// <https://github.com/rustls/pemfile/issues/52>
/// - OpenSSL `x509 -trustout`, which emits `TRUSTED CERTIFICATE` PEM blocks:
/// <https://docs.openssl.org/master/man1/openssl-x509/>
/// - OpenSSL PEM readers, which document that plain `PEM_read_bio_X509()` discards auxiliary
/// trust settings:
/// <https://docs.openssl.org/master/man3/PEM_read_bio_PrivateKey/>
/// - `openssl s_server`, a real OpenSSL-based server/test tool that operates in this
/// ecosystem:
/// <https://docs.openssl.org/master/man1/openssl-s_server/>
fn from_pem_data(source_env: &'static str, path: &Path, pem_data: &[u8]) -> Self {
let pem = String::from_utf8_lossy(pem_data);
if pem.contains("TRUSTED CERTIFICATE") {
info!(
source_env,
ca_path = %path.display(),
"normalizing OpenSSL TRUSTED CERTIFICATE labels in custom CA bundle"
);
Self::TrustedCertificate(
pem.replace("BEGIN TRUSTED CERTIFICATE", "BEGIN CERTIFICATE")
.replace("END TRUSTED CERTIFICATE", "END CERTIFICATE"),
)
} else {
Self::Standard(pem.into_owned())
}
}
/// Returns the normalized PEM contents regardless of the label shape that produced them.
fn contents(&self) -> &str {
match self {
Self::Standard(contents) | Self::TrustedCertificate(contents) => contents,
}
}
/// Iterates over every recognized PEM section in this normalized PEM text.
///
/// `rustls-pki-types` exposes mixed-section parsing through a `PemObject` implementation on the
/// `(SectionKind, Vec<u8>)` tuple. Keeping that type-directed API here lets callers iterate in
/// terms of normalized sections rather than trait plumbing.
fn sections(&self) -> impl Iterator<Item = Result<PemSection, pem::Error>> + '_ {
PemSection::pem_slice_iter(self.contents().as_bytes())
}
/// Returns the certificate DER bytes for one parsed PEM certificate section.
///
/// Standard PEM certificates already decode to the exact DER bytes `reqwest` wants. OpenSSL
/// `TRUSTED CERTIFICATE` sections may append `X509_AUX` bytes after the certificate, so those
/// sections need to be trimmed down to their first DER object before registration.
fn certificate_der<'a>(&self, der: &'a [u8]) -> Option<&'a [u8]> {
match self {
Self::Standard(_) => Some(der),
Self::TrustedCertificate(_) => first_der_item(der),
}
}
}
/// Returns the first DER-encoded ASN.1 object in `der`, ignoring any trailing OpenSSL metadata.
///
/// A PEM `CERTIFICATE` block usually decodes to exactly one DER blob: the certificate itself.
/// OpenSSL's `TRUSTED CERTIFICATE` variant is different. It starts with that same certificate
/// blob, but may append extra `X509_AUX` bytes after it to describe OpenSSL-specific trust
/// settings. `reqwest::Certificate::from_der` only understands the certificate object, not those
/// trailing OpenSSL extensions.
///
/// This helper therefore asks a narrower question than "is this a valid certificate?": where does
/// the first top-level DER object end? If that boundary can be found, the caller keeps only that
/// prefix and discards the trailing trust metadata. If it cannot be found, the input is treated as
/// malformed CA data.
fn first_der_item(der: &[u8]) -> Option<&[u8]> {
der_item_length(der).map(|length| &der[..length])
}
/// Returns the byte length of the first DER item in `der`.
///
/// DER is a binary encoding for ASN.1 objects. Each object begins with:
///
/// - a tag byte describing what kind of object follows
/// - one or more length bytes describing how many content bytes belong to that object
/// - the content bytes themselves
///
/// For this module, the important fact is that a certificate is stored as one complete top-level
/// DER object. Once we know that object's declared length, we know exactly where the certificate
/// ends and where any trailing OpenSSL `X509_AUX` data begins.
///
/// This helper intentionally parses only that outer length field. It does not validate the inner
/// certificate structure, the meaning of the tag, or every nested ASN.1 value. That narrower scope
/// is deliberate: the caller only needs a safe slice boundary for the leading certificate object
/// before handing those bytes to `reqwest`, which performs the real certificate parsing.
///
/// The implementation supports the DER length forms needed here:
///
/// - short form, where the length is stored directly in the second byte
/// - long form, where the second byte says how many following bytes make up the length value
///
/// Indefinite lengths are rejected because DER does not permit them, and any declared length that
/// would run past the end of the input is treated as malformed.
fn der_item_length(der: &[u8]) -> Option<usize> {
let &length_octet = der.get(1)?;
if length_octet & 0x80 == 0 {
return Some(2 + usize::from(length_octet)).filter(|length| *length <= der.len());
}
let length_octets = usize::from(length_octet & 0x7f);
if length_octets == 0 {
return None;
}
let length_start = 2usize;
let length_end = length_start.checked_add(length_octets)?;
let length_bytes = der.get(length_start..length_end)?;
let mut content_length = 0usize;
for &byte in length_bytes {
content_length = content_length
.checked_mul(256)?
.checked_add(usize::from(byte))?;
}
length_end
.checked_add(content_length)
.filter(|length| *length <= der.len())
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::BuildCustomCaTransportError;
use super::CODEX_CA_CERT_ENV;
use super::EnvSource;
use super::SSL_CERT_FILE_ENV;
use super::maybe_build_rustls_client_config_with_env;
const TEST_CERT: &str = include_str!("../tests/fixtures/test-ca.pem");
struct MapEnv {
values: HashMap<String, String>,
}
impl EnvSource for MapEnv {
fn var(&self, key: &str) -> Option<String> {
self.values.get(key).cloned()
}
}
fn map_env(pairs: &[(&str, &str)]) -> MapEnv {
MapEnv {
values: pairs
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect(),
}
}
fn write_cert_file(temp_dir: &TempDir, name: &str, contents: &str) -> PathBuf {
let path = temp_dir.path().join(name);
fs::write(&path, contents).unwrap_or_else(|error| {
panic!("write cert fixture failed for {}: {error}", path.display())
});
path
}
#[test]
fn ca_path_prefers_codex_env() {
let env = map_env(&[
(CODEX_CA_CERT_ENV, "/tmp/codex.pem"),
(SSL_CERT_FILE_ENV, "/tmp/fallback.pem"),
]);
assert_eq!(
env.configured_ca_bundle().map(|bundle| bundle.path),
Some(PathBuf::from("/tmp/codex.pem"))
);
}
#[test]
fn ca_path_falls_back_to_ssl_cert_file() {
let env = map_env(&[(SSL_CERT_FILE_ENV, "/tmp/fallback.pem")]);
assert_eq!(
env.configured_ca_bundle().map(|bundle| bundle.path),
Some(PathBuf::from("/tmp/fallback.pem"))
);
}
#[test]
fn ca_path_ignores_empty_values() {
let env = map_env(&[
(CODEX_CA_CERT_ENV, ""),
(SSL_CERT_FILE_ENV, "/tmp/fallback.pem"),
]);
assert_eq!(
env.configured_ca_bundle().map(|bundle| bundle.path),
Some(PathBuf::from("/tmp/fallback.pem"))
);
}
#[test]
fn rustls_config_uses_custom_ca_bundle_when_configured() {
let temp_dir = TempDir::new().expect("tempdir");
let cert_path = write_cert_file(&temp_dir, "ca.pem", TEST_CERT);
let env = map_env(&[(CODEX_CA_CERT_ENV, cert_path.to_string_lossy().as_ref())]);
let config = maybe_build_rustls_client_config_with_env(&env)
.expect("rustls config")
.expect("custom CA config should be present");
assert!(config.enable_sni);
}
#[test]
fn rustls_config_reports_invalid_ca_file() {
let temp_dir = TempDir::new().expect("tempdir");
let cert_path = write_cert_file(&temp_dir, "empty.pem", "");
let env = map_env(&[(CODEX_CA_CERT_ENV, cert_path.to_string_lossy().as_ref())]);
let error = maybe_build_rustls_client_config_with_env(&env).expect_err("invalid CA");
assert!(matches!(
error,
BuildCustomCaTransportError::InvalidCaFile { .. }
));
}
}
#[cfg(test)]
#[path = "custom_ca_tls_tests.rs"]
mod tls_tests;

View File

@@ -0,0 +1,100 @@
//! Handshake and fresh-file-read coverage for shared custom trust configuration.
use super::CODEX_CA_CERT_ENV;
use super::ConfiguredCaBundle;
use super::build_rustls_client_config;
use pretty_assertions::assert_eq;
use rcgen::BasicConstraints;
use rcgen::CertificateParams;
use rcgen::CertifiedIssuer;
use rcgen::IsCa;
use rcgen::KeyPair;
use std::sync::Arc;
#[test]
fn custom_intermediate_trust_preserves_hostname_validation() {
let mut params = CertificateParams::default();
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
let root = CertifiedIssuer::self_signed(params.clone(), KeyPair::generate().unwrap()).unwrap();
let intermediate =
CertifiedIssuer::signed_by(params, KeyPair::generate().unwrap(), &root).unwrap();
let leaf_key = KeyPair::generate().unwrap();
let leaf = CertificateParams::new(vec!["localhost".to_string()])
.unwrap()
.signed_by(&leaf_key, &intermediate)
.unwrap();
let temp = tempfile::TempDir::new().unwrap();
let path = temp.path().join("intermediate.pem");
std::fs::write(&path, intermediate.pem()).unwrap();
let bundle = ConfiguredCaBundle {
source_env: CODEX_CA_CERT_ENV,
path,
};
let config = build_rustls_client_config(Some(&bundle)).unwrap();
let server = Arc::new(
rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(vec![leaf.der().clone()], leaf_key.into())
.unwrap(),
);
assert_eq!(
handshake(config.clone(), server.clone(), "localhost"),
Ok(())
);
let error = handshake(config.clone(), server.clone(), "wrong.example").unwrap_err();
assert!(
matches!(
error,
rustls::Error::InvalidCertificate(
rustls::CertificateError::NotValidForName
| rustls::CertificateError::NotValidForNameContext { .. }
)
),
"{error:?}"
);
std::fs::write(&bundle.path, include_str!("../tests/fixtures/test-ca.pem")).unwrap();
let replaced = build_rustls_client_config(Some(&bundle)).unwrap();
assert!(matches!(
handshake(replaced, server.clone(), "localhost"),
Err(rustls::Error::InvalidCertificate(
rustls::CertificateError::UnknownIssuer
))
));
assert_eq!(handshake(config, server, "localhost"), Ok(()));
std::fs::write(&bundle.path, "").unwrap();
assert!(matches!(
build_rustls_client_config(Some(&bundle)),
Err(super::BuildCustomCaTransportError::InvalidCaFile { .. })
));
std::fs::remove_file(&bundle.path).unwrap();
assert!(matches!(
build_rustls_client_config(Some(&bundle)),
Err(super::BuildCustomCaTransportError::ReadCaFile { .. })
));
}
fn handshake(
config: Arc<rustls::ClientConfig>,
server: Arc<rustls::ServerConfig>,
hostname: &'static str,
) -> Result<(), rustls::Error> {
let mut client = rustls::ClientConnection::new(config, hostname.try_into().unwrap()).unwrap();
let mut server = rustls::ServerConnection::new(server).unwrap();
for _ in 0..10 {
let mut bytes = Vec::new();
client.write_tls(&mut bytes).unwrap();
server.read_tls(&mut bytes.as_slice()).unwrap();
server.process_new_packets()?;
bytes.clear();
server.write_tls(&mut bytes).unwrap();
client.read_tls(&mut bytes.as_slice()).unwrap();
client.process_new_packets()?;
if !client.is_handshaking() {
return Ok(());
}
}
panic!("handshake did not complete");
}

View File

@@ -0,0 +1,57 @@
//! Errors returned by the shared Codex HTTP transport.
use crate::client::HttpError;
use crate::retry_after::RetryAfter;
use http::HeaderMap;
use http::StatusCode;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum TransportError {
#[error(transparent)]
Policy(#[from] crate::NetworkPolicyDenied),
#[error("http {status}: {body:?}")]
Http {
status: StatusCode,
url: Option<String>,
headers: Option<HeaderMap>,
body: Option<String>,
retry_after: Option<RetryAfter>,
},
#[error("retry limit reached")]
RetryLimit,
#[error("timeout")]
Timeout,
#[error("connection failed: {0}")]
Connection(#[source] HttpError),
#[error("network error: {0}")]
Network(String),
#[error("request build error: {0}")]
Build(String),
#[error("response body exceeds the {max_bytes} byte limit")]
ResponseTooLarge { max_bytes: usize },
}
impl TransportError {
/// Returns retry advice captured when this error response arrived.
pub fn retry_after(&self) -> Option<RetryAfter> {
match self {
Self::Http { retry_after, .. } => *retry_after,
Self::Policy(_)
| Self::RetryLimit
| Self::Timeout
| Self::Connection(_)
| Self::Network(_)
| Self::Build(_)
| Self::ResponseTooLarge { .. } => None,
}
}
}
#[derive(Debug, Error)]
pub enum StreamError {
#[error("stream failed: {0}")]
Stream(String),
#[error("timeout")]
Timeout,
}

View File

@@ -0,0 +1,130 @@
use url::Host;
use url::Url;
mod chatgpt_cloudflare_cookies;
mod chatgpt_hosts;
mod chatgpt_routing_affinity;
mod client;
mod client_builder;
mod client_tls;
mod custom_ca;
mod error;
mod native_roots;
mod network_policy;
mod openai_endpoints;
mod openai_headers;
mod outbound_proxy;
mod request;
mod request_builder;
mod request_draft;
mod response;
mod retry_after;
mod route_aware_client_pool;
mod route_aware_redirect;
mod tls_backend_fallback;
mod transport;
pub use crate::chatgpt_cloudflare_cookies::with_chatgpt_cloudflare_cookie_store;
pub use crate::chatgpt_hosts::is_allowed_chatgpt_host;
pub use crate::chatgpt_routing_affinity::ChatGptRoutingAffinity;
pub use crate::client::HttpClient;
pub use crate::client::HttpError;
pub use crate::client_builder::HttpClientBuilder;
pub use crate::client_tls::HttpClientTlsConfig;
pub use crate::custom_ca::BuildCustomCaTransportError;
/// Test-only subprocess hook for custom CA coverage.
///
/// This stays public only so the `custom_ca_probe` binary target can reuse the shared helper. It
/// is hidden from normal docs because ordinary callers should use
/// [`build_reqwest_client_with_custom_ca`] instead.
#[doc(hidden)]
pub use crate::custom_ca::build_reqwest_client_for_subprocess_tests;
pub use crate::custom_ca::build_reqwest_client_with_custom_ca;
pub use crate::custom_ca::build_rustls_client_config_with_custom_ca;
pub use crate::custom_ca::maybe_build_rustls_client_config_with_custom_ca;
pub use crate::error::StreamError;
pub use crate::error::TransportError;
pub use crate::network_policy::DestinationPolicy;
pub use crate::network_policy::NetworkPermit;
pub use crate::network_policy::NetworkPolicy;
pub use crate::network_policy::NetworkPolicyController;
pub use crate::network_policy::NetworkPolicyDenied;
pub use crate::network_policy::NetworkPolicyRevision;
pub use crate::openai_endpoints::OpenAiDestination;
pub use crate::openai_endpoints::classify_openai_api_url;
pub use crate::openai_endpoints::is_openai_api_url;
pub use crate::openai_headers::CHATGPT_ACCOUNT_ID_HEADER;
pub use crate::openai_headers::OPENAI_ORGANIZATION_HEADER;
pub use crate::openai_headers::OPENAI_PROJECT_HEADER;
pub use crate::outbound_proxy::BuildRouteAwareHttpClientError;
pub use crate::outbound_proxy::ClientRouteClass;
pub use crate::outbound_proxy::HttpClientFactory;
#[cfg(target_os = "macos")]
pub use crate::outbound_proxy::MacosSystemProxyConfiguration;
pub use crate::outbound_proxy::OutboundProxyPolicy;
pub use crate::outbound_proxy::OutboundProxyRoute;
pub use crate::outbound_proxy::RouteFailureClass;
#[doc(hidden)]
pub use crate::outbound_proxy::cache_system_proxy_route_for_test;
#[cfg(target_os = "macos")]
pub use crate::outbound_proxy::macos_system_proxy_configuration;
pub use crate::request::EncodedJsonBody;
pub use crate::request::PreparedRequestBody;
pub use crate::request::Request;
pub use crate::request::RequestBody;
pub use crate::request::RequestCompression;
pub use crate::request::Response;
pub use crate::request_builder::RequestBuilder;
pub use crate::response::HttpResponse;
pub use crate::retry_after::RetryAfter;
pub use crate::route_aware_client_pool::RouteAwareClientPool;
pub use crate::route_aware_client_pool::RouteAwareClientPoolError;
pub use crate::route_aware_client_pool::RouteAwareRequestError;
pub use crate::transport::ByteStream;
pub use crate::transport::HttpTransport;
pub use crate::transport::ReqwestTransport;
pub use crate::transport::StreamResponse;
pub use crate::transport::bounded_response_bytes;
#[cfg(windows)]
mod windows_proxy_auth;
#[cfg(windows)]
mod windows_tls;
#[cfg(windows)]
pub use crate::windows_proxy_auth::WindowsProxyTls;
#[cfg(windows)]
pub use crate::windows_proxy_auth::connect_windows_proxy;
#[cfg(windows)]
pub use crate::windows_tls::build_windows_platform_tls_config;
/// Validates HTTPS or loopback HTTP endpoints, rejecting userinfo and fragments.
/// Errors identify the caller-supplied field without including the URL.
pub fn validate_endpoint_url(value: &str, field: &str) -> Result<Url, String> {
let url = Url::parse(value).map_err(|_| format!("invalid {field} URL"))?;
let loopback = match url.host() {
Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
Some(Host::Ipv4(host)) => host.is_loopback(),
Some(Host::Ipv6(host)) => host.is_loopback(),
None => false,
};
if url.host().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.fragment().is_some()
|| !(url.scheme() == "https" || (url.scheme() == "http" && loopback))
{
return Err(format!(
"{field} must use HTTPS (or loopback HTTP), without userinfo or a fragment"
));
}
Ok(url)
}
/// Validates a credential-bearing HTTPS endpoint without including the URL in errors.
pub fn validate_https_endpoint_url(value: &str, field: &str) -> Result<Url, String> {
validate_endpoint_url(value, field)
.ok()
.filter(|url| url.scheme() == "https")
.ok_or_else(|| format!("{field} URLs must use HTTPS without userinfo or fragments"))
}

View File

@@ -0,0 +1,68 @@
//! Coalesces overlapping platform-root reads without retaining completed trust snapshots.
//! Later callers always reload. File/directory overrides bypass coalescing so their contents
//! are reread independently; custom Codex CA bundles are handled by the caller.
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::Weak;
use rustls::RootCertStore;
#[derive(Default)]
struct NativeRootsLoader {
in_flight: Mutex<Weak<OnceLock<Arc<RootCertStore>>>>,
}
impl NativeRootsLoader {
fn load(&self, load: impl FnOnce() -> RootCertStore) -> Arc<RootCertStore> {
let pending = {
let mut in_flight = self
.in_flight
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match in_flight
.upgrade()
.filter(|pending| pending.get().is_none())
{
Some(pending) => pending,
None => {
let pending = Arc::new(OnceLock::new());
*in_flight = Arc::downgrade(&pending);
pending
}
}
};
Arc::clone(pending.get_or_init(|| Arc::new(load())))
}
}
pub(crate) fn load() -> Arc<RootCertStore> {
// rustls-native-certs treats these as overrides of the platform store.
// Preserve fresh file reads even when several callers construct clients together.
if std::env::var_os("SSL_CERT_FILE").is_some() || std::env::var_os("SSL_CERT_DIR").is_some() {
return Arc::new(load_roots());
}
static LOADER: NativeRootsLoader = NativeRootsLoader {
in_flight: Mutex::new(Weak::new()),
};
LOADER.load(load_roots)
}
fn load_roots() -> RootCertStore {
let rustls_native_certs::CertificateResult { certs, errors, .. } =
rustls_native_certs::load_native_certs();
if !errors.is_empty() {
tracing::warn!(
native_root_error_count = errors.len(),
"encountered errors while loading native root certificates"
);
}
let mut roots = RootCertStore::empty();
let _ = roots.add_parsable_certificates(certs);
roots
}
#[cfg(test)]
#[path = "native_roots_tests.rs"]
mod tests;

View File

@@ -0,0 +1,55 @@
//! Verifies overlapping root loads, fresh trust generations, and panic recovery.
use super::*;
use pretty_assertions::assert_eq;
use rustls_pki_types::CertificateDer;
use rustls_pki_types::pem::PemObject;
use std::sync::mpsc;
use std::thread;
#[test]
fn concurrent_loads_share_roots_but_completed_loads_are_never_reused() {
let loader = NativeRootsLoader::default();
let (entered, started) = mpsc::channel();
let (release, released) = mpsc::channel();
thread::scope(|scope| {
let first_loader = &loader;
let first = scope.spawn(move || {
first_loader.load(|| {
entered.send(()).unwrap();
released.recv().unwrap();
RootCertStore::empty()
})
});
started.recv().unwrap();
let pending = loader.in_flight.lock().unwrap().upgrade().unwrap();
let second = scope.spawn(|| loader.load(|| panic!("overlapping load must be shared")));
// Wait for the second caller to own this generation before allowing it to finish.
while Arc::strong_count(&pending) < 3 {
thread::yield_now();
}
drop(loader.in_flight.lock().unwrap());
release.send(()).unwrap();
let first = first.join().unwrap();
let second = second.join().unwrap();
assert!(Arc::ptr_eq(&first, &second));
// Keep the old generation alive: completion, not refcount expiry, must force a reload.
let updated = loader.load(|| {
let mut roots = RootCertStore::empty();
roots.add_parsable_certificates(
CertificateDer::pem_slice_iter(include_bytes!("../tests/fixtures/test-ca.pem"))
.map(Result::unwrap),
);
roots
});
assert_eq!((first.len(), second.len(), updated.len()), (0, 0, 1));
});
}
#[test]
fn panicking_load_does_not_poison_later_trust_reads() {
let loader = NativeRootsLoader::default();
assert!(std::panic::catch_unwind(|| loader.load(|| panic!("interrupted load"))).is_err());
assert!(loader.load(RootCertStore::empty).is_empty());
}

View File

@@ -0,0 +1,387 @@
//! Application destination checks and revocation of outstanding network operations.
//!
//! The configuration owner publishes an already-composed policy. Transports retain only its
//! read side and a permit for each request; invalidation cannot leave an old request authorized.
use std::collections::BTreeSet;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::Weak;
use reqwest::Url;
use tokio::sync::watch;
/// Effective application destinations, after the requirements owner has applied precedence.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DestinationPolicy {
Unrestricted,
/// Only HTTPS and WSS requests to these exact, normalized hosts are permitted.
Restricted {
allowed_hosts: BTreeSet<String>,
},
}
impl DestinationPolicy {
fn allows(&self, url: &Url) -> bool {
match self {
Self::Unrestricted => true,
Self::Restricted { allowed_hosts } => {
matches!(url.scheme(), "https" | "wss")
&& url.host_str().is_some_and(|host| {
allowed_hosts.contains(host.strip_suffix('.').unwrap_or(host))
})
}
}
}
}
/// A deterministic denial, distinct from retryable network failures.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum NetworkPolicyDenied {
#[error("application network policy is unavailable")]
Unavailable,
#[error("destination denied by application network policy")]
Destination,
#[error("application network permission was revoked")]
Revoked,
#[error("this SDK transport is disabled by application network restrictions")]
UnsupportedTransport,
}
/// Read access to application policy. Clones observe the same updates.
#[derive(Clone, Default)]
pub struct NetworkPolicy {
state: Option<Arc<Mutex<State>>>,
endpoints: Option<Arc<BTreeSet<Url>>>,
account: Option<u64>,
}
impl fmt::Debug for NetworkPolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NetworkPolicy")
.field("managed", &self.state.is_some())
.finish_non_exhaustive()
}
}
impl PartialEq for NetworkPolicy {
fn eq(&self, other: &Self) -> bool {
self.endpoints == other.endpoints
&& self.account == other.account
&& match (&self.state, &other.state) {
(Some(left), Some(right)) => Arc::ptr_eq(left, right),
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
}
}
}
impl Eq for NetworkPolicy {}
struct State {
policy: Option<DestinationPolicy>,
revision: u64,
account: u64,
permits: Vec<Weak<Permit>>,
changes: watch::Sender<()>,
}
struct Permit {
destination: PermitDestination,
revoked: watch::Sender<bool>,
}
enum PermitDestination {
Url(Url),
UnrestrictedSdk,
}
impl PermitDestination {
fn allowed_by(&self, policy: &DestinationPolicy) -> bool {
match self {
Self::Url(url) => policy.allows(url),
Self::UnrestrictedSdk => matches!(policy, DestinationPolicy::Unrestricted),
}
}
}
/// Publication access retained by the account/configuration owner.
#[derive(Clone)]
pub struct NetworkPolicyController {
state: Arc<Mutex<State>>,
}
/// Identifies the account/configuration generation that a load is allowed to publish into.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NetworkPolicyRevision(u64);
impl Default for NetworkPolicyController {
fn default() -> Self {
Self {
state: Arc::new(Mutex::new(State {
policy: None,
revision: 0,
account: 0,
permits: Vec::new(),
changes: watch::channel(()).0,
})),
}
}
}
fn lock_state(state: &Mutex<State>) -> MutexGuard<'_, State> {
state
.lock()
.unwrap_or_else(|_| panic!("application network policy lock poisoned"))
}
impl NetworkPolicyController {
pub fn policy(&self) -> NetworkPolicy {
NetworkPolicy {
state: Some(self.state.clone()),
endpoints: None,
account: None,
}
}
/// Fails a requirements load without changing the current account identity.
pub fn unavailable(&self, revision: NetworkPolicyRevision) {
let mut state = lock_state(&self.state);
if state.revision != revision.0 {
return;
}
if state.policy.take().is_some() {
state.changes.send_replace(());
}
for permit in state
.permits
.drain(..)
.filter_map(|permit| permit.upgrade())
{
permit.revoked.send_replace(/*value*/ true);
}
}
/// Publishes a successful load only if its account/configuration generation is still current.
pub fn publish(&self, revision: NetworkPolicyRevision, policy: DestinationPolicy) -> bool {
let mut state = lock_state(&self.state);
if state.revision != revision.0 {
return false;
}
state.permits.retain(|permit| {
let Some(permit) = permit.upgrade() else {
return false;
};
if !permit.destination.allowed_by(&policy) {
permit.revoked.send_replace(/*value*/ true);
}
true
});
if state.policy.as_ref() != Some(&policy) {
state.policy = Some(policy);
state.changes.send_replace(());
}
true
}
}
impl NetworkPolicy {
pub const fn unmanaged() -> Self {
Self {
state: None,
endpoints: None,
account: None,
}
}
/// Narrows a bootstrap client's existing local policy to exact endpoint URLs.
/// This cannot grant access to a destination denied by the underlying policy.
pub fn restrict_to_endpoints(mut self, endpoints: BTreeSet<Url>) -> Self {
self.endpoints = Some(Arc::new(match &self.endpoints {
Some(existing) => existing.intersection(&endpoints).cloned().collect(),
None => endpoints,
}));
self
}
/// Binds a content client to the current account so retained credentials cannot
/// be used after another workspace's policy has been installed.
pub fn for_current_account(mut self) -> Self {
self.account = self.state.as_ref().map(|state| lock_state(state).account);
self
}
/// Bind a caller's restrictions to a captured credential policy without widening either.
/// Different managed controllers or account bindings cannot authorize the same request.
pub fn with_account_binding(mut self, credentials: &Self) -> Option<Self> {
if let Some(state) = &credentials.state {
if let Some(caller) = &self.state {
if !Arc::ptr_eq(caller, state) {
return None;
}
} else {
self.state = Some(Arc::clone(state));
}
}
if let (Some(caller), Some(credentials)) = (self.account, credentials.account)
&& caller != credentials
{
return None;
}
self.account = self.account.or(credentials.account);
if let Some(endpoints) = &credentials.endpoints {
self = self.restrict_to_endpoints(endpoints.as_ref().clone());
}
Some(self)
}
/// Whether this transport participates in the application policy lifecycle.
pub fn is_managed(&self) -> bool {
self.state.is_some()
}
/// Watches effective changes; unmanaged callers have no application policy owner.
pub fn changes(&self) -> Option<watch::Receiver<()>> {
self.state
.as_ref()
.map(|state| lock_state(state).changes.subscribe())
}
pub fn revision(&self) -> NetworkPolicyRevision {
NetworkPolicyRevision(
self.state
.as_ref()
.map_or(0, |state| lock_state(state).revision),
)
}
/// Revokes outstanding operations before an account change or a failed requirements load.
/// This read-side operation can only remove access; publication stays with the controller.
pub fn invalidate(&self) {
if let Some(state) = &self.state {
let mut state = lock_state(state);
state.revision += 1;
state.account += 1;
state.policy = None;
state.changes.send_replace(());
for permit in state
.permits
.drain(..)
.filter_map(|permit| permit.upgrade())
{
permit.revoked.send_replace(/*value*/ true);
}
}
}
/// Checks a destination before proxy resolution, DNS, or transport work starts.
pub fn acquire(&self, url: &Url) -> Result<NetworkPermit, NetworkPolicyDenied> {
if self
.endpoints
.as_ref()
.is_some_and(|endpoints| !endpoints.contains(url))
{
return Err(NetworkPolicyDenied::Destination);
}
self.acquire_destination(PermitDestination::Url(url.clone()))
}
/// Disables SDKs without destination enforcement whenever restrictions apply.
/// The returned permit also cancels work if an unrestricted policy changes.
pub fn acquire_for_unsupported_sdk(&self) -> Result<NetworkPermit, NetworkPolicyDenied> {
if self.endpoints.is_some() {
return Err(NetworkPolicyDenied::UnsupportedTransport);
}
self.acquire_destination(PermitDestination::UnrestrictedSdk)
}
fn acquire_destination(
&self,
destination: PermitDestination,
) -> Result<NetworkPermit, NetworkPolicyDenied> {
let Some(state) = &self.state else {
return Ok(NetworkPermit { inner: None });
};
let mut state = lock_state(state);
if self.account.is_some_and(|account| account != state.account) {
return Err(NetworkPolicyDenied::Revoked);
}
let policy = state
.policy
.as_ref()
.ok_or(NetworkPolicyDenied::Unavailable)?;
if !destination.allowed_by(policy) {
return Err(match destination {
PermitDestination::Url(_) => NetworkPolicyDenied::Destination,
PermitDestination::UnrestrictedSdk => NetworkPolicyDenied::UnsupportedTransport,
});
}
let (revoked, _) = watch::channel(/*init*/ false);
let permit = Arc::new(Permit {
destination,
revoked,
});
state.permits.retain(|permit| permit.strong_count() != 0);
state.permits.push(Arc::downgrade(&permit));
Ok(NetworkPermit {
inner: Some(permit),
})
}
}
/// Authorization retained for the entire operation, including response or WebSocket streaming.
#[derive(Clone)]
pub struct NetworkPermit {
inner: Option<Arc<Permit>>,
}
impl fmt::Debug for NetworkPermit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NetworkPermit").finish_non_exhaustive()
}
}
impl NetworkPermit {
pub fn check(&self) -> Result<(), NetworkPolicyDenied> {
if self
.inner
.as_ref()
.is_some_and(|permit| *permit.revoked.borrow())
{
Err(NetworkPolicyDenied::Revoked)
} else {
Ok(())
}
}
pub async fn revoked(&self) {
match &self.inner {
Some(permit) => {
let _ = permit
.revoked
.subscribe()
.wait_for(|revoked| *revoked)
.await;
}
None => std::future::pending().await,
}
}
pub async fn run<T>(
&self,
operation: impl Future<Output = T>,
) -> Result<T, NetworkPolicyDenied> {
tokio::select! {
biased;
_ = self.revoked() => Err(NetworkPolicyDenied::Revoked),
result = operation => Ok(result),
}
}
}
#[cfg(test)]
#[path = "network_policy_tests.rs"]
mod tests;

View File

@@ -0,0 +1,185 @@
//! Destination matching, bootstrap scope, and account revocation behavior.
use std::collections::BTreeSet;
use pretty_assertions::assert_eq;
use reqwest::Url;
use super::*;
#[test]
fn credential_binding_keeps_both_endpoint_restrictions_and_account_revocation() {
let controller = NetworkPolicyController::default();
let policy = controller.policy();
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
let a = Url::parse("https://example.com/a").unwrap();
let b = Url::parse("https://example.com/b").unwrap();
let c = Url::parse("https://example.com/c").unwrap();
let credentials = policy
.clone()
.for_current_account()
.restrict_to_endpoints(BTreeSet::from([b.clone(), c.clone()]));
let bound = policy
.clone()
.restrict_to_endpoints(BTreeSet::from([a.clone(), b.clone()]))
.with_account_binding(&credentials)
.unwrap();
assert!(matches!(
bound.acquire(&a),
Err(NetworkPolicyDenied::Destination)
));
assert!(matches!(
bound.acquire(&c),
Err(NetworkPolicyDenied::Destination)
));
let permit = bound.acquire(&b).unwrap();
policy.invalidate();
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
assert!(matches!(
bound.acquire(&b),
Err(NetworkPolicyDenied::Revoked)
));
assert_eq!(permit.check(), Err(NetworkPolicyDenied::Revoked));
}
#[test]
fn credential_binding_cannot_replace_a_callers_policy_or_revive_its_account() {
let controller = NetworkPolicyController::default();
let policy = controller.policy();
let allowed = Url::parse("https://example.com/allowed").unwrap();
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
let caller = policy
.clone()
.for_current_account()
.restrict_to_endpoints(BTreeSet::from([allowed.clone()]));
let bound = caller
.clone()
.with_account_binding(&NetworkPolicy::unmanaged())
.unwrap();
assert!(bound.acquire(&allowed).is_ok());
assert!(matches!(
bound.acquire(&Url::parse("https://example.com/other").unwrap()),
Err(NetworkPolicyDenied::Destination)
));
assert!(
caller
.clone()
.with_account_binding(&NetworkPolicyController::default().policy())
.is_none()
);
policy.invalidate();
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
assert!(
caller
.with_account_binding(&policy.for_current_account())
.is_none()
);
assert!(matches!(
bound.acquire(&allowed),
Err(NetworkPolicyDenied::Revoked)
));
}
#[test]
fn restricted_policy_matches_exact_secure_hosts() {
let controller = NetworkPolicyController::default();
let policy = controller.policy();
assert!(controller.publish(
policy.revision(),
DestinationPolicy::Restricted {
allowed_hosts: BTreeSet::from(["example.com".to_string()]),
}
));
for (url, expected) in [
("https://EXAMPLE.com/path", true),
("https://example.com.:8443/path", true),
("wss://example.com/path", true),
("http://example.com/path", false),
("ws://example.com/path", false),
("https://sub.example.com/path", false),
("https://example.com.evil.test/path", false),
("https://example.com@evil.test/path", false),
("https://127.0.0.1/path", false),
] {
assert_eq!(
policy.acquire(&Url::parse(url).unwrap()).is_ok(),
expected,
"{url}"
);
}
}
#[tokio::test]
async fn invalidation_revokes_existing_permits_and_rejects_stale_publication() {
let controller = NetworkPolicyController::default();
let policy = controller.policy();
let url = Url::parse("https://example.com").unwrap();
assert_eq!(
policy.acquire(&url).unwrap_err(),
NetworkPolicyDenied::Unavailable
);
let previous = policy.revision();
assert!(controller.publish(previous, DestinationPolicy::Unrestricted));
let permit = policy.acquire(&url).unwrap();
policy.invalidate();
assert!(!controller.publish(previous, DestinationPolicy::Unrestricted));
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
assert_eq!(
permit.run(async { "should not run" }).await,
Err(NetworkPolicyDenied::Revoked)
);
assert!(policy.acquire(&url).is_ok());
}
#[tokio::test]
async fn load_failure_recovers_current_account_but_cannot_revive_previous_account() {
let controller = NetworkPolicyController::default();
let policy = controller.policy();
let account = policy.clone().for_current_account();
let url = Url::parse("https://example.com").unwrap();
let mut changes = policy.changes().unwrap();
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
changes.changed().await.unwrap();
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
assert!(!changes.has_changed().unwrap());
let old_request = account.acquire(&url).unwrap();
controller.unavailable(policy.revision());
assert_eq!(
account.acquire(&url).unwrap_err(),
NetworkPolicyDenied::Unavailable
);
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
assert!(account.acquire(&url).is_ok());
assert_eq!(old_request.check(), Err(NetworkPolicyDenied::Revoked));
policy.invalidate();
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
assert_eq!(
account.acquire(&url).unwrap_err(),
NetworkPolicyDenied::Revoked
);
assert!(policy.for_current_account().acquire(&url).is_ok());
}
#[tokio::test]
async fn unsupported_sdk_work_is_denied_and_running_work_is_cancelled() {
let controller = NetworkPolicyController::default();
let policy = controller.policy();
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
let permit = policy.acquire_for_unsupported_sdk().unwrap();
controller.publish(
policy.revision(),
DestinationPolicy::Restricted {
allowed_hosts: BTreeSet::from(["example.com".to_string()]),
},
);
assert_eq!(
policy.acquire_for_unsupported_sdk().unwrap_err(),
NetworkPolicyDenied::UnsupportedTransport
);
assert_eq!(
permit.run(std::future::pending::<()>()).await,
Err(NetworkPolicyDenied::Revoked)
);
}

View File

@@ -0,0 +1,155 @@
//! Classify OpenAI API destinations without treating an unsupported origin as another provider.
use crate::is_allowed_chatgpt_host;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OpenAiDestination {
Supported,
Unsupported,
Other,
}
pub fn classify_openai_api_url(destination: &str) -> OpenAiDestination {
let Ok(url) = reqwest::Url::parse(destination) else {
return OpenAiDestination::Other;
};
let Some(host) = url.host_str() else {
return OpenAiDestination::Other;
};
let host = host.strip_suffix('.').unwrap_or(host);
let openai_owned = [
"openai.com",
"openai.org",
"openai-staging.com",
"chatgpt.com",
"chatgpt-staging.com",
]
.iter()
.any(|domain| {
let host = host.trim_end_matches('.');
host == *domain
|| host
.strip_suffix(*domain)
.is_some_and(|prefix| prefix.ends_with('.'))
});
if !openai_owned {
return OpenAiDestination::Other;
}
let supported_host = matches!(
host,
"api.openai.com"
| "gov.api.openai.com"
| "us.api.openai.com"
| "eu.api.openai.com"
| "au.api.openai.com"
| "ca.api.openai.com"
| "jp.api.openai.com"
| "in.api.openai.com"
| "sg.api.openai.com"
| "kr.api.openai.com"
| "gb.api.openai.com"
| "ae.api.openai.com"
| "mtls.api.openai.com"
| "mtls-us.api.openai.com"
| "mtls-eu.api.openai.com"
| "api.openai.org"
| "api.openai-staging.com"
) || is_allowed_chatgpt_host(host);
if supported_host
&& url.scheme() == "https"
&& url.port_or_known_default() == Some(443)
&& url.username().is_empty()
&& url.password().is_none()
{
OpenAiDestination::Supported
} else {
OpenAiDestination::Unsupported
}
}
pub fn is_openai_api_url(destination: &str) -> bool {
classify_openai_api_url(destination) == OpenAiDestination::Supported
}
#[cfg(test)]
mod tests {
use super::OpenAiDestination;
use super::classify_openai_api_url;
use super::is_openai_api_url;
#[test]
fn unsupported_openai_origins_are_distinct_from_other_providers() {
for destination in [
"https://unknown.api.openai.com/v1",
"https://api.openai.com../v1",
"https://api.openai.com:8443/v1",
"http://api.openai.com/v1",
"https://user@api.openai.com/v1",
"https://other.openai.org/v1",
] {
assert_eq!(
classify_openai_api_url(destination),
OpenAiDestination::Unsupported,
"{destination}"
);
}
for destination in [
"https://api.openai.com.example.test/v1",
"https://example.test/v1",
"http://127.0.0.1:8080/v1",
] {
assert_eq!(
classify_openai_api_url(destination),
OpenAiDestination::Other,
"{destination}"
);
}
}
#[test]
fn runtime_credentials_require_a_trusted_https_origin() {
for destination in [
"https://api.openai.com/v1",
"https://api.openai.com.:443/v1",
"https://gov.api.openai.com/v1",
"https://eu.api.openai.com/v1",
"https://us.api.openai.com/v1",
"https://au.api.openai.com/v1",
"https://ca.api.openai.com/v1",
"https://jp.api.openai.com/v1",
"https://in.api.openai.com/v1",
"https://sg.api.openai.com/v1",
"https://kr.api.openai.com/v1",
"https://gb.api.openai.com/v1",
"https://ae.api.openai.com/v1",
"https://mtls.api.openai.com/v1",
"https://mtls-us.api.openai.com/v1",
"https://mtls-eu.api.openai.com/v1",
"https://api.openai.org/v1",
"https://api.openai-staging.com/v1",
"https://chatgpt.com/backend-api",
"https://chat.openai.com/backend-api",
"https://us.chatgpt.com/backend-api",
"https://chatgpt-staging.com/backend-api",
"https://us.chatgpt-staging.com/backend-api",
] {
assert!(is_openai_api_url(destination), "{destination}");
}
for destination in [
"http://api.openai.com/v1",
"https://api.openai.com:8443/v1",
"https://user@api.openai.com/v1",
"https://user:password@chatgpt.com/backend-api",
"https://api.openai.com.example.test/v1",
"https://eu.api.openai.com.example.test/v1",
"https://unknown.api.openai.com/v1",
"https://evilchatgpt.com/backend-api",
"https://chatgpt.com.example.test/backend-api",
"https://foo.chat.openai.com/backend-api",
"http://127.0.0.1:8080/v1",
"https://example.test/v1",
] {
assert!(!is_openai_api_url(destination), "{destination}");
}
}
}

View File

@@ -0,0 +1,5 @@
//! Shared OpenAI identity and resource-selection header names.
pub const CHATGPT_ACCOUNT_ID_HEADER: &str = "chatgpt-account-id";
pub const OPENAI_ORGANIZATION_HEADER: &str = "openai-organization";
pub const OPENAI_PROJECT_HEADER: &str = "openai-project";

View File

@@ -0,0 +1,904 @@
//! Conservative outbound proxy selection for resolver-aware HTTP clients.
//!
//! When enabled, platform system discovery is tried first, explicit environment
//! proxies are the fallback, and the final fallback is a direct connection.
//! When disabled, callers retain the existing reqwest builder behavior.
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::io;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::time::Duration;
use std::time::Instant;
#[cfg(any(target_os = "windows", target_os = "macos"))]
use tokio::sync::Semaphore;
use http::HeaderValue;
use crate::NetworkPolicy;
use crate::chatgpt_cloudflare_cookies::ChatGptCookieStore;
use crate::custom_ca::BuildCustomCaTransportError;
use crate::custom_ca::build_reqwest_client_with_custom_ca;
use sha2::Digest;
use sha2::Sha256;
use thiserror::Error;
const SYSTEM_PROXY_SUCCESS_CACHE_TTL: Duration = Duration::from_secs(60);
const SYSTEM_PROXY_UNAVAILABLE_CACHE_TTL: Duration = Duration::from_secs(5);
const SYSTEM_PROXY_CACHE_MAX_ENTRIES: usize = 256;
#[cfg(any(target_os = "windows", target_os = "macos"))]
static ASYNC_SYSTEM_PROXY_RESOLUTION_PERMIT: Semaphore = Semaphore::const_new(1);
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "windows")]
mod windows;
/// Coarse semantic bucket for the HTTP or WebSocket client being constructed.
///
/// This is not the selected proxy route or a concrete endpoint. It labels the
/// product path that owns the client so proxy-resolution diagnostics can
/// distinguish auth, API, WebSocket, and miscellaneous traffic without exposing
/// endpoint details.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClientRouteClass {
/// Login, token refresh/revoke, PAT, and agent identity auth traffic.
Auth,
/// First-party API traffic that is not part of the auth flow.
Api,
/// WebSocket traffic.
WebSocket,
/// Call sites without a more specific route class.
Other,
}
impl fmt::Display for ClientRouteClass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Auth => "auth",
Self::Api => "api",
Self::WebSocket => "wss",
Self::Other => "other",
})
}
}
/// Coarse failure class for route selection errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouteFailureClass {
ProxyResolutionUnavailable,
ConnectTimeout,
ProxyAuthenticationRequired,
TlsError,
InvalidProxyConfig,
UnsupportedProxyScheme,
ResolverError,
}
impl fmt::Display for RouteFailureClass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::ProxyResolutionUnavailable => "proxy_resolution_unavailable",
Self::ConnectTimeout => "connect_timeout",
Self::ProxyAuthenticationRequired => "proxy_407",
Self::TlsError => "tls_error",
Self::InvalidProxyConfig => "invalid_proxy_config",
Self::UnsupportedProxyScheme => "unsupported_proxy_scheme",
Self::ResolverError => "resolver_error",
})
}
}
/// Resolved outbound proxy behavior for HTTP clients.
///
/// Callers must choose a policy explicitly so omitting feature resolution cannot silently select
/// legacy behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutboundProxyPolicy {
/// Preserve reqwest's built-in proxy behavior.
ReqwestDefault,
/// Resolve system/PAC/WPAD settings, then environment settings, then direct routing.
RespectSystemProxy,
}
/// Privacy-safe macOS system proxy configuration for one outbound destination.
#[cfg(target_os = "macos")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacosSystemProxyConfiguration {
/// A PAC script or automatic proxy-discovery route applies to the destination.
Automatic,
/// An explicitly configured HTTP or HTTPS proxy applies.
Manual,
/// macOS selected a direct connection for the destination.
Direct,
/// The destination or system proxy settings could not be inspected.
Unavailable,
}
/// Inspects macOS proxy configuration without executing PAC scripts or exposing proxy URLs.
#[cfg(target_os = "macos")]
pub fn macos_system_proxy_configuration(request_url: &str) -> MacosSystemProxyConfiguration {
macos::configuration(request_url)
}
/// Resolved proxy route for a concrete outbound destination.
///
/// `TransportDefault` preserves the underlying transport behavior only when system-proxy support
/// is disabled. When system resolution is enabled, environment and direct fallbacks are resolved
/// explicitly so the transport cannot repeat system discovery. Proxy URLs and no-proxy settings
/// are intentionally redacted from `Debug` output because they may contain credentials or private
/// hostnames.
#[derive(Clone, Hash, PartialEq, Eq)]
pub enum OutboundProxyRoute {
/// Preserve the underlying transport's existing proxy behavior.
TransportDefault,
/// Connect directly and bypass transport-level proxy discovery.
Direct,
/// Connect through the selected proxy URL.
Proxy {
url: String,
no_proxy: Option<String>,
},
}
impl fmt::Debug for OutboundProxyRoute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TransportDefault => f.write_str("TransportDefault"),
Self::Direct => f.write_str("Direct"),
Self::Proxy { .. } => f
.debug_struct("Proxy")
.field("url", &"<redacted>")
.field("no_proxy", &"<redacted>")
.finish(),
}
}
}
/// Builds route-specific HTTP clients using one resolved outbound proxy policy.
///
/// Construct this once from the effective application configuration and carry it with the
/// session or component that owns outbound requests. Individual request paths should supply only
/// their destination and route class rather than resolving feature state themselves.
#[derive(Clone)]
pub struct HttpClientFactory {
outbound_proxy_policy: OutboundProxyPolicy,
system_proxy_fallback: bool,
protect_sensitive_headers: bool,
chatgpt_cookie_store: Option<Arc<ChatGptCookieStore>>,
network_policy: NetworkPolicy,
}
impl PartialEq for HttpClientFactory {
fn eq(&self, other: &Self) -> bool {
self.outbound_proxy_policy == other.outbound_proxy_policy
&& self.system_proxy_fallback == other.system_proxy_fallback
&& self.protect_sensitive_headers == other.protect_sensitive_headers
&& self.network_policy == other.network_policy
&& self
.chatgpt_cookie_store
.as_ref()
.map(|store| store.configured_cookies())
== other
.chatgpt_cookie_store
.as_ref()
.map(|store| store.configured_cookies())
}
}
impl Eq for HttpClientFactory {}
impl fmt::Debug for HttpClientFactory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpClientFactory")
.field("outbound_proxy_policy", &self.outbound_proxy_policy)
.field("system_proxy_fallback", &self.system_proxy_fallback)
.field("protect_sensitive_headers", &self.protect_sensitive_headers)
.field("network_policy", &self.network_policy)
.finish()
}
}
impl HttpClientFactory {
/// Creates a factory from the outbound proxy policy resolved by the application.
pub const fn new(outbound_proxy_policy: OutboundProxyPolicy) -> Self {
Self {
outbound_proxy_policy,
system_proxy_fallback: false,
protect_sensitive_headers: false,
chatgpt_cookie_store: None,
network_policy: NetworkPolicy::unmanaged(),
}
}
/// Follows redirects while keeping headers marked sensitive on the original origin.
/// Reqwest's default redirect handling only recognizes standard credential headers.
pub fn with_sensitive_header_protection(mut self) -> Self {
self.protect_sensitive_headers = true;
self
}
/// Whether redirect handling removes sensitive headers when the origin changes.
pub fn protects_sensitive_headers(&self) -> bool {
self.protect_sensitive_headers
}
/// Carries the account/configuration owner's application policy into every transport.
pub fn with_network_policy(mut self, policy: NetworkPolicy) -> Self {
self.network_policy = policy;
self
}
pub fn network_policy(&self) -> &NetworkPolicy {
&self.network_policy
}
/// Changes the route policy while retaining the configured cookies and network policy.
pub fn with_outbound_proxy_policy(mut self, policy: OutboundProxyPolicy) -> Self {
self.outbound_proxy_policy = policy;
self
}
/// Allows bootstrap callers to retry through the system proxy when their request is safe
/// to replay. This does not change routing or enable retries for ordinary HTTP requests.
pub fn with_system_proxy_fallback(mut self) -> Self {
self.system_proxy_fallback = true;
self
}
pub fn allows_system_proxy_fallback(&self) -> bool {
self.system_proxy_fallback
&& self.outbound_proxy_policy == OutboundProxyPolicy::ReqwestDefault
}
/// Adds process-scoped cookies to requests made by ChatGPT cookie-store clients.
pub fn with_chatgpt_cookies(mut self, cookies: impl IntoIterator<Item = HeaderValue>) -> Self {
let cookies = cookies.into_iter().collect::<Vec<_>>();
self.chatgpt_cookie_store =
(!cookies.is_empty()).then(|| Arc::new(ChatGptCookieStore::new(cookies)));
self
}
/// Returns whether ChatGPT cookie-store clients have additional configured cookies.
pub fn has_chatgpt_cookies(&self) -> bool {
self.chatgpt_cookie_store.is_some()
}
pub(crate) fn chatgpt_cookie_store(&self) -> Option<Arc<ChatGptCookieStore>> {
self.chatgpt_cookie_store.clone()
}
/// Returns the outbound proxy policy used for clients built by this factory.
pub const fn outbound_proxy_policy(&self) -> OutboundProxyPolicy {
self.outbound_proxy_policy
}
/// Resolves the proxy route for a concrete destination.
///
/// WebSocket schemes are resolved through their HTTP equivalents so platform PAC and system
/// proxy APIs apply the same policy to `ws`/`wss` and `http`/`https` destinations. When system
/// resolution is unavailable, explicit environment settings are resolved before falling back
/// to a direct route. Ordered PAC candidates are collapsed to one route on Windows and macOS;
/// later proxy or `DIRECT` candidates are not retried after a connection failure.
pub fn resolve_proxy_route(&self, request_url: &str) -> OutboundProxyRoute {
resolve_proxy_route(
&ProcessEnv,
request_url,
self.outbound_proxy_policy,
resolve_system_proxy,
)
}
/// Resolves the proxy route for a concrete destination without blocking a Tokio worker.
pub async fn resolve_proxy_route_async(
&self,
request_url: String,
) -> io::Result<OutboundProxyRoute> {
if matches!(
self.outbound_proxy_policy,
OutboundProxyPolicy::ReqwestDefault
) {
return Ok(OutboundProxyRoute::TransportDefault);
}
if let Some(route) = self.cached_proxy_route(&request_url) {
return Ok(route);
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
return Ok(self.resolve_proxy_route(&request_url));
#[cfg(any(target_os = "windows", target_os = "macos"))]
{
let permit = ASYNC_SYSTEM_PROXY_RESOLUTION_PERMIT
.acquire()
.await
.map_err(io::Error::other)?;
let factory = self.clone();
tokio::task::spawn_blocking(move || {
// Keep the permit with the blocking task: cancelling the caller must not allow a
// second PAC/WinHTTP lookup to start while this one is still running.
let _permit = permit;
factory.resolve_proxy_route(&request_url)
})
.await
.map_err(io::Error::other)
}
}
fn cached_proxy_route(&self, request_url: &str) -> Option<OutboundProxyRoute> {
let env_proxy_kind = EnvProxyKind::from_request_url(request_url);
let request_url = proxy_resolution_url(request_url);
if RequestOrigin::parse(&request_url).is_none() {
return Some(OutboundProxyRoute::Direct);
}
cached_system_proxy_decision(&request_url)
.map(|decision| route_from_system_decision(&ProcessEnv, env_proxy_kind, decision))
}
}
fn resolve_proxy_route(
env: &dyn EnvSource,
request_url: &str,
outbound_proxy_policy: OutboundProxyPolicy,
resolve_system_proxy: impl FnOnce(&str, &RequestOrigin) -> SystemProxyDecision,
) -> OutboundProxyRoute {
if matches!(outbound_proxy_policy, OutboundProxyPolicy::ReqwestDefault) {
return OutboundProxyRoute::TransportDefault;
}
let env_proxy_kind = EnvProxyKind::from_request_url(request_url);
let request_url = proxy_resolution_url(request_url);
let Some(origin) = RequestOrigin::parse(&request_url) else {
return OutboundProxyRoute::Direct;
};
route_from_system_decision(
env,
env_proxy_kind,
resolve_system_proxy(&request_url, &origin),
)
}
fn route_from_system_decision(
env: &dyn EnvSource,
env_proxy_kind: EnvProxyKind,
decision: SystemProxyDecision,
) -> OutboundProxyRoute {
match decision {
SystemProxyDecision::Direct => OutboundProxyRoute::Direct,
SystemProxyDecision::Proxy { url } => OutboundProxyRoute::Proxy {
url,
no_proxy: None,
},
SystemProxyDecision::Unavailable { .. } => resolve_env_proxy_route(env, env_proxy_kind),
}
}
fn resolve_env_proxy_route(
env: &dyn EnvSource,
env_proxy_kind: EnvProxyKind,
) -> OutboundProxyRoute {
let proxy_url = match env_proxy_kind {
EnvProxyKind::Https => {
proxy_env_value(env, "HTTPS_PROXY").or_else(|| proxy_env_value(env, "ALL_PROXY"))
}
EnvProxyKind::SecureWebSocket => proxy_env_value(env, "HTTPS_PROXY")
.or_else(|| proxy_env_value(env, "HTTP_PROXY"))
.or_else(|| proxy_env_value(env, "ALL_PROXY")),
EnvProxyKind::Http => {
proxy_env_value(env, "HTTP_PROXY").or_else(|| proxy_env_value(env, "ALL_PROXY"))
}
EnvProxyKind::Other => proxy_env_value(env, "ALL_PROXY"),
};
match proxy_url {
Some(url) => OutboundProxyRoute::Proxy {
url,
no_proxy: proxy_env_value(env, "NO_PROXY"),
},
None => OutboundProxyRoute::Direct,
}
}
#[derive(Clone, Copy)]
enum EnvProxyKind {
Http,
Https,
SecureWebSocket,
Other,
}
impl EnvProxyKind {
fn from_request_url(request_url: &str) -> Self {
let scheme = request_url
.parse::<http::Uri>()
.ok()
.and_then(|uri| uri.scheme_str().map(str::to_ascii_lowercase));
match scheme.as_deref() {
Some("http" | "ws") => Self::Http,
Some("https") => Self::Https,
Some("wss") => Self::SecureWebSocket,
Some(_) | None => Self::Other,
}
}
}
fn proxy_resolution_url(request_url: &str) -> Cow<'_, str> {
if let Some(suffix) = request_url.strip_prefix("wss://") {
Cow::Owned(format!("https://{suffix}"))
} else if let Some(suffix) = request_url.strip_prefix("ws://") {
Cow::Owned(format!("http://{suffix}"))
} else {
Cow::Borrowed(request_url)
}
}
/// Error while building a resolver-aware reqwest client.
#[derive(Debug, Error)]
pub enum BuildRouteAwareHttpClientError {
#[error(transparent)]
CustomCa(#[from] BuildCustomCaTransportError),
#[error("Failed to build HTTP client with explicit TLS configuration: {0}")]
ExplicitTls(reqwest::Error),
#[error("Failed to configure outbound proxy selected for {route_class}")]
InvalidProxyConfig { route_class: ClientRouteClass },
}
impl From<BuildRouteAwareHttpClientError> for io::Error {
fn from(error: BuildRouteAwareHttpClientError) -> Self {
match error {
BuildRouteAwareHttpClientError::CustomCa(error) => error.into(),
BuildRouteAwareHttpClientError::InvalidProxyConfig { .. }
| BuildRouteAwareHttpClientError::ExplicitTls(_) => io::Error::other(error),
}
}
}
/// Builds a reqwest client with the resolved route and shared CA handling.
pub(crate) fn build_reqwest_client_for_route(
builder: reqwest::ClientBuilder,
route_class: ClientRouteClass,
route: &OutboundProxyRoute,
) -> Result<reqwest::Client, BuildRouteAwareHttpClientError> {
let builder = configure_builder_for_resolved_route(builder, route_class, route)?;
build_reqwest_client_with_custom_ca(builder).map_err(Into::into)
}
#[cfg(test)]
fn configure_proxy_for_route(
env: &dyn EnvSource,
builder: reqwest::ClientBuilder,
request_url: &str,
route_class: ClientRouteClass,
outbound_proxy_policy: OutboundProxyPolicy,
resolve_system_proxy: impl FnOnce(&str, &RequestOrigin) -> SystemProxyDecision,
) -> Result<reqwest::ClientBuilder, BuildRouteAwareHttpClientError> {
let route = resolve_proxy_route(
env,
request_url,
outbound_proxy_policy,
resolve_system_proxy,
);
configure_builder_for_resolved_route(builder, route_class, &route)
}
pub(crate) fn configure_builder_for_resolved_route(
builder: reqwest::ClientBuilder,
route_class: ClientRouteClass,
route: &OutboundProxyRoute,
) -> Result<reqwest::ClientBuilder, BuildRouteAwareHttpClientError> {
match route {
OutboundProxyRoute::TransportDefault => Ok(builder),
OutboundProxyRoute::Direct => Ok(builder.no_proxy()),
OutboundProxyRoute::Proxy { url, no_proxy } => {
let no_proxy = no_proxy.as_deref().and_then(reqwest::NoProxy::from_string);
configure_concrete_proxy(builder, route_class, url, no_proxy)
}
}
}
fn configure_concrete_proxy(
builder: reqwest::ClientBuilder,
route_class: ClientRouteClass,
proxy_url: &str,
no_proxy: Option<reqwest::NoProxy>,
) -> Result<reqwest::ClientBuilder, BuildRouteAwareHttpClientError> {
let proxy = match reqwest::Proxy::all(proxy_url) {
Ok(proxy) => proxy,
Err(_source) => {
return Err(BuildRouteAwareHttpClientError::InvalidProxyConfig { route_class });
}
};
Ok(builder.proxy(proxy.no_proxy(no_proxy)))
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(dead_code)]
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(match scheme.as_str() {
"http" | "ws" => Some(80),
"https" | "wss" => Some(443),
_ => None,
})?;
Some(Self { scheme, host, port })
}
}
#[cfg_attr(
not(any(target_os = "windows", target_os = "macos")),
allow(
dead_code,
reason = "Direct and Proxy are constructed only by platform-specific resolvers"
)
)]
#[derive(Debug, Clone, PartialEq, Eq)]
enum SystemProxyDecision {
Direct,
Proxy { url: String },
Unavailable { failure: RouteFailureClass },
}
fn resolve_system_proxy(request_url: &str, origin: &RequestOrigin) -> SystemProxyDecision {
let cache = SYSTEM_PROXY_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
resolve_system_proxy_with(cache, request_url, origin, resolve_platform_system_proxy)
}
fn resolve_system_proxy_with(
cache: &Mutex<HashMap<String, CachedSystemProxyDecision>>,
request_url: &str,
origin: &RequestOrigin,
resolve_platform_system_proxy: impl FnOnce(&str, &RequestOrigin) -> SystemProxyDecision,
) -> SystemProxyDecision {
let mut cache = match cache.lock() {
Ok(cache) => cache,
Err(error) => panic!("system proxy cache lock should not be poisoned: {error}"),
};
let cache_key = system_proxy_cache_key(request_url);
if let Some(decision) =
cached_system_proxy_decision_from_cache(&mut cache, &cache_key, Instant::now())
{
return decision;
}
// Keep cache misses single-flight. Platform PAC/WPAD APIs are synchronous, so async callers
// run this work on the blocking pool; serializing misses prevents concurrent requests from
// consuming an unbounded number of blocking workers while system lookup is pending.
let decision = resolve_platform_system_proxy(request_url, origin);
insert_system_proxy_cache_entry(&mut cache, &cache_key, decision.clone(), Instant::now());
decision
}
#[cfg(target_os = "macos")]
fn resolve_platform_system_proxy(request_url: &str, origin: &RequestOrigin) -> SystemProxyDecision {
macos::resolve(request_url, origin)
}
#[cfg(target_os = "windows")]
fn resolve_platform_system_proxy(request_url: &str, origin: &RequestOrigin) -> SystemProxyDecision {
windows::resolve(request_url, origin)
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn resolve_platform_system_proxy(
_request_url: &str,
_origin: &RequestOrigin,
) -> SystemProxyDecision {
SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
}
}
#[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(request_url: &str) -> Option<SystemProxyDecision> {
let cache = SYSTEM_PROXY_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
// Platform resolution holds this mutex. Let contended async callers wait in the resolver
// lane instead of blocking their executor while checking the cache.
let mut cache = cache.try_lock().ok()?;
let key = system_proxy_cache_key(request_url);
cached_system_proxy_decision_from_cache(&mut cache, &key, Instant::now())
}
fn cached_system_proxy_decision_from_cache(
cache: &mut HashMap<String, CachedSystemProxyDecision>,
cache_key: &str,
now: Instant,
) -> Option<SystemProxyDecision> {
let cached = cache.get(cache_key)?;
if cached.expires_at > now {
return Some(cached.decision.clone());
}
cache.remove(cache_key);
None
}
fn cache_system_proxy_decision(request_url: &str, decision: SystemProxyDecision) {
let cache = SYSTEM_PROXY_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
if let Ok(mut cache) = cache.lock() {
let cache_key = system_proxy_cache_key(request_url);
insert_system_proxy_cache_entry(&mut cache, &cache_key, decision, Instant::now());
}
}
/// Primes one proxy decision for cross-crate integration tests.
///
/// This is public only so tests in HTTP-client consumers can exercise system-proxy routing
/// deterministically on every supported platform.
pub fn cache_system_proxy_route_for_test(request_url: &str, proxy_url: String) {
cache_system_proxy_decision(request_url, SystemProxyDecision::Proxy { url: proxy_url });
}
fn insert_system_proxy_cache_entry(
cache: &mut HashMap<String, CachedSystemProxyDecision>,
cache_key: &str,
decision: SystemProxyDecision,
now: Instant,
) {
let ttl = match &decision {
SystemProxyDecision::Direct | SystemProxyDecision::Proxy { .. } => {
SYSTEM_PROXY_SUCCESS_CACHE_TTL
}
SystemProxyDecision::Unavailable { .. } => SYSTEM_PROXY_UNAVAILABLE_CACHE_TTL,
};
cache.retain(|_, cached| cached.expires_at > now);
if cache.len() >= SYSTEM_PROXY_CACHE_MAX_ENTRIES
&& !cache.contains_key(cache_key)
&& let Some(cache_key_to_evict) = cache
.iter()
.min_by_key(|(_, cached)| cached.expires_at)
.map(|(cache_key, _)| cache_key.clone())
{
cache.remove(&cache_key_to_evict);
}
cache.insert(
cache_key.to_string(),
CachedSystemProxyDecision {
decision,
expires_at: now + ttl,
},
);
}
fn system_proxy_cache_key(request_url: &str) -> String {
// Keep URL-specific PAC decisions without retaining the raw routed URL.
let mut hasher = Sha256::new();
hasher.update(b"system-proxy-cache-v1\0");
hasher.update(request_url.as_bytes());
format!("{:x}", hasher.finalize())
}
#[cfg(any(test, target_os = "windows"))]
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))
}
#[cfg(any(test, target_os = "windows"))]
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
}
#[cfg(any(test, target_os = "windows"))]
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()
}
#[cfg(any(test, target_os = "windows"))]
#[derive(Debug, Clone, PartialEq, Eq)]
enum ParsedProxyListDecision {
Direct,
Proxy(String),
UnsupportedScheme,
Unavailable,
}
#[cfg(any(test, target_os = "windows"))]
fn parse_proxy_list(input: &str, target_scheme: &str) -> ParsedProxyListDecision {
let mut saw_unsupported = false;
{
let mut process_token = |token: &str| {
let decision = parse_proxy_token(token, target_scheme);
match decision {
ParsedProxyListDecision::Direct => Some(ParsedProxyListDecision::Direct),
ParsedProxyListDecision::Proxy(url) => Some(ParsedProxyListDecision::Proxy(url)),
ParsedProxyListDecision::UnsupportedScheme => {
saw_unsupported = true;
None
}
ParsedProxyListDecision::Unavailable => None,
}
};
for segment in input
.split(';')
.map(str::trim)
.filter(|segment| !segment.is_empty())
{
let mut parts = segment.split_whitespace();
let directive = parts.next();
let hostport = parts.next();
let extra = parts.next();
let is_proxy_directive = matches!(
directive.map(str::to_ascii_lowercase).as_deref(),
Some("proxy" | "http" | "https" | "socks" | "socks4" | "socks5")
) && hostport.is_some()
&& extra.is_none();
if is_proxy_directive {
if let Some(decision) = process_token(segment) {
return decision;
}
} else {
for token in segment.split_whitespace() {
if let Some(decision) = process_token(token) {
return decision;
}
}
}
}
}
if saw_unsupported {
ParsedProxyListDecision::UnsupportedScheme
} else {
ParsedProxyListDecision::Unavailable
}
}
#[cfg(any(test, target_os = "windows"))]
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;
}
let mut parts = token.split_whitespace();
let directive = parts.next();
let hostport = parts.next();
if let (Some(directive), Some(hostport), None) = (directive, hostport, parts.next()) {
return match directive.to_ascii_lowercase().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)
}
#[cfg(any(test, target_os = "windows"))]
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)
}
}
#[cfg(any(test, target_os = "windows"))]
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}"))
}
trait EnvSource {
fn var(&self, key: &str) -> Option<String>;
}
struct ProcessEnv;
impl EnvSource for ProcessEnv {
fn var(&self, key: &str) -> Option<String> {
std::env::var(key).ok()
}
}
fn proxy_env_value(env: &dyn EnvSource, upper: &str) -> Option<String> {
let lower = upper.to_ascii_lowercase();
env.var(upper)
.or_else(|| env.var(&lower))
.filter(|value| !value.is_empty())
}
#[cfg(test)]
#[path = "route_aware_redirect_integration_tests.rs"]
mod redirect_integration_tests;
#[cfg(test)]
#[path = "outbound_proxy_tests.rs"]
mod tests;

View File

@@ -0,0 +1,418 @@
//! macOS system proxy resolution through SystemConfiguration and CFNetwork.
use std::ffi::c_void;
use std::ptr;
use std::time::Duration;
use std::time::Instant;
use super::MacosSystemProxyConfiguration;
use super::RequestOrigin;
use super::RouteFailureClass;
use super::SystemProxyDecision;
use system_configuration::core_foundation::array::CFArray;
use system_configuration::core_foundation::array::CFArrayRef;
use system_configuration::core_foundation::base::CFEqual;
use system_configuration::core_foundation::base::CFGetTypeID;
use system_configuration::core_foundation::base::CFIndex;
use system_configuration::core_foundation::base::CFType;
use system_configuration::core_foundation::base::CFTypeRef;
use system_configuration::core_foundation::base::TCFType;
use system_configuration::core_foundation::base::kCFAllocatorDefault;
use system_configuration::core_foundation::dictionary::CFDictionary;
use system_configuration::core_foundation::dictionary::CFDictionaryRef;
use system_configuration::core_foundation::error::CFErrorRef;
use system_configuration::core_foundation::number::CFNumber;
use system_configuration::core_foundation::runloop::CFRunLoop;
use system_configuration::core_foundation::runloop::CFRunLoopSource;
use system_configuration::core_foundation::runloop::CFRunLoopSourceInvalidate;
use system_configuration::core_foundation::runloop::CFRunLoopSourceRef;
use system_configuration::core_foundation::runloop::kCFRunLoopDefaultMode;
use system_configuration::core_foundation::string::CFString;
use system_configuration::core_foundation::string::CFStringRef;
use system_configuration::core_foundation::url::CFURL;
use system_configuration::core_foundation::url::CFURLCreateWithString;
use system_configuration::core_foundation::url::CFURLGetTypeID;
use system_configuration::core_foundation::url::CFURLRef;
use system_configuration::dynamic_store::SCDynamicStoreBuilder;
const PAC_EXECUTION_TIMEOUT: Duration = Duration::from_secs(5);
type ProxyDictionary = CFDictionary<CFString, CFType>;
type ProxyArray = CFArray<ProxyDictionary>;
#[repr(C)]
struct CFStreamClientContext {
version: CFIndex,
info: *mut c_void,
retain: Option<unsafe extern "C" fn(*mut c_void) -> *mut c_void>,
release: Option<unsafe extern "C" fn(*mut c_void)>,
copy_description: Option<unsafe extern "C" fn(*mut c_void) -> CFStringRef>,
}
type CFProxyAutoConfigurationResultCallback =
unsafe extern "C" fn(*mut c_void, CFArrayRef, CFErrorRef);
#[link(name = "CFNetwork", kind = "framework")]
unsafe extern "C" {
static kCFProxyTypeKey: CFStringRef;
static kCFProxyHostNameKey: CFStringRef;
static kCFProxyPortNumberKey: CFStringRef;
static kCFProxyAutoConfigurationURLKey: CFStringRef;
static kCFProxyAutoConfigurationJavaScriptKey: CFStringRef;
static kCFProxyTypeNone: CFStringRef;
static kCFProxyTypeHTTP: CFStringRef;
static kCFProxyTypeHTTPS: CFStringRef;
static kCFProxyTypeSOCKS: CFStringRef;
static kCFProxyTypeAutoConfigurationURL: CFStringRef;
static kCFProxyTypeAutoConfigurationJavaScript: CFStringRef;
fn CFNetworkCopyProxiesForURL(url: CFURLRef, proxy_settings: CFDictionaryRef) -> CFArrayRef;
fn CFNetworkExecuteProxyAutoConfigurationURL(
proxy_auto_config_url: CFURLRef,
target_url: CFURLRef,
callback: CFProxyAutoConfigurationResultCallback,
client_context: *mut CFStreamClientContext,
) -> CFRunLoopSourceRef;
fn CFNetworkExecuteProxyAutoConfigurationScript(
proxy_auto_config_script: CFStringRef,
target_url: CFURLRef,
callback: CFProxyAutoConfigurationResultCallback,
client_context: *mut CFStreamClientContext,
) -> CFRunLoopSourceRef;
}
pub(super) fn resolve(request_url: &str, origin: &RequestOrigin) -> SystemProxyDecision {
let Some(target_url) = cf_url(request_url) else {
return SystemProxyDecision::Unavailable {
failure: RouteFailureClass::InvalidProxyConfig,
};
};
let Some(settings) = system_proxy_settings() else {
return SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
};
};
let Some(proxies) = copy_proxies_for_url(&target_url, &settings) else {
return SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
};
};
proxy_array_decision(&proxies, &target_url, origin)
}
pub(super) fn configuration(request_url: &str) -> MacosSystemProxyConfiguration {
let Some(target_url) = cf_url(request_url) else {
return MacosSystemProxyConfiguration::Unavailable;
};
let Some(settings) = system_proxy_settings() else {
return MacosSystemProxyConfiguration::Unavailable;
};
let Some(proxies) = copy_proxies_for_url(&target_url, &settings) else {
return MacosSystemProxyConfiguration::Unavailable;
};
(&proxies)
.into_iter()
.find_map(|proxy| {
let proxy_type = cf_string_value(&proxy, unsafe { kCFProxyTypeKey })?;
if cf_string_equals(&proxy_type, unsafe { kCFProxyTypeAutoConfigurationURL })
|| cf_string_equals(&proxy_type, unsafe {
kCFProxyTypeAutoConfigurationJavaScript
})
{
Some(MacosSystemProxyConfiguration::Automatic)
} else if cf_string_equals(&proxy_type, unsafe { kCFProxyTypeHTTP })
|| cf_string_equals(&proxy_type, unsafe { kCFProxyTypeHTTPS })
{
Some(MacosSystemProxyConfiguration::Manual)
} else {
cf_string_equals(&proxy_type, unsafe { kCFProxyTypeNone })
.then_some(MacosSystemProxyConfiguration::Direct)
}
})
.unwrap_or(MacosSystemProxyConfiguration::Unavailable)
}
fn system_proxy_settings() -> Option<CFDictionary<CFString, CFType>> {
let store = SCDynamicStoreBuilder::new("Codex").build()?;
store.get_proxies()
}
fn copy_proxies_for_url(
target_url: &CFURL,
settings: &CFDictionary<CFString, CFType>,
) -> Option<ProxyArray> {
let proxies = unsafe {
CFNetworkCopyProxiesForURL(
target_url.as_concrete_TypeRef(),
settings.as_concrete_TypeRef(),
)
};
if proxies.is_null() {
None
} else {
Some(unsafe { ProxyArray::wrap_under_create_rule(proxies) })
}
}
fn proxy_array_decision(
proxies: &ProxyArray,
target_url: &CFURL,
origin: &RequestOrigin,
) -> SystemProxyDecision {
let mut saw_unsupported = false;
let mut saw_unavailable = false;
// CFNetwork returns candidates in failover order, but the shared resolver currently carries
// only one route. This matches the Windows limitation; cross-platform retry requires request
// replay semantics and is intentionally deferred.
for proxy in proxies {
match proxy_entry_decision(&proxy, target_url, origin) {
ProxyEntryDecision::Direct => return SystemProxyDecision::Direct,
ProxyEntryDecision::Proxy { url } => return SystemProxyDecision::Proxy { url },
ProxyEntryDecision::UnsupportedScheme => saw_unsupported = true,
ProxyEntryDecision::Unavailable => saw_unavailable = true,
}
}
if saw_unsupported {
SystemProxyDecision::Unavailable {
failure: RouteFailureClass::UnsupportedProxyScheme,
}
} else if saw_unavailable {
SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
}
} else {
SystemProxyDecision::Direct
}
}
fn proxy_entry_decision(
proxy: &ProxyDictionary,
target_url: &CFURL,
origin: &RequestOrigin,
) -> ProxyEntryDecision {
let Some(proxy_type) = cf_string_value(proxy, unsafe { kCFProxyTypeKey }) else {
return ProxyEntryDecision::Unavailable;
};
if cf_string_equals(&proxy_type, unsafe { kCFProxyTypeNone }) {
return ProxyEntryDecision::Direct;
}
if cf_string_equals(&proxy_type, unsafe { kCFProxyTypeHTTP }) {
return concrete_proxy_entry(proxy, "http");
}
if cf_string_equals(&proxy_type, unsafe { kCFProxyTypeHTTPS }) {
// CFNetwork's HTTPS proxy type is a tunneling proxy for HTTPS destinations; it does not
// preserve an explicit TLS-to-proxy transport. See https://developer.apple.com/documentation/cfnetwork/kcfproxytypehttps.
return concrete_proxy_entry(proxy, "http");
}
if cf_string_equals(&proxy_type, unsafe { kCFProxyTypeSOCKS }) {
return ProxyEntryDecision::UnsupportedScheme;
}
if cf_string_equals(&proxy_type, unsafe { kCFProxyTypeAutoConfigurationURL }) {
let Some(pac_url) = cf_url_value(proxy, unsafe { kCFProxyAutoConfigurationURLKey }) else {
return ProxyEntryDecision::Unavailable;
};
return pac_decision(execute_pac_url(&pac_url, target_url), target_url, origin);
}
if cf_string_equals(&proxy_type, unsafe {
kCFProxyTypeAutoConfigurationJavaScript
}) {
let Some(script) =
cf_string_value(proxy, unsafe { kCFProxyAutoConfigurationJavaScriptKey })
else {
return ProxyEntryDecision::Unavailable;
};
return pac_decision(
execute_pac(|callback, context| unsafe {
CFNetworkExecuteProxyAutoConfigurationScript(
script.as_concrete_TypeRef(),
target_url.as_concrete_TypeRef(),
callback,
context,
)
}),
target_url,
origin,
);
}
ProxyEntryDecision::Unavailable
}
fn pac_decision(
result: Result<ProxyArray, RouteFailureClass>,
target_url: &CFURL,
origin: &RequestOrigin,
) -> ProxyEntryDecision {
let proxies = match result {
Ok(proxies) => proxies,
Err(RouteFailureClass::UnsupportedProxyScheme) => {
return ProxyEntryDecision::UnsupportedScheme;
}
Err(_) => return ProxyEntryDecision::Unavailable,
};
match proxy_array_decision(&proxies, target_url, origin) {
SystemProxyDecision::Direct => ProxyEntryDecision::Direct,
SystemProxyDecision::Proxy { url } => ProxyEntryDecision::Proxy { url },
SystemProxyDecision::Unavailable {
failure: RouteFailureClass::UnsupportedProxyScheme,
} => ProxyEntryDecision::UnsupportedScheme,
SystemProxyDecision::Unavailable { failure: _ } => ProxyEntryDecision::Unavailable,
}
}
fn execute_pac_url(pac_url: &CFURL, target_url: &CFURL) -> Result<ProxyArray, RouteFailureClass> {
execute_pac(|callback, context| unsafe {
CFNetworkExecuteProxyAutoConfigurationURL(
pac_url.as_concrete_TypeRef(),
target_url.as_concrete_TypeRef(),
callback,
context,
)
})
}
fn execute_pac(
create_source: impl FnOnce(
CFProxyAutoConfigurationResultCallback,
*mut CFStreamClientContext,
) -> CFRunLoopSourceRef,
) -> Result<ProxyArray, RouteFailureClass> {
let mut state = PacRunLoopState { result: None };
let mut context = CFStreamClientContext {
version: 0,
info: (&mut state as *mut PacRunLoopState).cast::<c_void>(),
retain: None,
release: None,
copy_description: None,
};
let source = create_source(pac_result_callback, &mut context);
if source.is_null() {
return Err(RouteFailureClass::ProxyResolutionUnavailable);
}
let source = unsafe { CFRunLoopSource::wrap_under_create_rule(source) };
let run_loop = CFRunLoop::get_current();
let mode = unsafe { kCFRunLoopDefaultMode };
run_loop.add_source(&source, mode);
let started_at = Instant::now();
while state.result.is_none() && started_at.elapsed() < PAC_EXECUTION_TIMEOUT {
CFRunLoop::run_in_mode(mode, Duration::from_millis(50), true);
}
if state.result.is_none() {
unsafe { CFRunLoopSourceInvalidate(source.as_concrete_TypeRef()) };
}
run_loop.remove_source(&source, mode);
state
.result
.unwrap_or(Err(RouteFailureClass::ConnectTimeout))
}
unsafe extern "C" fn pac_result_callback(
client: *mut c_void,
proxies: CFArrayRef,
error: CFErrorRef,
) {
let state = unsafe { &mut *client.cast::<PacRunLoopState>() };
state.result = if !error.is_null() || proxies.is_null() {
Some(Err(RouteFailureClass::ProxyResolutionUnavailable))
} else {
Some(Ok(unsafe { ProxyArray::wrap_under_get_rule(proxies) }))
};
CFRunLoop::get_current().stop();
}
struct PacRunLoopState {
result: Option<Result<ProxyArray, RouteFailureClass>>,
}
fn concrete_proxy_entry(proxy: &ProxyDictionary, proxy_scheme: &str) -> ProxyEntryDecision {
let Some(host) = cf_string_value(proxy, unsafe { kCFProxyHostNameKey })
.map(|host| host.to_string())
.filter(|host| !host.is_empty())
else {
return ProxyEntryDecision::Unavailable;
};
let host = bracket_ipv6_host(&host);
let url = match cf_i32_value(proxy, unsafe { kCFProxyPortNumberKey }) {
Some(port) if port > 0 => format!("{proxy_scheme}://{host}:{port}"),
_ => format!("{proxy_scheme}://{host}"),
};
ProxyEntryDecision::Proxy { url }
}
fn bracket_ipv6_host(host: &str) -> String {
if host.contains(':') && !host.starts_with('[') {
format!("[{host}]")
} else {
host.to_string()
}
}
fn cf_string_value(proxy: &ProxyDictionary, key: CFStringRef) -> Option<CFString> {
proxy
.find(key)
.and_then(|value| value.downcast::<CFString>())
}
fn cf_i32_value(proxy: &ProxyDictionary, key: CFStringRef) -> Option<i32> {
proxy
.find(key)
.and_then(|value| value.downcast::<CFNumber>())
.and_then(|value| value.to_i32())
}
fn cf_url_value(proxy: &ProxyDictionary, key: CFStringRef) -> Option<CFURL> {
proxy.find(key).and_then(|value| {
if unsafe { CFGetTypeID(value.as_CFTypeRef()) == CFURLGetTypeID() } {
Some(unsafe { CFURL::wrap_under_get_rule(value.as_CFTypeRef() as CFURLRef) })
} else {
value
.downcast::<CFString>()
.and_then(|value| cf_url(value.to_string().as_str()))
}
})
}
fn cf_string_equals(value: &CFString, expected: CFStringRef) -> bool {
unsafe { CFEqual(value.as_CFTypeRef(), expected as CFTypeRef) != 0 }
}
fn cf_url(value: &str) -> Option<CFURL> {
let value = CFString::new(value);
let url = unsafe {
CFURLCreateWithString(
kCFAllocatorDefault,
value.as_concrete_TypeRef(),
ptr::null(),
)
};
if url.is_null() {
None
} else {
Some(unsafe { CFURL::wrap_under_create_rule(url) })
}
}
enum ProxyEntryDecision {
Direct,
Proxy { url: String },
UnsupportedScheme,
Unavailable,
}

View File

@@ -0,0 +1,364 @@
//! Windows system proxy resolution through WinHTTP.
use std::ffi::c_void;
use std::ptr;
use super::ParsedProxyListDecision;
use super::RequestOrigin;
use super::RouteFailureClass;
use super::SystemProxyDecision;
use super::no_proxy_matches_origin;
use super::parse_proxy_list;
use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND;
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 { 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;
}
return proxy_list_decision(proxy, origin);
}
if ie_config.auto_config_url.is_some() || ie_config.auto_detect {
SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
}
} else {
SystemProxyDecision::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: FALSE,
};
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 {
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 {
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;
}
if proxy_info.access_type != WINHTTP_ACCESS_TYPE_NAMED_PROXY {
return SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
};
}
let Some(proxy) = proxy_info.proxy.as_deref() else {
return SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
};
};
proxy_list_decision(proxy, origin)
}
fn proxy_list_decision(proxy_list: &str, origin: &RequestOrigin) -> SystemProxyDecision {
match parse_proxy_list(proxy_list, &origin.scheme) {
ParsedProxyListDecision::Direct => SystemProxyDecision::Direct,
ParsedProxyListDecision::Proxy(url) => SystemProxyDecision::Proxy { url },
ParsedProxyListDecision::UnsupportedScheme => SystemProxyDecision::Unavailable {
failure: RouteFailureClass::UnsupportedProxyScheme,
},
ParsedProxyListDecision::Unavailable => SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
},
}
}
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 {
let error = last_error();
if error == ERROR_FILE_NOT_FOUND {
// Match WinHTTP's fallback by attempting WPAD when no IE proxy settings exist.
return Ok(IeProxyConfig {
auto_detect: true,
..Default::default()
});
}
return Err(classify_winhttp_error(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, Default)]
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(|ch: char| ch == ';' || ch == ',' || ch.is_whitespace())
.map(str::trim)
.filter(|entry| !entry.is_empty())
.any(|entry| {
if entry.eq_ignore_ascii_case("<local>") {
!origin.host.contains('.')
} else {
no_proxy_matches_origin(entry, origin)
}
})
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod tests;
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::ProxyResolutionUnavailable,
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,
}
}

View File

@@ -0,0 +1,20 @@
//! Windows proxy parsing tests.
use super::*;
#[test]
fn proxy_bypass_matches_whitespace_separated_winhttp_entries() {
let local_origin = RequestOrigin {
scheme: "https".to_string(),
host: "intranet".to_string(),
port: 443,
};
assert!(proxy_bypass_matches_origin("<local> *.corp", &local_origin));
let corp_origin = RequestOrigin {
scheme: "https".to_string(),
host: "service.corp".to_string(),
port: 443,
};
assert!(proxy_bypass_matches_origin("<local> *.corp", &corp_origin));
}

View File

@@ -0,0 +1,388 @@
use super::*;
use crate::HttpTransport;
use crate::Request;
use crate::ReqwestTransport;
use crate::TransportError;
use futures::TryStreamExt;
use http::Method;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::SubscriberExt;
#[tokio::test]
async fn transport_resolves_routes_for_execute_and_stream_redirects() {
let initial_url = "http://transport-start.test/start";
let destination_url = "http://transport-final.test/final";
let (destination_addr, destination_thread) = spawn_http_listener(vec![
"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_string();
2
]);
let (initial_addr, initial_thread) = spawn_http_listener(vec![
format!(
"HTTP/1.1 307 Temporary Redirect\r\nLocation: {destination_url}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
2
]);
for (url, address) in [
(initial_url, initial_addr),
(destination_url, destination_addr),
] {
cache_system_proxy_decision(
url,
SystemProxyDecision::Proxy {
url: format!("http://{address}"),
},
);
}
let transport =
ReqwestTransport::from_route_aware_client_pool(crate::RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
));
let mut request = Request::new(Method::POST, initial_url.to_string())
.with_json(&serde_json::json!({"input": "redirected request"}));
request.timeout = Some(Duration::from_secs(/*secs*/ 2));
let response = transport
.execute(request.clone())
.await
.expect("execute should follow the routed redirect");
let streamed = transport
.stream(request)
.await
.expect("stream should follow the routed redirect");
let streamed_body = streamed
.bytes
.try_collect::<Vec<_>>()
.await
.expect("streamed body should be readable")
.concat();
assert_eq!(
(response.body.as_ref(), streamed_body.as_slice()),
(&b"ok"[..], &b"ok"[..])
);
let initial_requests = initial_thread.join().expect("initial proxy should finish");
let destination_requests = destination_thread
.join()
.expect("destination proxy should finish");
assert_eq!((initial_requests.len(), destination_requests.len()), (2, 2));
for (initial, destination) in initial_requests.iter().zip(&destination_requests) {
assert!(initial.starts_with("POST http://transport-start.test/start HTTP/1.1\r\n"));
assert!(destination.starts_with("POST http://transport-final.test/final HTTP/1.1\r\n"));
assert_eq!(
(
initial.split_once("\r\n\r\n").map(|(_, body)| body),
destination.split_once("\r\n\r\n").map(|(_, body)| body),
),
(
Some(r#"{"input":"redirected request"}"#),
Some(r#"{"input":"redirected request"}"#),
)
);
}
}
#[tokio::test]
async fn transport_classifies_route_construction_failures_as_build_errors() {
let request_url = "http://transport-invalid-proxy.test/request";
cache_system_proxy_decision(
request_url,
SystemProxyDecision::Proxy {
url: "://invalid".to_string(),
},
);
let transport =
ReqwestTransport::from_route_aware_client_pool(crate::RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
));
let error = transport
.execute(Request::new(Method::GET, request_url.to_string()))
.await
.expect_err("invalid proxy configuration should fail");
assert!(matches!(error, TransportError::Build(_)));
}
#[tokio::test]
async fn transport_classifies_connection_failures_without_request_urls() {
let listener =
std::net::TcpListener::bind(("127.0.0.1", 0)).expect("unavailable proxy port should bind");
let address = listener.local_addr().expect("proxy should have an address");
drop(listener);
let request_url = "http://transport-unavailable-proxy.test/request?token=url-secret";
cache_system_proxy_decision(
request_url,
SystemProxyDecision::Proxy {
url: format!("http://{address}"),
},
);
let transport =
ReqwestTransport::from_route_aware_client_pool(crate::RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
));
let error = match transport
.stream(Request::new(Method::GET, request_url.to_string()))
.await
{
Err(TransportError::Connection(error)) => error,
Err(error) => panic!("expected a connection failure, got {error}"),
Ok(_) => panic!("unavailable proxy should not return a response"),
};
assert!(!error.to_string().contains("url-secret"));
}
#[tokio::test]
async fn route_aware_pool_strips_credentials_on_cross_origin_redirect() {
let (destination_addr, destination_thread) = spawn_proxy_listener();
let destination_url = format!("http://{destination_addr}/final");
let (redirect_addr, redirect_thread) = spawn_redirect_listener(&destination_url);
let initial_url = format!("http://{redirect_addr}/start");
cache_system_proxy_decision(&initial_url, SystemProxyDecision::Direct);
cache_system_proxy_decision(&destination_url, SystemProxyDecision::Direct);
let pool = crate::RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
);
let response = tokio::time::timeout(
Duration::from_secs(2),
pool.get(&initial_url)
.header(AUTHORIZATION, "Bearer origin-secret")
.header(COOKIE, "session=origin-secret")
.header(PROXY_AUTHORIZATION, "Basic proxy-secret")
.send(),
)
.await
.expect("redirected request should finish")
.expect("cross-origin redirect should succeed");
let initial_request = only_request(redirect_thread, "redirect");
let destination_request = only_request(destination_thread, "destination");
assert_eq!(response.url().as_str(), destination_url);
assert_eq!(
[
credential_headers(&initial_request),
credential_headers(&destination_request),
],
[(true, true, true), (false, false, false)]
);
}
#[tokio::test]
async fn route_aware_pool_retains_credentials_for_same_origin_and_route() {
let (proxy_addr, proxy_thread) = spawn_http_listener(vec![
"HTTP/1.1 302 Found\r\nLocation: /final\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
.to_string(),
"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_string(),
]);
let initial_url = "http://same-route.test/start";
let redirected_url = "http://same-route.test/final";
let route = SystemProxyDecision::Proxy {
url: format!("http://{proxy_addr}"),
};
cache_system_proxy_decision(initial_url, route.clone());
cache_system_proxy_decision(redirected_url, route);
let pool = crate::RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
);
let response = tokio::time::timeout(
Duration::from_secs(2),
pool.get(initial_url)
.header(AUTHORIZATION, "Bearer origin-secret")
.header(COOKIE, "session=origin-secret")
.header(PROXY_AUTHORIZATION, "Basic proxy-secret")
.send(),
)
.await
.expect("redirected request should finish")
.expect("same-route redirect should succeed");
let requests = proxy_thread.join().expect("proxy thread should finish");
assert_eq!(response.url().as_str(), redirected_url);
assert_eq!(
requests
.iter()
.map(|request| credential_headers(request))
.collect::<Vec<_>>(),
vec![(true, true, true), (true, true, true)]
);
}
#[tokio::test]
async fn route_aware_pool_sanitizes_redirected_failure_logs() {
const SUBPROCESS_ENV_VAR: &str = "CODEX_HTTP_CLIENT_REDIRECT_FAILURE_LOG_TEST";
if std::env::var_os(SUBPROCESS_ENV_VAR).is_none() {
// Bazel runs unit tests in one process. Isolate the tracing subscriber and callsite
// cache from other tests that install different subscribers while requests are in flight.
let test_module = module_path!()
.split_once("::")
.expect("test module should include the crate name")
.1;
let test_name =
format!("{test_module}::route_aware_pool_sanitizes_redirected_failure_logs");
let output = std::process::Command::new(
std::env::current_exe().expect("test executable should be available"),
)
.args(["--exact", &test_name, "--nocapture"])
.env(SUBPROCESS_ENV_VAR, "1")
.output()
.expect("logging test subprocess should finish");
assert!(
output.status.success(),
"logging test subprocess failed\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
return;
}
let log_buffer = Arc::new(Mutex::new(Vec::new()));
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(TestLogWriter {
buffer: Arc::clone(&log_buffer),
})
.with_filter(
tracing_subscriber::filter::Targets::new()
.with_target("codex_http_client", tracing::Level::TRACE),
),
);
let _guard = tracing::subscriber::set_default(subscriber);
tracing::debug!(target: "codex_http_client", "log capture sentinel");
let (enabled_failure_addr, enabled_failure_thread) = spawn_failing_listener();
let enabled_target_url =
format!("http://{enabled_failure_addr}/final?token=enabled-target-secret");
let (enabled_redirect_addr, enabled_redirect_thread) =
spawn_redirect_listener(&enabled_target_url);
let enabled_initial_url = format!("http://{enabled_redirect_addr}/start");
cache_system_proxy_decision(&enabled_initial_url, SystemProxyDecision::Direct);
cache_system_proxy_decision(&enabled_target_url, SystemProxyDecision::Direct);
let enabled_pool = crate::RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
);
let error = enabled_pool
.get(&enabled_initial_url)
.timeout(Duration::from_secs(2))
.send()
.await
.expect_err("redirect target should fail");
assert!(
matches!(error, crate::RouteAwareRequestError::Request(_)),
"expected a transport error from the redirect target, got {error:?}",
);
only_request(enabled_redirect_thread, "enabled redirect");
enabled_failure_thread
.join()
.expect("enabled failure thread should finish");
let (disabled_failure_addr, disabled_failure_thread) = spawn_failing_listener();
let disabled_target_url =
format!("http://{disabled_failure_addr}/final?token=disabled-target-secret");
let (disabled_redirect_addr, disabled_redirect_thread) =
spawn_redirect_listener(&disabled_target_url);
let disabled_initial_url = format!("http://{disabled_redirect_addr}/start");
cache_system_proxy_decision(&disabled_initial_url, SystemProxyDecision::Direct);
cache_system_proxy_decision(&disabled_target_url, SystemProxyDecision::Direct);
let disabled_pool = crate::RouteAwareClientPool::new_without_request_logging(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
);
disabled_pool
.get(&disabled_initial_url)
.timeout(Duration::from_secs(2))
.send()
.await
.expect_err("redirect target should fail");
only_request(disabled_redirect_thread, "disabled redirect");
disabled_failure_thread
.join()
.expect("disabled failure thread should finish");
let logs = String::from_utf8(log_buffer.lock().expect("log buffer lock").clone())
.expect("logs should be UTF-8");
assert!(logs.contains("log capture sentinel"));
assert!(
logs.contains(&enabled_initial_url),
"captured logs:\n{logs}"
);
assert!(!logs.contains(&disabled_initial_url));
assert_eq!(logs.matches("Request failed").count(), 1);
assert!(logs.contains("is_timeout"));
assert!(logs.contains("is_connect"));
for secret in [
"enabled-target-secret",
"disabled-target-secret",
enabled_target_url.as_str(),
disabled_target_url.as_str(),
"error=",
] {
assert!(!logs.contains(secret), "logs exposed {secret}:\n{logs}");
}
}
fn credential_headers(request: &str) -> (bool, bool, bool) {
let names = request
.lines()
.filter_map(|line| {
line.split_once(':')
.map(|(name, _)| name.to_ascii_lowercase())
})
.collect::<Vec<_>>();
(
names.iter().any(|name| name == "authorization"),
names.iter().any(|name| name == "cookie"),
names.iter().any(|name| name == "proxy-authorization"),
)
}
fn spawn_failing_listener() -> (std::net::SocketAddr, std::thread::JoinHandle<()>) {
let listener =
std::net::TcpListener::bind(("127.0.0.1", 0)).expect("failing listener should bind");
let address = listener
.local_addr()
.expect("failing listener should have an address");
listener
.set_nonblocking(true)
.expect("failing listener should become nonblocking");
let thread = std::thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(2);
let (mut stream, _) = loop {
match listener.accept() {
Ok(connection) => break connection,
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
assert!(
Instant::now() < deadline,
"failing listener should receive a request"
);
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => panic!("failing listener should accept: {error}"),
}
};
// Accepted sockets inherit the listener's nonblocking mode on macOS.
stream
.set_nonblocking(false)
.expect("failing stream should become blocking");
stream
.set_read_timeout(Some(Duration::from_secs(2)))
.expect("failing stream should get a read timeout");
read_http_message(&mut stream);
});
(address, thread)
}

View File

@@ -0,0 +1,714 @@
//! Shared outbound proxy policy tests.
use super::*;
use crate::HttpClientBuilder;
use http::HeaderMap;
use http::HeaderValue;
use http::header::AUTHORIZATION;
use http::header::COOKIE;
use http::header::PROXY_AUTHORIZATION;
use pretty_assertions::assert_eq;
use std::io::Read;
use std::io::Write;
use std::sync::Arc;
use std::sync::Mutex;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::SubscriberExt;
#[path = "outbound_proxy_redirect_coverage_tests.rs"]
mod redirect_coverage_tests;
struct MapEnv {
values: HashMap<String, String>,
}
fn spawn_proxy_listener() -> (std::net::SocketAddr, std::thread::JoinHandle<Vec<String>>) {
spawn_http_listener(vec![
"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_string(),
])
}
fn spawn_redirect_listener(
location: &str,
) -> (std::net::SocketAddr, std::thread::JoinHandle<Vec<String>>) {
spawn_http_listener(vec![format!(
"HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
)])
}
fn spawn_http_listener(
responses: Vec<String>,
) -> (std::net::SocketAddr, std::thread::JoinHandle<Vec<String>>) {
let listener =
std::net::TcpListener::bind(("127.0.0.1", 0)).expect("HTTP listener should bind");
let address = listener
.local_addr()
.expect("HTTP listener should have an address");
listener
.set_nonblocking(true)
.expect("HTTP listener should become nonblocking");
let thread = std::thread::spawn(move || {
let mut requests = Vec::new();
for response in responses {
let deadline = Instant::now() + Duration::from_secs(10);
let (mut stream, _) = loop {
match listener.accept() {
Ok(connection) => break connection,
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
assert!(
Instant::now() < deadline,
"HTTP listener should receive the next request"
);
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => panic!("HTTP listener should accept: {error}"),
}
};
stream
.set_nonblocking(false)
.expect("HTTP stream should become blocking");
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.expect("HTTP stream should get a read timeout");
requests.push(read_http_message(&mut stream));
stream
.write_all(response.as_bytes())
.expect("HTTP listener should write response");
}
requests
});
(address, thread)
}
fn only_request(thread: std::thread::JoinHandle<Vec<String>>, source: &str) -> String {
let requests = thread
.join()
.unwrap_or_else(|_| panic!("{source} thread should finish"));
let [request]: [String; 1] = requests.try_into().unwrap_or_else(|requests: Vec<String>| {
panic!(
"{source} should receive one request, got {}",
requests.len()
)
});
request
}
fn read_http_message(stream: &mut impl Read) -> String {
let mut buffer = Vec::new();
let mut chunk = [0_u8; 1024];
loop {
let bytes_read = stream.read(&mut chunk).expect("HTTP message should read");
if bytes_read == 0 {
break;
}
buffer.extend_from_slice(&chunk[..bytes_read]);
if let Some(header_end) = buffer.windows(4).position(|window| window == b"\r\n\r\n") {
let body_start = header_end + 4;
let headers = String::from_utf8_lossy(&buffer[..body_start]);
let content_length = headers
.lines()
.filter_map(|line| line.split_once(':'))
.find_map(|(name, value)| {
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse::<usize>().ok())
.flatten()
})
.unwrap_or(0);
if buffer.len() >= body_start + content_length {
break;
}
}
}
String::from_utf8_lossy(&buffer).into_owned()
}
#[test]
fn cloned_factories_share_chatgpt_cookie_stores_without_changing_value_equality() {
let factory =
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault).with_chatgpt_cookies([
HeaderValue::from_static("first=true"),
HeaderValue::from_static("second=true"),
]);
let cloned = factory.clone();
assert!(Arc::ptr_eq(
&factory.chatgpt_cookie_store().expect("configured store"),
&cloned.chatgpt_cookie_store().expect("shared store"),
));
assert_eq!(
factory,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault).with_chatgpt_cookies([
HeaderValue::from_static("first=true"),
HeaderValue::from_static("second=true"),
])
);
}
#[test]
fn websocket_route_uses_http_equivalent_for_system_resolution() {
let env = MapEnv {
values: HashMap::new(),
};
let route = resolve_proxy_route(
&env,
"wss://api.openai.com/v1/responses",
OutboundProxyPolicy::RespectSystemProxy,
|request_url, origin| {
assert_eq!(request_url, "https://api.openai.com/v1/responses");
assert_eq!(origin.scheme, "https");
assert_eq!(origin.host, "api.openai.com");
assert_eq!(origin.port, 443);
SystemProxyDecision::Proxy {
url: "http://proxy.example:8080".to_string(),
}
},
);
assert_eq!(
route,
OutboundProxyRoute::Proxy {
url: "http://proxy.example:8080".to_string(),
no_proxy: None,
}
);
}
#[test]
fn reqwest_default_route_preserves_transport_proxy_behavior() {
let env = MapEnv {
values: HashMap::new(),
};
let route = resolve_proxy_route(
&env,
"wss://api.openai.com/v1/responses",
OutboundProxyPolicy::ReqwestDefault,
|_, _| panic!("default policy should not resolve system proxy settings"),
);
assert_eq!(route, OutboundProxyRoute::TransportDefault);
}
#[cfg(target_os = "macos")]
#[test]
fn macos_proxy_configuration_rejects_invalid_destination() {
assert_eq!(
macos_system_proxy_configuration("not a valid destination"),
MacosSystemProxyConfiguration::Unavailable
);
}
impl EnvSource for MapEnv {
fn var(&self, key: &str) -> Option<String> {
self.values.get(key).cloned()
}
}
#[test]
fn proxy_env_value_matches_reqwest_casing_precedence() {
let env = MapEnv {
values: HashMap::from([
("HTTPS_PROXY".to_string(), "upper".to_string()),
("https_proxy".to_string(), "lower".to_string()),
("http_proxy".to_string(), "lower-only".to_string()),
("ALL_PROXY".to_string(), String::new()),
("all_proxy".to_string(), "masked".to_string()),
]),
};
assert_eq!(
proxy_env_value(&env, "HTTPS_PROXY"),
Some("upper".to_string())
);
assert_eq!(
proxy_env_value(&env, "HTTP_PROXY"),
Some("lower-only".to_string())
);
assert_eq!(proxy_env_value(&env, "ALL_PROXY"), None);
}
#[test]
fn environment_fallback_reads_injected_proxy_environment() {
let env = MapEnv {
values: HashMap::from([("HTTPS_PROXY".to_string(), "://invalid".to_string())]),
};
let route = resolve_env_proxy_route(&env, EnvProxyKind::Https);
let result = configure_builder_for_resolved_route(
reqwest::Client::builder(),
ClientRouteClass::Auth,
&route,
);
assert!(matches!(
result,
Err(BuildRouteAwareHttpClientError::InvalidProxyConfig {
route_class: ClientRouteClass::Auth,
})
));
}
#[test]
fn unavailable_system_route_resolves_environment_or_direct_explicitly() {
let env = MapEnv {
values: HashMap::from([
(
"HTTPS_PROXY".to_string(),
"http://proxy.example:8080".to_string(),
),
("NO_PROXY".to_string(), "localhost,.internal".to_string()),
]),
};
assert_eq!(
route_from_system_decision(
&env,
EnvProxyKind::Https,
SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
},
),
OutboundProxyRoute::Proxy {
url: "http://proxy.example:8080".to_string(),
no_proxy: Some("localhost,.internal".to_string()),
}
);
assert_eq!(
route_from_system_decision(
&MapEnv {
values: HashMap::new(),
},
EnvProxyKind::Https,
SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
},
),
OutboundProxyRoute::Direct
);
}
#[test]
fn unavailable_system_route_preserves_wss_http_proxy_fallback() {
let env = MapEnv {
values: HashMap::from([(
"HTTP_PROXY".to_string(),
"http://proxy.example:8080".to_string(),
)]),
};
let route = resolve_proxy_route(
&env,
"wss://api.openai.com/v1/responses",
OutboundProxyPolicy::RespectSystemProxy,
|_, _| SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
},
);
assert_eq!(
route,
OutboundProxyRoute::Proxy {
url: "http://proxy.example:8080".to_string(),
no_proxy: None,
}
);
}
#[cfg(any(target_os = "windows", target_os = "macos"))]
#[tokio::test]
async fn async_resolution_uses_cached_route_before_global_permit() {
let request_url = "https://cached-fast-path.test/request";
cache_system_proxy_decision(request_url, SystemProxyDecision::Direct);
let factory = HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy);
let permit = ASYNC_SYSTEM_PROXY_RESOLUTION_PERMIT
.acquire()
.await
.expect("global proxy permit should stay open");
let route = tokio::time::timeout(Duration::from_secs(2), async {
loop {
// A concurrent cache writer may cause a miss. Drop that attempt before retrying
// so it does not wait for the permit deliberately held by this test.
if let Some(route) = futures::FutureExt::now_or_never(
factory.resolve_proxy_route_async(request_url.to_string()),
) {
break route;
}
tokio::task::yield_now().await;
}
})
.await
.expect("cached resolution should not wait for the global permit")
.expect("cached route should resolve");
drop(permit);
assert_eq!(route, OutboundProxyRoute::Direct);
}
#[cfg(any(target_os = "windows", target_os = "macos"))]
#[tokio::test(flavor = "current_thread")]
async fn async_resolution_yields_while_cache_is_locked() {
let request_url = "https://contended-cache.test/request";
let permit = ASYNC_SYSTEM_PROXY_RESOLUTION_PERMIT
.acquire()
.await
.expect("global proxy permit should stay open");
cache_system_proxy_decision(request_url, SystemProxyDecision::Direct);
let (locked_tx, locked_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let holder = std::thread::spawn(move || {
let cache = SYSTEM_PROXY_CACHE.get().expect("initialized proxy cache");
let guard = cache.lock().expect("proxy cache should not be poisoned");
locked_tx.send(()).expect("test should still be running");
// Bound a blocking regression without using elapsed time as the assertion.
let released = release_rx.recv_timeout(Duration::from_secs(5));
drop(guard);
released
});
locked_rx.await.expect("cache holder should start");
let factory = HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy);
let resolution = factory.resolve_proxy_route_async(request_url.to_string());
tokio::pin!(resolution);
let yielded = std::future::poll_fn(|cx| {
std::task::Poll::Ready(std::future::Future::poll(resolution.as_mut(), cx).is_pending())
})
.await;
let released = release_tx.send(());
let holder_result = holder.join().expect("cache holder should finish");
drop(permit);
assert!(yielded, "resolution should yield while the cache is locked");
released.expect("resolution must yield before the holder's deadline");
holder_result.expect("test should release the cache holder");
let route = tokio::time::timeout(Duration::from_secs(2), resolution)
.await
.expect("resolution should finish after releasing the cache")
.expect("cached route should resolve");
assert_eq!(route, OutboundProxyRoute::Direct);
}
#[tokio::test]
async fn enabled_environment_proxy_routes_request_through_proxy() {
let (proxy_addr, proxy_thread) = spawn_proxy_listener();
let env = MapEnv {
values: HashMap::from([("HTTP_PROXY".to_string(), format!("http://{proxy_addr}"))]),
};
let request_url = "http://enabled-proxy.test/proxy-check";
let builder = configure_proxy_for_route(
&env,
reqwest::Client::builder().timeout(Duration::from_secs(2)),
request_url,
ClientRouteClass::Auth,
OutboundProxyPolicy::RespectSystemProxy,
|_, _| SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
},
)
.expect("enabled proxy route should configure");
let response = builder
.build()
.expect("proxy client should build")
.get(request_url)
.send()
.await
.expect("request should use local proxy");
let proxy_request = only_request(proxy_thread, "proxy");
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
proxy_request.lines().next(),
Some("GET http://enabled-proxy.test/proxy-check HTTP/1.1")
);
}
#[tokio::test]
async fn route_aware_builder_preserves_default_headers() {
let (server_addr, server_thread) = spawn_proxy_listener();
let request_url = format!("http://{server_addr}/builder-check");
cache_system_proxy_decision(&request_url, SystemProxyDecision::Direct);
let mut headers = HeaderMap::new();
headers.insert("x-builder-test", HeaderValue::from_static("preserved"));
let factory = HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy);
let client = HttpClientBuilder::new()
.default_headers(headers)
.build_respecting_outbound_proxy_policy(&factory, &request_url, ClientRouteClass::Api)
.expect("route-aware client should build");
let response = client
.get(&request_url)
.send()
.await
.expect("request should use direct route");
let request = only_request(server_thread, "server");
assert!(response.status().is_success());
assert!(
request
.lines()
.any(|line| line.eq_ignore_ascii_case("x-builder-test: preserved"))
);
}
#[tokio::test]
async fn route_aware_pool_uses_respect_system_proxy_route_for_exact_url() {
let (proxy_addr, proxy_thread) = spawn_proxy_listener();
let request_url = "http://route-aware-proxy.test/proxy-check?pac=exact";
cache_system_proxy_decision(
request_url,
SystemProxyDecision::Proxy {
url: format!("http://{proxy_addr}"),
},
);
let pool = crate::RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
);
let response = tokio::time::timeout(Duration::from_secs(2), pool.get(request_url).send())
.await
.expect("proxy request should finish")
.expect("request should use local proxy");
let proxy_request = only_request(proxy_thread, "proxy");
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
proxy_request.lines().next(),
Some("GET http://route-aware-proxy.test/proxy-check?pac=exact HTTP/1.1")
);
}
#[tokio::test]
async fn route_aware_pool_logs_only_the_final_redirect_outcome() {
let (proxy_addr, proxy_thread) = spawn_proxy_listener();
let redirected_url = "http://redirect-target.test/final?token=redirect-target-secret-value";
let (redirect_addr, redirect_thread) = spawn_redirect_listener(redirected_url);
let initial_url = format!("http://{redirect_addr}/start");
cache_system_proxy_decision(&initial_url, SystemProxyDecision::Direct);
cache_system_proxy_decision(
redirected_url,
SystemProxyDecision::Proxy {
url: format!("http://{proxy_addr}"),
},
);
let pool = crate::RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
);
let log_buffer = Arc::new(Mutex::new(Vec::new()));
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(TestLogWriter {
buffer: Arc::clone(&log_buffer),
})
.with_filter(
tracing_subscriber::filter::Targets::new()
.with_target("codex_http_client", tracing::Level::TRACE),
),
);
let _guard = tracing::subscriber::set_default(subscriber);
tracing::debug!(target: "codex_http_client", "log capture sentinel");
let response = tokio::time::timeout(Duration::from_secs(2), pool.get(&initial_url).send())
.await
.expect("redirected request should finish")
.expect("redirected request should use selected routes");
only_request(redirect_thread, "redirect");
only_request(proxy_thread, "proxy");
assert_eq!(response.status(), reqwest::StatusCode::OK);
let logs = String::from_utf8(log_buffer.lock().expect("log buffer lock").clone())
.expect("logs should be UTF-8");
assert!(logs.contains("log capture sentinel"));
assert!(logs.contains(&initial_url));
assert_eq!(logs.matches("Request completed").count(), 1);
for secret in ["redirect-target-secret-value", redirected_url, "location"] {
assert!(
!logs
.to_ascii_lowercase()
.contains(&secret.to_ascii_lowercase())
);
}
}
#[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 unavailable_system_proxy_decision_is_cached() {
let request_url = "https://unavailable-cache.test/oauth/token";
let decision = SystemProxyDecision::Unavailable {
failure: RouteFailureClass::ProxyResolutionUnavailable,
};
let mut cache = HashMap::new();
let cache_key = system_proxy_cache_key(request_url);
let now = Instant::now();
insert_system_proxy_cache_entry(&mut cache, &cache_key, decision.clone(), now);
assert_eq!(
cached_system_proxy_decision_from_cache(&mut cache, &cache_key, now),
Some(decision)
);
}
#[derive(Clone)]
struct TestLogWriter {
buffer: Arc<Mutex<Vec<u8>>>,
}
struct TestLogSink {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TestLogWriter {
type Writer = TestLogSink;
fn make_writer(&'a self) -> Self::Writer {
TestLogSink {
buffer: Arc::clone(&self.buffer),
}
}
}
impl Write for TestLogSink {
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
let mut log_buffer = self
.buffer
.lock()
.map_err(|_| io::Error::other("log buffer lock was poisoned"))?;
log_buffer.extend(buffer);
Ok(buffer.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn system_proxy_resolution_is_single_flight() {
let cache = Arc::new(Mutex::new(HashMap::new()));
let request_url = "https://single-flight.test/models";
let origin = RequestOrigin::parse(request_url).expect("valid request URL");
let (started_tx, started_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let worker_cache = Arc::clone(&cache);
let worker_origin = origin.clone();
let worker = std::thread::spawn(move || {
resolve_system_proxy_with(&worker_cache, request_url, &worker_origin, |_, _| {
started_tx.send(()).expect("test should still be running");
release_rx.recv().expect("test should release resolver");
SystemProxyDecision::Direct
})
});
started_rx.recv().expect("resolver should start");
assert!(matches!(
cache.try_lock(),
Err(std::sync::TryLockError::WouldBlock)
));
release_tx
.send(())
.expect("resolver should still be running");
assert_eq!(
worker.join().expect("resolver should finish"),
SystemProxyDecision::Direct
);
assert_eq!(
resolve_system_proxy_with(&cache, request_url, &origin, |_, _| {
panic!("cached waiter should not resolve the platform proxy again")
}),
SystemProxyDecision::Direct
);
}
#[test]
fn system_proxy_cache_is_bounded() {
let mut cache = HashMap::new();
let now = Instant::now();
for index in 0..=SYSTEM_PROXY_CACHE_MAX_ENTRIES {
insert_system_proxy_cache_entry(
&mut cache,
&format!("https://bounded-cache.test/{index}"),
SystemProxyDecision::Direct,
now,
);
}
assert_eq!(cache.len(), SYSTEM_PROXY_CACHE_MAX_ENTRIES);
}
#[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("http=web-proxy:8080 https=secure-proxy:8443", "https"),
ParsedProxyListDecision::Proxy("http://secure-proxy:8443".to_string())
);
assert_eq!(
parse_proxy_list("http=web-proxy:8080", "https"),
ParsedProxyListDecision::Unavailable
);
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("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("*.openai.com", &origin));
assert!(no_proxy_matches_origin("auth.openai.com:443", &origin));
assert!(!no_proxy_matches_origin("auth.openai.com:8443", &origin));
}
#[test]
fn system_proxy_cache_key_preserves_url_specific_pac_decisions() {
let request_url = "https://auth.openai.com/oauth/token?access_token=secret";
let cache_key = system_proxy_cache_key(request_url);
assert_ne!(
cache_key,
system_proxy_cache_key("https://auth.openai.com/oauth/revoke")
);
assert!(!cache_key.contains(request_url));
}

View File

@@ -0,0 +1,333 @@
use bytes::Bytes;
use http::HeaderMap;
use http::HeaderValue;
use http::Method;
use serde::Serialize;
use serde_json::Value;
use std::time::Duration;
/// A JSON request body serialized once into reference-counted bytes.
///
/// Clones share the encoded allocation. Internally, the body can also hold the
/// final compressed wire bytes while retaining the original JSON only when
/// request-body trace logging is enabled.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncodedJsonBody {
bytes: Bytes,
trace_bytes: Option<Bytes>,
prepared: bool,
}
impl EncodedJsonBody {
/// Serializes `value` into a reusable JSON body.
pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Self, serde_json::Error> {
serde_json::to_vec(value).map(|bytes| Self {
bytes: Bytes::from(bytes),
trace_bytes: None,
prepared: false,
})
}
/// Returns the encoded bytes currently stored by this body.
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub(crate) fn trace_bytes(&self) -> &[u8] {
self.trace_bytes.as_ref().unwrap_or(&self.bytes)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RequestCompression {
#[default]
None,
Zstd,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RequestBody {
Json(Value),
EncodedJson(EncodedJsonBody),
Raw(Bytes),
}
impl RequestBody {
pub fn json(&self) -> Option<&Value> {
match self {
Self::Json(value) => Some(value),
Self::EncodedJson(_) | Self::Raw(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedRequestBody {
pub headers: HeaderMap,
pub body: Option<Bytes>,
}
impl PreparedRequestBody {
pub fn body_bytes(&self) -> Bytes {
self.body.clone().unwrap_or_default()
}
}
#[derive(Debug, Clone)]
pub struct Request {
pub method: Method,
pub url: String,
pub headers: HeaderMap,
pub body: Option<RequestBody>,
pub compression: RequestCompression,
pub timeout: Option<Duration>,
/// Maximum accepted response-body bytes, including streaming and error bodies.
/// `None` leaves the response unbounded.
pub response_body_limit_bytes: Option<usize>,
}
impl Request {
pub fn new(method: Method, url: String) -> Self {
Self {
method,
url,
headers: HeaderMap::new(),
body: None,
compression: RequestCompression::None,
timeout: None,
response_body_limit_bytes: None,
}
}
pub fn with_json<T: Serialize>(mut self, body: &T) -> Self {
self.body = serde_json::to_value(body).ok().map(RequestBody::Json);
self
}
pub fn with_raw_body(mut self, body: impl Into<Bytes>) -> Self {
self.body = Some(RequestBody::Raw(body.into()));
self
}
pub fn with_compression(mut self, compression: RequestCompression) -> Self {
self.compression = compression;
self
}
/// Prepares the body once and stores the exact bytes that will be sent.
///
/// Cloning the returned request shares the body bytes, so retry attempts do
/// not repeat JSON serialization or compression. Request-signing auth also
/// sees the same final headers and bytes that the transport will send.
pub fn into_prepared(mut self) -> Result<Self, String> {
let is_json = matches!(
self.body,
Some(RequestBody::Json(_) | RequestBody::EncodedJson(_))
);
let trace_bytes = if self.compression != RequestCompression::None
&& tracing::enabled!(target: "codex_http_client::transport", tracing::Level::TRACE)
{
match self.body.as_ref() {
Some(RequestBody::Json(body)) => Some(Bytes::from(
serde_json::to_vec(body).map_err(|err| err.to_string())?,
)),
Some(RequestBody::EncodedJson(body)) => Some(body.bytes.clone()),
Some(RequestBody::Raw(_)) | None => None,
}
} else {
None
};
let prepared = self.prepare_body_for_send()?;
self.headers = prepared.headers;
self.body = match (is_json, prepared.body) {
(true, Some(bytes)) => Some(RequestBody::EncodedJson(EncodedJsonBody {
bytes,
trace_bytes,
prepared: true,
})),
(false, Some(body)) => Some(RequestBody::Raw(body)),
(_, None) => None,
};
self.compression = RequestCompression::None;
Ok(self)
}
/// Convert the request body into the exact bytes that will be sent.
///
/// Auth schemes such as AWS SigV4 need to sign the final body bytes, including
/// compression and content headers. Calling this method does not mutate the
/// request.
pub fn prepare_body_for_send(&self) -> Result<PreparedRequestBody, String> {
let headers = self.headers.clone();
match self.body.as_ref() {
Some(RequestBody::Raw(raw_body)) => {
if self.compression != RequestCompression::None {
return Err("request compression cannot be used with raw bodies".to_string());
}
Ok(PreparedRequestBody {
headers,
body: Some(raw_body.clone()),
})
}
Some(RequestBody::Json(body)) => {
let body = EncodedJsonBody::encode(body).map_err(|err| err.to_string())?;
self.prepare_encoded_json(headers, &body)
}
Some(RequestBody::EncodedJson(body)) => self.prepare_encoded_json(headers, body),
None => Ok(PreparedRequestBody {
headers,
body: None,
}),
}
}
fn prepare_encoded_json(
&self,
mut headers: HeaderMap,
body: &EncodedJsonBody,
) -> Result<PreparedRequestBody, String> {
if body.prepared {
return Ok(PreparedRequestBody {
headers,
body: Some(body.bytes.clone()),
});
}
let bytes = if self.compression != RequestCompression::None {
if headers.contains_key(http::header::CONTENT_ENCODING) {
return Err(
"request compression was requested but content-encoding is already set"
.to_string(),
);
}
let pre_compression_bytes = body.bytes.len();
let compression_start = std::time::Instant::now();
let (compressed, content_encoding) = match self.compression {
RequestCompression::None => unreachable!("guarded by compression != None"),
RequestCompression::Zstd => (
zstd::stream::encode_all(std::io::Cursor::new(body.as_bytes()), 3)
.map_err(|err| err.to_string())?,
HeaderValue::from_static("zstd"),
),
};
let post_compression_bytes = compressed.len();
let compression_duration = compression_start.elapsed();
headers.insert(http::header::CONTENT_ENCODING, content_encoding);
tracing::debug!(
pre_compression_bytes,
post_compression_bytes,
compression_duration_ms = compression_duration.as_millis(),
"Compressed request body with zstd"
);
Bytes::from(compressed)
} else {
body.bytes.clone()
};
if !headers.contains_key(http::header::CONTENT_TYPE) {
headers.insert(
http::header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
}
Ok(PreparedRequestBody {
headers,
body: Some(bytes),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use http::HeaderValue;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn prepare_body_for_send_serializes_json_and_sets_content_type() {
let request = Request::new(Method::POST, "https://example.com/v1/responses".to_string())
.with_json(&json!({"model": "test-model"}));
let prepared = request
.prepare_body_for_send()
.expect("body should prepare");
assert_eq!(
prepared.body,
Some(Bytes::from_static(br#"{"model":"test-model"}"#))
);
assert_eq!(
prepared
.headers
.get(http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok()),
Some("application/json")
);
assert_eq!(
request.body,
Some(RequestBody::Json(json!({"model": "test-model"})))
);
assert_eq!(request.compression, RequestCompression::None);
}
#[test]
fn prepare_body_for_send_rejects_existing_content_encoding_when_compressing() {
let mut request =
Request::new(Method::POST, "https://example.com/v1/responses".to_string())
.with_json(&json!({"model": "test-model"}))
.with_compression(RequestCompression::Zstd);
request.headers.insert(
http::header::CONTENT_ENCODING,
HeaderValue::from_static("gzip"),
);
let err = request
.prepare_body_for_send()
.expect_err("conflicting content-encoding should fail");
assert_eq!(
err,
"request compression was requested but content-encoding is already set"
);
}
#[test]
fn into_prepared_stores_compressed_body_for_reuse() {
let body =
EncodedJsonBody::encode(&json!({"model": "test-model"})).expect("JSON should encode");
let mut request =
Request::new(Method::POST, "https://example.com/v1/responses".to_string())
.with_compression(RequestCompression::Zstd);
request.body = Some(RequestBody::EncodedJson(body));
let request = request.into_prepared().expect("body should prepare");
let Some(RequestBody::EncodedJson(body)) = request.body.as_ref() else {
panic!("expected an encoded JSON body");
};
let decompressed = zstd::stream::decode_all(std::io::Cursor::new(body.as_bytes()))
.expect("body should decompress");
assert_eq!(decompressed, br#"{"model":"test-model"}"#);
assert_eq!(request.compression, RequestCompression::None);
assert_eq!(
request.headers.get(http::header::CONTENT_ENCODING),
Some(&HeaderValue::from_static("zstd"))
);
assert_eq!(
request.headers.get(http::header::CONTENT_TYPE),
Some(&HeaderValue::from_static("application/json"))
);
}
}
#[derive(Debug, Clone)]
pub struct Response {
pub status: http::StatusCode,
pub headers: HeaderMap,
pub body: Bytes,
}

View File

@@ -0,0 +1,193 @@
//! Builds direct and routed requests without constructing a second transport client.
//! Routed requests select their transport only when sent; debug output redacts their URLs.
use bytes::Bytes;
use futures::TryStream;
use http::HeaderMap;
use http::HeaderName;
use http::HeaderValue;
use http::Method;
use http::header::AUTHORIZATION;
use http::header::CONTENT_TYPE;
use reqwest::IntoUrl;
use serde::Serialize;
use std::fmt;
use std::fmt::Display;
use std::sync::Arc;
use std::time::Duration;
use crate::HttpError;
use crate::HttpResponse;
use crate::RouteAwareClientPool;
use crate::client::HttpClientBackend;
use crate::client::TransportClient;
use crate::request_draft::HeaderUpdate;
use crate::request_draft::RequestDraft;
#[must_use = "requests are not sent unless `send` is awaited"]
pub struct RequestBuilder {
backend: HttpClientBackend,
request: Result<RequestDraft, HttpError>,
}
impl fmt::Debug for RequestBuilder {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RequestBuilder")
.field(
"method",
&self
.request
.as_ref()
.ok()
.map(|request| request.request.method()),
)
.field("url", &"<redacted>")
.finish_non_exhaustive()
}
}
impl RequestBuilder {
pub(crate) fn direct<U: IntoUrl>(client: &TransportClient, method: Method, url: U) -> Self {
Self {
backend: HttpClientBackend::Direct(client.clone()),
request: RequestDraft::new(method, url).map_err(HttpError::Request),
}
}
pub(crate) fn routed<U: IntoUrl>(
pool: Arc<RouteAwareClientPool>,
method: Method,
url: U,
) -> Self {
Self {
backend: HttpClientBackend::Routed(pool),
request: RequestDraft::new(method, url).map_err(HttpError::Request),
}
}
fn map(mut self, update: impl FnOnce(&mut RequestDraft) -> Result<(), HttpError>) -> Self {
self.request = self.request.and_then(|mut request| {
update(&mut request)?;
Ok(request)
});
self
}
pub fn headers(self, headers: HeaderMap) -> Self {
self.map(|request| {
request.extend_headers(headers);
Ok(())
})
}
pub fn header<K, V>(self, key: K, value: V) -> Self
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<http::Error>,
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
{
self.map(|request| {
let key = HeaderName::try_from(key)
.map_err(Into::into)
.map_err(|error: http::Error| HttpError::Build(error.to_string()))?;
let value = HeaderValue::try_from(value)
.map_err(Into::into)
.map_err(|error: http::Error| HttpError::Build(error.to_string()))?;
request.headers.push(HeaderUpdate::Append(key, value));
Ok(())
})
}
pub fn bearer_auth<T: Display>(self, token: T) -> Self {
self.map(|request| {
let mut value = HeaderValue::from_str(&format!("Bearer {token}"))
.map_err(|error| HttpError::Build(error.to_string()))?;
value.set_sensitive(true);
request
.headers
.push(HeaderUpdate::Append(AUTHORIZATION, value));
Ok(())
})
}
/// Bounds route selection, connection establishment, and the response headers.
/// Use [`crate::HttpClientBuilder::connect_timeout`] to bound only connection establishment.
pub fn timeout(self, timeout: Duration) -> Self {
self.map(|request| {
*request.request.timeout_mut() = Some(timeout);
Ok(())
})
}
pub fn version(self, version: http::Version) -> Self {
self.map(|request| {
*request.request.version_mut() = version;
Ok(())
})
}
pub fn json<T: ?Sized + Serialize>(self, value: &T) -> Self {
self.map(|request| {
let body =
serde_json::to_vec(value).map_err(|error| HttpError::Build(error.to_string()))?;
let has_content_type = request.headers.iter().any(|update| match update {
HeaderUpdate::Replace(headers) => headers.contains_key(CONTENT_TYPE),
HeaderUpdate::Append(name, _) => *name == CONTENT_TYPE,
});
if !has_content_type {
request.headers.push(HeaderUpdate::Append(
CONTENT_TYPE,
HeaderValue::from_static("application/json"),
));
}
*request.request.body_mut() = Some(body.into());
Ok(())
})
}
pub fn query<T: ?Sized + Serialize>(self, query: &T) -> Self {
self.map(|request| {
query
.serialize(serde_urlencoded::Serializer::new(
&mut request.request.url_mut().query_pairs_mut(),
))
.map_err(|error| HttpError::Build(error.to_string()))?;
if request.request.url().query() == Some("") {
request.request.url_mut().set_query(None);
}
Ok(())
})
}
pub fn body<B: Into<reqwest::Body>>(self, body: B) -> Self {
self.map(|request| {
*request.request.body_mut() = Some(body.into());
Ok(())
})
}
/// Sets a streaming body without exposing the underlying HTTP implementation.
pub fn body_stream<S>(self, stream: S) -> Self
where
S: TryStream + Send + 'static,
S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
Bytes: From<S::Ok>,
{
self.body(reqwest::Body::wrap_stream(stream))
}
pub async fn send(self) -> Result<HttpResponse, HttpError> {
match self.backend {
HttpClientBackend::Routed(pool) => pool.send(self.request?).await,
HttpClientBackend::Direct(client) => {
Ok(client.execute(self.request?.build(&client)?).await?.into())
}
}
}
}
#[cfg(test)]
#[path = "request_builder_tests.rs"]
mod tests;

View File

@@ -0,0 +1,117 @@
use super::*;
use crate::ClientRouteClass;
use crate::HttpClientBuilder;
use crate::HttpClientFactory;
use crate::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
#[test]
fn request_draft_preserves_reqwest_url_auth_and_header_precedence() {
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
);
let client = HttpClientBuilder::new()
.build_direct()
.expect("client should build");
let HttpClientBackend::Direct(transport) = &client.backend else {
panic!("client should use direct transport");
};
let reqwest = &transport.inner;
for url in [
"https://example.com/path",
"https://user:p%40ss@example.com/path",
"https://:%E2%98%83@example.com/path",
"https://%FF:password@example.com/path",
] {
let headers = HeaderMap::from_iter([
(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer replacement"),
),
(
CONTENT_TYPE,
HeaderValue::from_static("application/custom+json"),
),
]);
for (actual, expected) in [
(pool.post(url), reqwest.post(url)),
(
pool.post(url)
.header(http::header::AUTHORIZATION, "Bearer appended"),
reqwest
.post(url)
.header(http::header::AUTHORIZATION, "Bearer appended"),
),
(
pool.post(url)
.header(http::header::AUTHORIZATION, "Bearer first")
.headers(headers.clone())
.header(http::header::AUTHORIZATION, "Bearer last"),
reqwest
.post(url)
.header(http::header::AUTHORIZATION, "Bearer first")
.headers(headers)
.header(http::header::AUTHORIZATION, "Bearer last"),
),
(
pool.post(url)
.header(CONTENT_TYPE, "application/custom+json")
.headers(HeaderMap::new()),
reqwest
.post(url)
.header(CONTENT_TYPE, "application/custom+json")
.headers(HeaderMap::new()),
),
(
pool.post(url).json(&serde_json::json!({"previous": true})),
reqwest
.post(url)
.json(&serde_json::json!({"previous": true})),
),
] {
let body = serde_json::json!({"query": "test"});
let timeout = Duration::from_secs(7);
let actual = actual
.json(&body)
.timeout(timeout)
.request
.expect("request inputs should be valid")
.build(transport)
.expect("request should build");
let expected = expected
.json(&body)
.timeout(timeout)
.build()
.expect("reqwest should build");
assert_eq!(
(
actual.url(),
actual.method(),
actual.headers(),
actual.body().and_then(reqwest::Body::as_bytes),
actual.timeout()
),
(
expected.url(),
expected.method(),
expected.headers(),
expected.body().and_then(reqwest::Body::as_bytes),
expected.timeout()
),
);
assert_eq!(
actual
.headers()
.values()
.map(HeaderValue::is_sensitive)
.collect::<Vec<_>>(),
expected
.headers()
.values()
.map(HeaderValue::is_sensitive)
.collect::<Vec<_>>(),
);
}
}
}

View File

@@ -0,0 +1,67 @@
//! Request drafts shared by fixed clients and route-aware pools.
//!
//! Replay header operations in order so reqwest owns URL authentication and header precedence.
//! Header operations are the sole header state until build; the draft's request holds no headers.
//! Redirects and TLS retries use the resulting request without repeating this construction.
use http::HeaderMap;
use http::HeaderName;
use http::HeaderValue;
use http::Method;
use reqwest::IntoUrl;
use crate::client::TransportClient;
/// Request inputs awaiting construction through reqwest with a selected HTTP client.
///
/// Route-aware pools select a client for the destination before calling [`Self::build`]; fixed
/// transports use their existing client. Building applies URL authentication and the queued header
/// operations once, then redirects and TLS retries reuse the resulting request.
pub(crate) struct RequestDraft {
pub(crate) request: reqwest::Request,
pub(crate) headers: Vec<HeaderUpdate>,
}
pub(crate) enum HeaderUpdate {
Replace(HeaderMap),
Append(HeaderName, HeaderValue),
}
impl From<reqwest::Request> for RequestDraft {
fn from(mut request: reqwest::Request) -> Self {
let headers = vec![HeaderUpdate::Replace(std::mem::take(request.headers_mut()))];
Self { request, headers }
}
}
impl RequestDraft {
pub(crate) fn new<U: IntoUrl>(method: Method, url: U) -> Result<Self, reqwest::Error> {
url.into_url()
.map(|url| Self::from(reqwest::Request::new(method, url)))
}
pub(crate) fn extend_headers(&mut self, headers: HeaderMap) {
self.headers.push(HeaderUpdate::Replace(headers));
}
pub(crate) fn build(
self,
client: &TransportClient,
) -> Result<reqwest::Request, reqwest::Error> {
let mut request = self.request;
let mut builder = client
.inner
.request(request.method().clone(), request.url().clone());
for update in self.headers {
builder = match update {
HeaderUpdate::Replace(headers) => builder.headers(headers),
HeaderUpdate::Append(name, value) => builder.header(name, value),
};
}
let mut built = builder.build()?;
*built.body_mut() = request.body_mut().take();
*built.timeout_mut() = request.timeout().copied();
*built.version_mut() = request.version();
Ok(built)
}
}

View File

@@ -0,0 +1,147 @@
//! HTTP responses retain application authorization while their bodies are consumed.
use std::ops::Deref;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use bytes::Bytes;
use futures::FutureExt;
use futures::Stream;
use futures::StreamExt;
use futures::future::BoxFuture;
use futures::stream;
use serde::de::DeserializeOwned;
use crate::HttpError;
use crate::NetworkPermit;
use crate::NetworkPolicy;
#[derive(Debug)]
pub struct HttpResponse {
inner: reqwest::Response,
permit: NetworkPermit,
}
impl HttpResponse {
/// Preserves HTTP frames, including gRPC trailers, while enforcing revocation.
pub fn into_http_response(
self,
) -> http::Response<impl http_body::Body<Data = Bytes, Error = HttpError> + Send> {
let response: http::Response<reqwest::Body> = self.inner.into();
let revoked = self.permit.clone();
response.map(|body| PolicyBody {
body: Some(Box::pin(body)),
permit: self.permit,
revoked: async move { revoked.revoked().await }.boxed(),
})
}
pub(crate) fn new(inner: reqwest::Response, permit: NetworkPermit) -> Self {
Self { inner, permit }
}
pub async fn bytes(self) -> Result<Bytes, HttpError> {
Ok(Box::pin(self.permit.run(self.inner.bytes())).await??)
}
pub async fn text(self) -> Result<String, HttpError> {
Ok(Box::pin(self.permit.run(self.inner.text())).await??)
}
pub async fn json<T: DeserializeOwned>(self) -> Result<T, HttpError> {
Ok(Box::pin(self.permit.run(self.inner.json())).await??)
}
pub async fn chunk(&mut self) -> Result<Option<Bytes>, HttpError> {
Ok(Box::pin(self.permit.run(self.inner.chunk())).await??)
}
pub fn error_for_status(self) -> Result<Self, HttpError> {
self.permit.check()?;
Ok(Self {
inner: self.inner.error_for_status()?,
permit: self.permit,
})
}
pub fn error_for_status_ref(&self) -> Result<&Self, HttpError> {
self.permit.check()?;
self.inner.error_for_status_ref()?;
Ok(self)
}
pub fn bytes_stream(self) -> impl Stream<Item = Result<Bytes, HttpError>> + Send + Unpin {
Box::pin(stream::try_unfold(
(Box::pin(self.inner.bytes_stream()), self.permit),
|(mut body, permit)| async move {
let next = permit.run(body.next()).await?;
next.transpose()
.map(|next| next.map(|bytes| (bytes, (body, permit))))
.map_err(HttpError::from)
},
))
}
}
struct PolicyBody<B> {
body: Option<Pin<Box<B>>>,
permit: NetworkPermit,
revoked: BoxFuture<'static, ()>,
}
impl<B: http_body::Body<Data = Bytes, Error = reqwest::Error>> http_body::Body for PolicyBody<B> {
type Data = Bytes;
type Error = HttpError;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<http_body::Frame<Bytes>, HttpError>>> {
let body = self.get_mut();
let Some(inner) = body.body.as_mut() else {
return Poll::Ready(None);
};
if body.permit.check().is_err() || body.revoked.poll_unpin(cx).is_ready() {
body.body = None;
return Poll::Ready(Some(Err(crate::NetworkPolicyDenied::Revoked.into())));
}
inner
.as_mut()
.poll_frame(cx)
.map(|frame| frame.map(|frame| frame.map_err(HttpError::from)))
}
fn is_end_stream(&self) -> bool {
self.body
.as_ref()
.is_none_or(http_body::Body::is_end_stream)
}
fn size_hint(&self) -> http_body::SizeHint {
self.body
.as_ref()
.map_or_else(http_body::SizeHint::default, http_body::Body::size_hint)
}
}
impl Deref for HttpResponse {
type Target = reqwest::Response;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl From<reqwest::Response> for HttpResponse {
fn from(inner: reqwest::Response) -> Self {
let permit = NetworkPolicy::unmanaged()
.acquire(inner.url())
.unwrap_or_else(|_| unreachable!("unmanaged policy permits every URL"));
Self { inner, permit }
}
}
impl<T: Into<reqwest::Body>> From<http::Response<T>> for HttpResponse {
fn from(response: http::Response<T>) -> Self {
reqwest::Response::from(response).into()
}
}

View File

@@ -0,0 +1,54 @@
//! Server retry advice captured once so passing an error between callers does not restart it.
use http::HeaderMap;
use http::header::RETRY_AFTER;
use std::time::Duration;
use std::time::SystemTime;
use tokio::time::Instant;
/// The earliest time a server advised making a follow-up request.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RetryAfter(Instant);
impl RetryAfter {
/// Captures an interval measured from receipt of the server's advice.
pub fn from_delay(delay: Duration) -> Option<Self> {
Instant::now().checked_add(delay).map(Self)
}
/// Reads either nonnegative delay seconds or an HTTP date from `Retry-After`.
pub fn from_headers(headers: &HeaderMap) -> Option<Self> {
Self::from_header(headers.get(RETRY_AFTER)?.to_str().ok()?)
}
/// Reads a `Retry-After` value, including values carried inside a streamed error.
pub fn from_header(value: &str) -> Option<Self> {
// Sample wall time first so a scheduling pause cannot shorten the server's deadline.
let now = SystemTime::now();
let received_at = Instant::now();
let value = value.trim();
let delay = if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
Duration::from_secs(value.parse().ok()?)
} else {
httpdate::parse_http_date(value)
.ok()?
.duration_since(now)
.unwrap_or_default()
};
received_at.checked_add(delay).map(Self)
}
/// Returns the original deadline for callers that pass advice on or sleep until it.
pub fn deadline(self) -> Instant {
self.0
}
/// Returns the remaining delay, or zero after the deadline has passed.
pub fn remaining_delay(self) -> Duration {
self.0.saturating_duration_since(Instant::now())
}
}
#[cfg(test)]
#[path = "retry_after_tests.rs"]
mod tests;

View File

@@ -0,0 +1,45 @@
use super::*;
use http::HeaderValue;
use pretty_assertions::assert_eq;
/// Delta seconds start at receipt and remain present once their deadline expires.
#[tokio::test(start_paused = true)]
async fn delta_seconds_count_down_to_zero() {
let mut headers = HeaderMap::new();
headers.insert(RETRY_AFTER, HeaderValue::from_static("10"));
let advice = RetryAfter::from_headers(&headers).expect("valid advice");
let deadline = Instant::now() + Duration::from_secs(10);
assert_eq!(advice.deadline(), deadline);
assert_eq!(advice.remaining_delay(), Duration::from_secs(10));
tokio::time::advance(Duration::from_secs(4)).await;
assert_eq!(advice.remaining_delay(), Duration::from_secs(6));
tokio::time::advance(Duration::from_secs(7)).await;
assert_eq!(advice.remaining_delay(), Duration::ZERO);
}
/// HTTP dates share the monotonic clock; expired dates and explicit zero are still advice.
#[tokio::test(start_paused = true)]
async fn http_dates_and_invalid_advice() {
let value = httpdate::fmt_http_date(SystemTime::now() + Duration::from_secs(60));
let date = httpdate::parse_http_date(&value).expect("formatted date");
let before = SystemTime::now();
let advice = RetryAfter::from_header(&value).expect("valid date");
let after = SystemTime::now();
let remaining = advice.remaining_delay();
assert!(
(date.duration_since(after).unwrap()..=date.duration_since(before).unwrap())
.contains(&remaining)
);
tokio::time::advance(Duration::from_secs(3)).await;
assert_eq!(advice.remaining_delay(), remaining - Duration::from_secs(3));
for value in ["0", "Thu, 01 Jan 1970 00:00:00 GMT"] {
assert_eq!(
RetryAfter::from_header(value).map(RetryAfter::remaining_delay),
Some(Duration::ZERO)
);
}
for value in ["", "-1", "+1", "1.5", "invalid", "18446744073709551615"] {
assert_eq!(RetryAfter::from_header(value), None, "{value}");
}
}

View File

@@ -0,0 +1,626 @@
mod execution;
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::io;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use http::HeaderMap;
use http::Method;
use http::StatusCode;
use reqwest::IntoUrl;
use crate::BuildRouteAwareHttpClientError;
use crate::ClientRouteClass;
use crate::HttpClient;
use crate::HttpClientBuilder;
use crate::HttpClientFactory;
use crate::NetworkPolicy;
use crate::NetworkPolicyDenied;
use crate::OutboundProxyPolicy;
use crate::OutboundProxyRoute;
use crate::RequestBuilder;
use crate::RouteFailureClass;
use crate::client::HttpClientBackend;
use crate::client::TransportClient;
use crate::client_builder::ProxyRouting;
use crate::tls_backend_fallback::RustlsClientCache;
const MAX_CACHED_ROUTES: usize = 16;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
enum CustomCaFallback {
LegacyDirect,
#[default]
Disabled,
LegacyTransportDefault,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum SelectedTlsBackend {
TransportDefault,
RustlsFallback,
}
/// Reuses transport clients by resolved route while selecting a route for every request URL.
///
/// Resolves the initial route from the complete input URL, before reqwest handles URL credentials.
/// Redirects are followed through the pool as new requests, so
/// each hop gets its own route decision while connections are still reused by route.
#[derive(Clone)]
pub struct RouteAwareClientPool {
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
pub(crate) client_builder: HttpClientBuilder,
default_headers: HeaderMap,
custom_ca_fallback: CustomCaFallback,
direct_proxy: bool,
clients: Arc<Mutex<HashMap<OutboundProxyRoute, TransportClient>>>,
client_build: Arc<tokio::sync::Mutex<()>>,
rustls_clients: Option<RustlsClientCache>,
}
impl fmt::Debug for RouteAwareClientPool {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RouteAwareClientPool")
.field("http_client_factory", &self.http_client_factory)
.field("route_class", &self.route_class)
.finish_non_exhaustive()
}
}
/// Error returned when selecting a route or constructing its pooled HTTP client.
#[derive(Debug, thiserror::Error)]
pub enum RouteAwareClientPoolError {
#[error("failed to resolve the outbound proxy route: {0}")]
Resolve(#[source] io::Error),
#[error(transparent)]
Build(#[from] BuildRouteAwareHttpClientError),
#[error("HTTP transport construction task failed: {0}")]
BuildTask(#[source] tokio::task::JoinError),
}
/// Error returned while building, routing, or sending a route-aware request.
#[derive(Debug, thiserror::Error)]
pub enum RouteAwareRequestError {
#[error(transparent)]
Policy(#[from] NetworkPolicyDenied),
#[error(transparent)]
Request(#[from] reqwest::Error),
#[error(transparent)]
Route(#[from] RouteAwareClientPoolError),
#[error("failed to build route-aware request: {0}")]
Build(String),
#[error("redirect target uses unsupported URL scheme: {0}")]
UnsupportedRedirectScheme(String),
#[error("too many redirects")]
TooManyRedirects,
#[error("route-aware request timed out")]
Timeout,
}
impl RouteAwareRequestError {
/// Classifies transport, proxy, and certificate failures without exposing request details.
pub fn failure_class(&self) -> Option<RouteFailureClass> {
if self.is_timeout() {
return Some(RouteFailureClass::ConnectTimeout);
}
if self.status() == Some(StatusCode::PROXY_AUTHENTICATION_REQUIRED) {
return Some(RouteFailureClass::ProxyAuthenticationRequired);
}
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(self);
while let Some(error) = source {
if error.downcast_ref::<rustls::Error>().is_some()
|| error.downcast_ref::<native_tls::Error>().is_some()
{
return Some(RouteFailureClass::TlsError);
}
if error.to_string() == "tunnel error: proxy authorization required" {
return Some(RouteFailureClass::ProxyAuthenticationRequired);
}
// io::Error::source skips its inner error, which may itself be the TLS error.
source = match error
.downcast_ref::<io::Error>()
.and_then(io::Error::get_ref)
{
Some(inner) => Some(inner),
None => error.source(),
};
}
match self {
Self::Route(RouteAwareClientPoolError::Build(
BuildRouteAwareHttpClientError::CustomCa(_)
| BuildRouteAwareHttpClientError::ExplicitTls(_),
)) => Some(RouteFailureClass::TlsError),
Self::Route(RouteAwareClientPoolError::Build(
BuildRouteAwareHttpClientError::InvalidProxyConfig { .. },
)) => Some(RouteFailureClass::InvalidProxyConfig),
Self::Route(RouteAwareClientPoolError::Resolve(_)) => {
Some(RouteFailureClass::ProxyResolutionUnavailable)
}
Self::Route(RouteAwareClientPoolError::BuildTask(_))
| Self::Request(_)
| Self::Policy(_)
| Self::Build(_)
| Self::UnsupportedRedirectScheme(_)
| Self::TooManyRedirects
| Self::Timeout => None,
}
}
pub fn status(&self) -> Option<StatusCode> {
match self {
Self::Request(error) => error.status(),
Self::Route(_)
| Self::Policy(_)
| Self::Build(_)
| Self::UnsupportedRedirectScheme(_)
| Self::TooManyRedirects
| Self::Timeout => None,
}
}
pub fn is_timeout(&self) -> bool {
matches!(self, Self::Timeout) || matches!(self, Self::Request(error) if error.is_timeout())
}
pub fn is_connect(&self) -> bool {
matches!(self, Self::Request(error) if error.is_connect())
}
pub fn is_builder(&self) -> bool {
matches!(self, Self::Request(error) if error.is_builder())
}
pub fn is_body(&self) -> bool {
matches!(self, Self::Request(error) if error.is_body())
}
pub fn is_request(&self) -> bool {
matches!(self, Self::Request(error) if error.is_request())
}
pub fn url_mut(&mut self) -> Option<&mut reqwest::Url> {
match self {
Self::Request(error) => error.url_mut(),
_ => None,
}
}
/// Removes a request URL from the underlying transport error before it is logged or returned.
///
/// Use this for requests whose URL can contain credentials, such as signed blob uploads.
pub fn without_url(self) -> Self {
match self {
Self::Request(error) => Self::Request(error.without_url()),
other => other,
}
}
}
impl RouteAwareClientPool {
pub(crate) fn request_logging_enabled(&self) -> bool {
self.client_builder.request_logging_enabled()
}
pub fn outbound_proxy_policy(&self) -> OutboundProxyPolicy {
self.http_client_factory.outbound_proxy_policy()
}
pub fn allows_system_proxy_fallback(&self) -> bool {
self.http_client_factory.allows_system_proxy_fallback()
}
/// Changes routing while preserving transport settings and clients cached by resolved route.
pub fn with_outbound_proxy_policy(mut self, policy: OutboundProxyPolicy) -> Self {
self.http_client_factory = self.http_client_factory.with_outbound_proxy_policy(policy);
self
}
/// Exposes the ordinary request builder while sending through this policy-aware pool.
pub fn into_client(self) -> HttpClient {
HttpClient {
backend: HttpClientBackend::Routed(Arc::new(self)),
}
}
/// Creates a pool with the shared default HTTP transport settings.
pub fn new(http_client_factory: HttpClientFactory, route_class: ClientRouteClass) -> Self {
Self::with_builder(http_client_factory, route_class, HttpClientBuilder::new())
}
/// Creates a pool that returns redirect responses without following them.
///
/// This applies both when reqwest owns redirect handling and when the pool follows redirects
/// manually so each hop can receive its own proxy-route decision.
pub fn new_without_redirects(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new().without_redirects(),
)
}
/// Creates a no-redirect pool without request URL or response-header diagnostics.
pub fn new_without_redirects_or_request_logging(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new()
.without_redirects()
.without_request_logging(),
)
}
/// Creates a pool whose clients limit only connection establishment.
///
/// The timeout applies to every client built for a resolved route, including redirect hops.
pub fn with_connect_timeout(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
connect_timeout: Duration,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new().connect_timeout(connect_timeout),
)
}
/// Configures protocol-specific transport behavior without bypassing destination checks.
pub fn with_builder(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
mut client_builder: HttpClientBuilder,
) -> Self {
let default_headers = client_builder.default_headers.take().unwrap_or_default();
Self {
http_client_factory,
route_class,
client_builder,
default_headers,
custom_ca_fallback: CustomCaFallback::Disabled,
direct_proxy: false,
clients: Arc::new(Mutex::new(HashMap::new())),
client_build: Arc::default(),
rustls_clients: None,
}
}
/// Builds the first transport now so fixed-destination callers still receive setup errors.
#[cfg(windows)]
pub(crate) fn with_builder_and_initial_route(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
client_builder: HttpClientBuilder,
route: OutboundProxyRoute,
) -> Result<Self, BuildRouteAwareHttpClientError> {
let mut pool = Self::with_builder(http_client_factory, route_class, client_builder);
let client = pool.client_builder_for_route().build_for_resolved_route(
&pool.http_client_factory,
pool.route_class,
&route,
)?;
pool.clients = Arc::new(Mutex::new(HashMap::from([(route, client)])));
Ok(pool)
}
/// Starts a new account-scoped operation while sharing the existing connection cache.
/// Capture this before resolving credentials or reading account-specific content.
pub fn for_current_account(&self) -> Self {
let mut pool = self.clone();
pool.http_client_factory = pool.http_client_factory.clone().with_network_policy(
pool.http_client_factory
.network_policy()
.clone()
.for_current_account(),
);
pool
}
/// Bind an operation to the account that supplied its credentials while retaining the
/// caller's restrictions and the existing transport cache.
pub fn with_account_binding(&self, binding: &NetworkPolicy) -> Option<Self> {
let policy = self
.http_client_factory
.network_policy()
.clone()
.with_account_binding(binding)?;
let mut pool = self.clone();
pool.http_client_factory = pool.http_client_factory.with_network_policy(policy);
Some(pool)
}
/// Retries recognized TLS protocol-negotiation failures once using rustls.
///
/// Successful fallback is remembered for each HTTPS origin and resolved outbound route.
/// Rustls clients are reused across fallback destinations that share a route, while other
/// destinations retain the existing transport-default backend.
pub fn with_tls_backend_fallback(mut self) -> Self {
self.rustls_clients = Some(RustlsClientCache::default());
self
}
/// Creates a pool with the shared defaults but without URL or response-header diagnostics.
pub fn new_without_request_logging(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new().without_request_logging(),
)
}
/// Preserves the legacy custom-CA fallback for transport-default proxy routes.
///
/// Use this only when migrating a client that already continued with system roots after a
/// custom-CA construction failure. System-proxy routes still propagate construction errors.
pub fn with_legacy_custom_ca_fallback(mut self) -> Self {
self.custom_ca_fallback = CustomCaFallback::LegacyTransportDefault;
self
}
/// Uses direct routing without changing destination policy or TLS configuration.
pub fn with_direct_proxy(mut self) -> Self {
self.direct_proxy = true;
self
}
/// Preserves the legacy sandbox client's direct routing and custom-CA fallback.
pub fn with_legacy_direct_proxy_and_custom_ca_fallback(mut self) -> Self {
self.custom_ca_fallback = CustomCaFallback::LegacyDirect;
self
}
/// Creates a pool that retains the Cloudflare cookies required by ChatGPT endpoints.
pub fn with_chatgpt_cloudflare_cookies(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_chatgpt_cloudflare_cookies_and_default_headers(
http_client_factory,
route_class,
HeaderMap::new(),
)
}
/// Creates a pool with ChatGPT Cloudflare cookies and default headers on every route.
pub fn with_chatgpt_cloudflare_cookies_and_default_headers(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
default_headers: HeaderMap,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new()
.default_headers(default_headers)
.with_chatgpt_cloudflare_cookie_store(),
)
}
/// Creates a no-redirect pool that retains the Cloudflare cookies required by ChatGPT
/// endpoints.
pub fn with_chatgpt_cloudflare_cookies_without_redirects(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new()
.with_chatgpt_cloudflare_cookie_store()
.without_redirects(),
)
}
/// Creates a no-redirect ChatGPT Cloudflare-cookie pool without request diagnostics.
pub fn with_chatgpt_cloudflare_cookies_without_redirects_or_request_logging(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new()
.with_chatgpt_cloudflare_cookie_store()
.without_redirects()
.without_request_logging(),
)
}
/// Creates a ChatGPT Cloudflare-cookie pool without URL or response-header diagnostics.
pub fn with_chatgpt_cloudflare_cookies_without_request_logging(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new()
.with_chatgpt_cloudflare_cookie_store()
.without_request_logging(),
)
}
pub fn get<U>(&self, url: U) -> RequestBuilder
where
U: IntoUrl,
{
self.request(Method::GET, url)
}
pub fn post<U>(&self, url: U) -> RequestBuilder
where
U: IntoUrl,
{
self.request(Method::POST, url)
}
pub fn put<U>(&self, url: U) -> RequestBuilder
where
U: IntoUrl,
{
self.request(Method::PUT, url)
}
pub fn delete<U>(&self, url: U) -> RequestBuilder
where
U: IntoUrl,
{
self.request(Method::DELETE, url)
}
pub fn request<U>(&self, method: Method, url: U) -> RequestBuilder
where
U: IntoUrl,
{
RequestBuilder::routed(Arc::new(self.clone()), method, url)
}
async fn client_for_url_with_resolver<F, Fut>(
&self,
request_url: &str,
resolve_route: F,
) -> Result<(OutboundProxyRoute, TransportClient, SelectedTlsBackend), RouteAwareClientPoolError>
where
F: FnOnce(String) -> Fut,
Fut: Future<Output = io::Result<OutboundProxyRoute>>,
{
let route =
if self.direct_proxy || self.custom_ca_fallback == CustomCaFallback::LegacyDirect {
OutboundProxyRoute::Direct
} else {
resolve_route(request_url.to_string())
.await
.map_err(RouteAwareClientPoolError::Resolve)?
};
if let Some(rustls_clients) = self.rustls_clients.as_ref()
&& let Ok(url) = reqwest::Url::parse(request_url)
&& rustls_clients.requires_rustls(&url, &route)
&& let Some(client) = rustls_clients.client_for_route(&route)
{
return Ok((route, client, SelectedTlsBackend::RustlsFallback));
}
{
let clients = match self.clients.lock() {
Ok(clients) => clients,
Err(error) => {
panic!("route-aware client cache lock should not be poisoned: {error}")
}
};
if let Some(client) = clients.get(&route) {
return Ok((route, client.clone(), SelectedTlsBackend::TransportDefault));
}
}
let build_permit = Arc::clone(&self.client_build).lock_owned().await;
{
let clients = self.clients.lock().unwrap_or_else(|error| {
panic!("route-aware client cache lock should not be poisoned: {error}")
});
if let Some(client) = clients.get(&route) {
return Ok((route, client.clone(), SelectedTlsBackend::TransportDefault));
}
}
let client_builder = self.client_builder_for_route();
let pool = self.clone();
let build_route = route.clone();
let client = tokio::task::spawn_blocking(move || {
// A timed-out caller must not release the slot or discard a successful build.
let _build_permit = build_permit;
let client = match (
pool.http_client_factory.outbound_proxy_policy(),
pool.custom_ca_fallback,
) {
(_, CustomCaFallback::LegacyDirect) => {
Ok(client_builder.build_with_custom_ca_fallback(ProxyRouting::Direct))
}
(OutboundProxyPolicy::ReqwestDefault, CustomCaFallback::LegacyTransportDefault) => {
Ok(
client_builder
.build_with_custom_ca_fallback(ProxyRouting::TransportDefault),
)
}
(OutboundProxyPolicy::ReqwestDefault, CustomCaFallback::Disabled)
| (OutboundProxyPolicy::RespectSystemProxy, CustomCaFallback::Disabled)
| (
OutboundProxyPolicy::RespectSystemProxy,
CustomCaFallback::LegacyTransportDefault,
) => client_builder.build_for_resolved_route(
&pool.http_client_factory,
pool.route_class,
&build_route,
),
}?;
let mut clients = pool.clients.lock().unwrap_or_else(|error| {
panic!("route-aware client cache lock should not be poisoned: {error}")
});
if clients.len() >= MAX_CACHED_ROUTES
&& let Some(route_to_evict) = clients.keys().next().cloned()
{
clients.remove(&route_to_evict);
}
clients.insert(build_route, client.clone());
Ok::<_, BuildRouteAwareHttpClientError>(client)
})
.await
.map_err(RouteAwareClientPoolError::BuildTask)??;
Ok((route, client, SelectedTlsBackend::TransportDefault))
}
fn follows_redirects_manually(&self) -> bool {
self.client_builder.follows_redirects()
&& (self.http_client_factory.outbound_proxy_policy()
== OutboundProxyPolicy::RespectSystemProxy
|| self.http_client_factory.network_policy().is_managed()
|| self.http_client_factory.protects_sensitive_headers()
|| self.rustls_clients.is_some())
}
fn client_builder_for_route(&self) -> HttpClientBuilder {
if self.follows_redirects_manually() {
self.client_builder.clone().without_redirects()
} else {
self.client_builder.clone()
}
}
fn rustls_client_for_route(
&self,
route: &OutboundProxyRoute,
) -> Result<TransportClient, RouteAwareClientPoolError> {
let mut client_builder = self.client_builder.clone().with_rustls_tls();
if self.follows_redirects_manually() {
client_builder = client_builder.without_redirects();
}
client_builder
.build_for_resolved_route(&self.http_client_factory, self.route_class, route)
.map_err(Into::into)
}
}
#[cfg(test)]
#[path = "route_aware_client_pool_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "route_aware_tls_fallback_tests.rs"]
mod tls_fallback_tests;
#[cfg(test)]
#[path = "route_aware_policy_tests.rs"]
mod policy_tests;

View File

@@ -0,0 +1,380 @@
//! Executes pooled HTTP requests, redirects, and TLS fallback within one request lifetime.
use std::future::Future;
use std::io;
use std::sync::atomic::Ordering;
use futures::FutureExt;
use futures::future::BoxFuture;
use http::header::PROXY_AUTHORIZATION;
use super::RouteAwareClientPool;
#[cfg(windows)]
use super::RouteAwareClientPoolError;
use super::RouteAwareRequestError;
use super::SelectedTlsBackend;
use crate::HttpResponse;
use crate::OutboundProxyRoute;
#[cfg(windows)]
use crate::RouteFailureClass;
#[cfg(windows)]
use crate::client::TransportClient;
use crate::client::apply_default_headers;
use crate::request_draft::RequestDraft;
use crate::route_aware_redirect::MAX_REDIRECTS;
use crate::route_aware_redirect::insert_referer;
use crate::route_aware_redirect::is_redirect;
use crate::route_aware_redirect::redirect_request;
use crate::route_aware_redirect::redirect_url;
use crate::route_aware_redirect::remove_sensitive_headers;
use crate::tls_backend_fallback::should_retry_with_rustls;
#[cfg(windows)]
use crate::windows_proxy_auth::ProxyPipe;
impl RouteAwareClientPool {
/// Executes requests through shared routing, destination, and redirect checks.
///
/// Box the execution future so nested callers do not inherit policy and routing state.
pub fn execute(
&self,
request: reqwest::Request,
) -> BoxFuture<'_, Result<HttpResponse, RouteAwareRequestError>> {
self.send(request.into())
}
pub(crate) fn send(
&self,
request: RequestDraft,
) -> BoxFuture<'_, Result<HttpResponse, RouteAwareRequestError>> {
self.send_with_resolver(request, |request_url| {
self.http_client_factory
.resolve_proxy_route_async(request_url)
})
.boxed()
}
pub(super) async fn send_with_resolver<F, Fut>(
&self,
request: impl Into<RequestDraft>,
resolve_route: F,
) -> Result<HttpResponse, RouteAwareRequestError>
where
F: Fn(String) -> Fut,
Fut: Future<Output = io::Result<OutboundProxyRoute>>,
{
let request = request.into();
let permit = self
.http_client_factory
.network_policy()
.acquire(request.request.url())?;
permit
.run(Box::pin(self.send_authorized(request, resolve_route)))
.await?
}
async fn send_authorized<F, Fut>(
&self,
draft: RequestDraft,
resolve_route: F,
) -> Result<HttpResponse, RouteAwareRequestError>
where
F: Fn(String) -> Fut,
Fut: Future<Output = io::Result<OutboundProxyRoute>>,
{
let mut request = draft.request;
let mut draft_headers = Some(draft.headers);
let request_method = request.method().clone();
let mut request_url = request.url().to_string();
let follows_redirects_manually = self.follows_redirects_manually();
let timeout_deadline = request
.timeout()
.copied()
.map(|timeout| tokio::time::Instant::now() + timeout);
let mut redirects = 0;
let mut previous_route = None;
loop {
let current_url = request.url().clone();
let permit = self
.http_client_factory
.network_policy()
.acquire(&current_url)?;
let hop = async {
let (current_route, mut client, selected_tls_backend) = self
.client_for_url_with_resolver(current_url.as_str(), &resolve_route)
.await?;
client.request_logging = self.client_builder.request_logging;
if let Some(headers) = draft_headers.take() {
request = RequestDraft { request, headers }.build(&client)?;
request_url = request.url().to_string();
apply_default_headers(request.headers_mut(), &self.default_headers);
}
let current_url = request.url().clone();
if previous_route
.as_ref()
.is_some_and(|previous_route| previous_route != &current_route)
{
request.headers_mut().remove(PROXY_AUTHORIZATION);
}
previous_route = Some(current_route.clone());
set_remaining_timeout(&mut request, timeout_deadline)?;
let method = request.method().clone();
let headers = request.headers().clone();
let version = request.version();
let timeout = request.timeout().copied();
let replay = request.try_clone();
let result = if follows_redirects_manually {
client.execute_without_request_logging(request).await
} else {
client.execute(request).await
}
.map_err(RouteAwareRequestError::from);
let result = match result {
// A failed CONNECT identifies a proxy challenge. An origin 407 is a response.
#[cfg(windows)]
Err(error)
if error.is_connect()
&& error.failure_class()
== Some(RouteFailureClass::ProxyAuthenticationRequired) =>
{
self.retry_windows_proxy(
&current_route,
selected_tls_backend,
replay.as_ref(),
error,
timeout_deadline,
)
.await
}
Err(RouteAwareRequestError::Request(error)) => {
self.retry_with_rustls(
&current_route,
selected_tls_backend,
replay.as_ref(),
#[cfg(windows)]
/*proxy_pipe*/
None,
error,
timeout_deadline,
)
.await
}
result => result,
};
if follows_redirects_manually
&& let Err(RouteAwareRequestError::Request(error)) = &result
{
client.log_error_summary(&request_method, &request_url, error);
}
let response = result?;
let next_request = if follows_redirects_manually && is_redirect(response.status()) {
redirect_url(&response).and_then(|next_url| {
redirect_request(
response.status(),
method,
headers,
version,
timeout,
replay,
next_url,
)
})
} else {
None
};
if follows_redirects_manually && next_request.is_none() {
client.log_response(&request_method, &request_url, &response);
}
Ok::<_, RouteAwareRequestError>((response, next_request, current_url))
};
let (response, next_request, current_url) = permit
.run(async {
match timeout_deadline {
Some(deadline) => tokio::time::timeout_at(deadline, hop)
.await
.map_err(|_| RouteAwareRequestError::Timeout)?,
None => hop.await,
}
})
.await??;
let Some(mut next_request) = next_request else {
return Ok(HttpResponse::new(response, permit));
};
if let Some(redirect_observed) = &self.client_builder.redirect_observed {
redirect_observed.store(/*val*/ true, Ordering::Relaxed);
}
let next_request_url = next_request.url().clone();
if !matches!(next_request_url.scheme(), "http" | "https") {
return Err(RouteAwareRequestError::UnsupportedRedirectScheme(
next_request_url.scheme().to_string(),
));
}
if redirects >= MAX_REDIRECTS {
return Err(RouteAwareRequestError::TooManyRedirects);
}
remove_sensitive_headers(
next_request.headers_mut(),
&current_url,
&next_request_url,
self.http_client_factory.protects_sensitive_headers(),
);
insert_referer(next_request.headers_mut(), &current_url, &next_request_url);
request = next_request;
redirects += 1;
}
}
pub(super) async fn retry_with_rustls(
&self,
current_route: &OutboundProxyRoute,
selected_tls_backend: SelectedTlsBackend,
replay: Option<&reqwest::Request>,
#[cfg(windows)] proxy_pipe: Option<&ProxyPipe>,
error: reqwest::Error,
timeout_deadline: Option<tokio::time::Instant>,
) -> Result<reqwest::Response, RouteAwareRequestError> {
let Some(rustls_clients) = self.rustls_clients.as_ref() else {
return Err(error.into());
};
let Some(replay) = replay else {
return Err(error.into());
};
let current_url = replay.url();
if current_url.scheme() != "https"
|| selected_tls_backend == SelectedTlsBackend::RustlsFallback
|| !should_retry_with_rustls(&error)
{
return Err(error.into());
}
let Some(mut retry_request) = replay.try_clone() else {
return Err(error.into());
};
let candidate = rustls_clients.client_for_route(current_route);
#[cfg(windows)]
let candidate = match proxy_pipe {
Some(pipe) => Some(self.windows_proxy_client(
current_route,
SelectedTlsBackend::RustlsFallback,
pipe,
)?),
None => candidate,
};
let mut fallback_client = match candidate {
Some(client) => client,
None => self.rustls_client_for_route(current_route)?,
};
fallback_client.request_logging = self.client_builder.request_logging;
set_remaining_timeout(&mut retry_request, timeout_deadline)?;
let response = if self.follows_redirects_manually() {
fallback_client
.execute_without_request_logging(retry_request)
.await
} else {
fallback_client.execute(retry_request).await
}?;
tracing::info!(
event.name = "codex.http_client.tls_backend_fallback",
"HTTP client switched to rustls after a TLS protocol negotiation failure"
);
// A Windows auth pipe serves this destination alone, so it cannot enter the route cache.
#[cfg(windows)]
if proxy_pipe.is_some() {
return Ok(response);
}
rustls_clients.remember(current_url, current_route, fallback_client);
Ok(response)
}
#[cfg(windows)]
async fn retry_windows_proxy(
&self,
current_route: &OutboundProxyRoute,
selected_tls_backend: SelectedTlsBackend,
replay: Option<&reqwest::Request>,
error: RouteAwareRequestError,
timeout_deadline: Option<tokio::time::Instant>,
) -> Result<reqwest::Response, RouteAwareRequestError> {
let OutboundProxyRoute::Proxy { url, .. } = current_route else {
return Err(error);
};
let Some(mut request) = replay.and_then(reqwest::Request::try_clone) else {
return Err(error);
};
if request.url().scheme() != "https" {
return Err(error);
}
let pipe = match crate::windows_proxy_auth::pipe_for(
url,
request.url(),
&self.client_builder.tls,
self.client_builder.connect_timeout,
)
.await
{
Ok(pipe) => pipe,
Err(auth_error) if auth_error.kind() == io::ErrorKind::TimedOut => {
return Err(RouteAwareRequestError::Timeout);
}
Err(_) => return Err(error),
};
let client = self.windows_proxy_client(current_route, selected_tls_backend, &pipe)?;
set_remaining_timeout(&mut request, timeout_deadline)?;
// Keep the listener alive through a possible TLS retry.
let result = client.execute_without_request_logging(request).await;
match result {
Ok(response) => Ok(response),
Err(error) => {
self.retry_with_rustls(
current_route,
selected_tls_backend,
replay,
Some(&pipe),
error,
timeout_deadline,
)
.await
}
}
}
#[cfg(windows)]
fn windows_proxy_client(
&self,
route: &OutboundProxyRoute,
backend: SelectedTlsBackend,
pipe: &ProxyPipe,
) -> Result<TransportClient, RouteAwareClientPoolError> {
let mut builder = self
.client_builder
.clone()
.without_redirects()
.with_windows_proxy_pipe(pipe);
if backend == SelectedTlsBackend::RustlsFallback {
builder = builder.with_rustls_tls();
}
builder
.build_for_resolved_route(&self.http_client_factory, self.route_class, route)
.map_err(Into::into)
}
}
fn set_remaining_timeout(
request: &mut reqwest::Request,
deadline: Option<tokio::time::Instant>,
) -> Result<(), RouteAwareRequestError> {
if let Some(deadline) = deadline {
let remaining = deadline
.checked_duration_since(tokio::time::Instant::now())
.filter(|remaining| !remaining.is_zero())
.ok_or(RouteAwareRequestError::Timeout)?;
*request.timeout_mut() = Some(remaining);
}
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,132 @@
//! Unavailable policy rejects requests before a socket is opened.
use super::*;
use http::StatusCode;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn unavailable_policy_does_not_connect() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let url = format!("https://{}/", listener.local_addr().unwrap());
let controller = crate::NetworkPolicyController::default();
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(controller.policy());
let client = factory.build_client(&url, ClientRouteClass::Api).unwrap();
assert!(matches!(
client.get(&url).send().await,
Err(RouteAwareRequestError::Policy(
NetworkPolicyDenied::Unavailable
))
));
assert_eq!(
listener.accept().unwrap_err().kind(),
std::io::ErrorKind::WouldBlock
);
}
#[tokio::test]
async fn account_change_cancels_redirect_route_selection() {
let (address, server) = super::tests::spawn_response_server(vec![
"HTTP/1.1 302 Found\r\nLocation: /final\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
.into(),
]);
let controller = crate::NetworkPolicyController::default();
let policy = controller.policy();
controller.publish(policy.revision(), crate::DestinationPolicy::Unrestricted);
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy.clone()),
ClientRouteClass::Api,
);
let request = reqwest::Request::new(
Method::GET,
reqwest::Url::parse(&format!("http://{address}/start")).unwrap(),
);
let result = tokio::time::timeout(
std::time::Duration::from_secs(/*secs*/ 5),
pool.send_with_resolver(request, |url| {
let policy = policy.clone();
async move {
if url.ends_with("/final") {
policy.invalidate();
return std::future::pending().await;
}
Ok(OutboundProxyRoute::Direct)
}
}),
)
.await
.unwrap();
assert!(matches!(
result,
Err(RouteAwareRequestError::Policy(NetworkPolicyDenied::Revoked))
));
assert_eq!(server.join().unwrap().len(), 1);
}
#[tokio::test]
async fn managed_redirect_failure_is_tracked_before_proxy_retry() {
let unused = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let dead_address = unused.local_addr().unwrap();
drop(unused);
let (address, server) = super::tests::spawn_response_server(vec![format!(
"HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{dead_address}/token\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
)]);
let controller = crate::NetworkPolicyController::default();
let policy = controller.policy();
controller.publish(policy.revision(), crate::DestinationPolicy::Unrestricted);
let redirected = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(/*v*/ false));
let pool = RouteAwareClientPool::with_builder(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy)
.with_system_proxy_fallback(),
ClientRouteClass::Auth,
HttpClientBuilder::new().with_redirect_tracking(redirected.clone()),
);
let result = pool
.post(format!("http://{address}/token"))
.body("code=one-time-code")
.timeout(std::time::Duration::from_secs(/*secs*/ 5))
.send()
.await;
assert!(result.is_err());
assert!(redirected.load(std::sync::atomic::Ordering::Relaxed));
assert_eq!(server.join().unwrap().len(), 1);
}
#[tokio::test]
async fn credential_binding_rejects_old_operations_after_account_replacement() {
let (address, server) = super::tests::spawn_response_server(vec![
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
]);
let url = format!("http://{address}/account");
let controller = crate::NetworkPolicyController::default();
let policy = controller.policy();
assert!(controller.publish(policy.revision(), crate::DestinationPolicy::Unrestricted));
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy.clone()),
ClientRouteClass::Api,
);
let old = pool
.with_account_binding(&policy.clone().for_current_account())
.unwrap();
assert_eq!(old.get(&url).send().await.unwrap().status(), StatusCode::OK);
policy.invalidate();
assert!(controller.publish(policy.revision(), crate::DestinationPolicy::Unrestricted));
assert!(matches!(
old.get(&url).send().await,
Err(RouteAwareRequestError::Policy(NetworkPolicyDenied::Revoked))
));
let fresh = pool
.with_account_binding(&policy.for_current_account())
.unwrap();
assert_eq!(
fresh.get(&url).send().await.unwrap().status(),
StatusCode::OK
);
assert_eq!(server.join().unwrap().len(), 2);
}

View File

@@ -0,0 +1,159 @@
//! Redirect semantics for requests whose proxy route is selected from the complete URL.
//!
//! Reqwest normally follows redirects inside one `Client::execute` call. That is safe for
//! `ReqwestDefault`, where reqwest owns proxy selection, but not for `RespectSystemProxy`: Codex
//! resolves PAC and operating-system proxy settings before building a client pinned to the
//! resulting direct or concrete-proxy route. An internal reqwest redirect would reuse that client
//! for the new URL without giving [`crate::RouteAwareClientPool`] an opportunity to resolve the
//! redirect destination.
//!
//! The pool disables reqwest redirects when route or sensitive-header policy requires checking
//! each hop. It observes each redirect response and uses these helpers to construct the next
//! request before resolving its route. The helpers preserve the relevant reqwest
//! method/body behavior while applying stricter
//! origin-sensitive credential and `Referer` rules at the boundary between requests.
use std::time::Duration;
use http::HeaderMap;
use http::Method;
use http::StatusCode;
use http::header::AUTHORIZATION;
use http::header::CONTENT_ENCODING;
use http::header::CONTENT_LENGTH;
use http::header::CONTENT_TYPE;
use http::header::COOKIE;
use http::header::LOCATION;
use http::header::PROXY_AUTHORIZATION;
use http::header::REFERER;
use http::header::TRANSFER_ENCODING;
use http::header::WWW_AUTHENTICATE;
pub(super) const MAX_REDIRECTS: usize = 10;
pub(super) fn is_redirect(status: StatusCode) -> bool {
matches!(
status,
StatusCode::MOVED_PERMANENTLY
| StatusCode::FOUND
| StatusCode::SEE_OTHER
| StatusCode::TEMPORARY_REDIRECT
| StatusCode::PERMANENT_REDIRECT
)
}
pub(super) fn redirect_url(response: &reqwest::Response) -> Option<reqwest::Url> {
let location = response.headers().get(LOCATION)?.to_str().ok()?;
response.url().join(location).ok()
}
pub(super) fn redirect_request(
status: StatusCode,
mut method: Method,
mut headers: HeaderMap,
version: http::Version,
timeout: Option<Duration>,
replay: Option<reqwest::Request>,
next_url: reqwest::Url,
) -> Option<reqwest::Request> {
let drop_body = match status {
StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND if method == Method::POST => {
method = Method::GET;
true
}
StatusCode::SEE_OTHER => {
if method != Method::HEAD {
method = Method::GET;
}
true
}
StatusCode::MOVED_PERMANENTLY
| StatusCode::FOUND
| StatusCode::TEMPORARY_REDIRECT
| StatusCode::PERMANENT_REDIRECT => false,
_ => return None,
};
if drop_body {
for header in [
CONTENT_TYPE,
CONTENT_LENGTH,
CONTENT_ENCODING,
TRANSFER_ENCODING,
] {
headers.remove(header);
}
let mut request = reqwest::Request::new(method, next_url);
*request.headers_mut() = headers;
*request.version_mut() = version;
*request.timeout_mut() = timeout;
Some(request)
} else {
replay.map(|mut request| {
*request.url_mut() = next_url;
request
})
}
}
pub(super) fn remove_sensitive_headers(
headers: &mut HeaderMap,
previous: &reqwest::Url,
next: &reqwest::Url,
protect_sensitive_headers: bool,
) {
if !same_origin(previous, next) {
for header in [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION, WWW_AUTHENTICATE] {
headers.remove(header);
}
headers.remove("cookie2");
if protect_sensitive_headers {
let sensitive: Vec<_> = headers
.keys()
.filter(|name| {
headers
.get_all(*name)
.iter()
.any(http::HeaderValue::is_sensitive)
})
.cloned()
.collect();
for name in sensitive {
headers.remove(name);
}
}
}
}
pub(super) fn insert_referer(
headers: &mut HeaderMap,
previous: &reqwest::Url,
next: &reqwest::Url,
) {
headers.remove(REFERER);
if next.scheme() == "http" && previous.scheme() == "https" {
return;
}
let mut referer = previous.clone();
let _ = referer.set_username("");
let _ = referer.set_password(None);
referer.set_fragment(None);
if !same_origin(previous, next) {
referer.set_path("/");
referer.set_query(None);
}
if let Ok(value) = referer.as_str().parse() {
headers.insert(REFERER, value);
}
}
fn same_origin(previous: &reqwest::Url, next: &reqwest::Url) -> bool {
previous.scheme() == next.scheme()
&& previous.host_str() == next.host_str()
&& previous.port_or_known_default() == next.port_or_known_default()
}
#[cfg(test)]
#[path = "route_aware_redirect_tests.rs"]
mod tests;

View File

@@ -0,0 +1,172 @@
use std::io;
use std::io::Read;
use std::io::Write;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
use http::header::AUTHORIZATION;
use http::header::COOKIE;
use http::header::PROXY_AUTHORIZATION;
use pretty_assertions::assert_eq;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::SubscriberExt;
use super::*;
use crate::RouteAwareClientPool;
#[tokio::test]
async fn route_aware_pool_re_resolves_redirects_and_logs_only_final_outcome() {
let (proxy_addr, proxy_thread) =
spawn_response("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok");
let (redirect_addr, redirect_thread) = spawn_response(
"HTTP/1.1 302 Found\r\nLocation: /final?token=redirect-target-secret\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
);
let initial_url = format!("http://{redirect_addr}/start");
let redirected_url = format!("http://{redirect_addr}/final?token=redirect-target-secret");
cache_system_proxy_decision(&initial_url, SystemProxyDecision::Direct);
cache_system_proxy_decision(
&redirected_url,
SystemProxyDecision::Proxy {
url: format!("http://{proxy_addr}"),
},
);
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
ClientRouteClass::Api,
);
let log_buffer = Arc::new(Mutex::new(Vec::new()));
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(TestLogWriter {
buffer: Arc::clone(&log_buffer),
})
.with_filter(
tracing_subscriber::filter::Targets::new()
.with_target("codex_http_client", tracing::Level::TRACE),
),
);
let _guard = tracing::subscriber::set_default(subscriber);
tokio::time::timeout(
Duration::from_secs(2),
pool.get(&initial_url)
.header(AUTHORIZATION, "Bearer origin-secret")
.header(COOKIE, "session=origin-secret")
.header(PROXY_AUTHORIZATION, "Basic proxy-secret")
.send(),
)
.await
.expect("redirected request should finish")
.expect("redirected request should use both selected routes");
redirect_thread
.join()
.expect("redirect listener should finish");
let redirected_request = proxy_thread.join().expect("proxy listener should finish");
assert_eq!(
redirected_request.lines().next(),
Some(format!("GET {redirected_url} HTTP/1.1").as_str())
);
assert!(has_header(&redirected_request, "authorization"));
assert!(has_header(&redirected_request, "cookie"));
assert!(!has_header(&redirected_request, "proxy-authorization"));
let logs = String::from_utf8(log_buffer.lock().expect("log buffer lock").clone())
.expect("logs should be UTF-8");
assert!(logs.contains(&initial_url));
assert_eq!(logs.matches("Request completed").count(), 1);
assert!(!logs.contains("redirect-target-secret"));
}
fn spawn_response(
response: &'static str,
) -> (std::net::SocketAddr, std::thread::JoinHandle<String>) {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("bind listener");
let address = listener.local_addr().expect("HTTP listener address");
listener.set_nonblocking(true).expect("set nonblocking");
let thread = std::thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(2);
let (mut stream, _) = loop {
match listener.accept() {
Ok(connection) => break connection,
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
assert!(Instant::now() < deadline, "request timed out");
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => panic!("HTTP listener should accept: {error}"),
}
};
// Accepted sockets inherit the listener's nonblocking mode on macOS.
stream
.set_nonblocking(false)
.expect("set accepted stream blocking");
stream
.set_read_timeout(Some(Duration::from_secs(2)))
.expect("read timeout");
let request = read_http_headers(&mut stream);
stream
.write_all(response.as_bytes())
.expect("write response");
request
});
(address, thread)
}
fn read_http_headers(stream: &mut impl Read) -> String {
let mut buffer = Vec::new();
let mut chunk = [0_u8; 1024];
loop {
let bytes_read = stream.read(&mut chunk).expect("HTTP headers should read");
if bytes_read == 0 {
break;
}
buffer.extend_from_slice(&chunk[..bytes_read]);
if buffer.windows(4).any(|window| window == b"\r\n\r\n") {
break;
}
}
String::from_utf8_lossy(&buffer).into_owned()
}
fn has_header(request: &str, expected_name: &str) -> bool {
request.lines().any(|line| {
line.split_once(':')
.is_some_and(|(name, _)| name.eq_ignore_ascii_case(expected_name))
})
}
#[derive(Clone)]
struct TestLogWriter {
buffer: Arc<Mutex<Vec<u8>>>,
}
struct TestLogSink {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TestLogWriter {
type Writer = TestLogSink;
fn make_writer(&'a self) -> Self::Writer {
TestLogSink {
buffer: Arc::clone(&self.buffer),
}
}
}
impl Write for TestLogSink {
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
let mut log_buffer = self
.buffer
.lock()
.map_err(|_| io::Error::other("log buffer lock was poisoned"))?;
log_buffer.extend(buffer);
Ok(buffer.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}

View File

@@ -0,0 +1,238 @@
use http::HeaderValue;
use http::header::CONTENT_ENCODING;
use http::header::CONTENT_LENGTH;
use http::header::CONTENT_TYPE;
use http::header::COOKIE;
use http::header::REFERER;
use http::header::TRANSFER_ENCODING;
use pretty_assertions::assert_eq;
use super::*;
#[derive(Clone, Copy, Debug)]
enum RedirectBodyBehavior {
Drop,
Preserve,
}
#[test]
fn redirects_match_reqwest_method_and_body_rules() {
let original_url =
reqwest::Url::parse("https://example.com/original").expect("original URL should parse");
let redirected_url =
reqwest::Url::parse("https://example.com/next").expect("redirect URL should parse");
for (status, method, expected_method, body_behavior) in [
(
StatusCode::MOVED_PERMANENTLY,
Method::POST,
Method::GET,
RedirectBodyBehavior::Drop,
),
(
StatusCode::FOUND,
Method::POST,
Method::GET,
RedirectBodyBehavior::Drop,
),
(
StatusCode::SEE_OTHER,
Method::POST,
Method::GET,
RedirectBodyBehavior::Drop,
),
(
StatusCode::SEE_OTHER,
Method::HEAD,
Method::HEAD,
RedirectBodyBehavior::Drop,
),
(
StatusCode::MOVED_PERMANENTLY,
Method::PUT,
Method::PUT,
RedirectBodyBehavior::Preserve,
),
(
StatusCode::FOUND,
Method::PUT,
Method::PUT,
RedirectBodyBehavior::Preserve,
),
(
StatusCode::TEMPORARY_REDIRECT,
Method::POST,
Method::POST,
RedirectBodyBehavior::Preserve,
),
(
StatusCode::PERMANENT_REDIRECT,
Method::POST,
Method::POST,
RedirectBodyBehavior::Preserve,
),
] {
let mut original = reqwest::Request::new(method.clone(), original_url.clone());
*original.headers_mut() = HeaderMap::from_iter([
(CONTENT_TYPE, HeaderValue::from_static("application/json")),
(CONTENT_LENGTH, HeaderValue::from_static("2")),
(CONTENT_ENCODING, HeaderValue::from_static("identity")),
(TRANSFER_ENCODING, HeaderValue::from_static("chunked")),
(
http::header::ACCEPT,
HeaderValue::from_static("application/json"),
),
]);
*original.version_mut() = http::Version::HTTP_2;
*original.timeout_mut() = Some(Duration::from_secs(7));
*original.body_mut() = Some("{}".into());
let mut expected_headers = original.headers().clone();
let expected_body = match body_behavior {
RedirectBodyBehavior::Drop => {
for header in [
CONTENT_TYPE,
CONTENT_LENGTH,
CONTENT_ENCODING,
TRANSFER_ENCODING,
] {
expected_headers.remove(header);
}
None
}
RedirectBodyBehavior::Preserve => Some(b"{}".to_vec()),
};
let redirected = redirect_request(
status,
original.method().clone(),
original.headers().clone(),
original.version(),
original.timeout().copied(),
original.try_clone(),
redirected_url.clone(),
)
.expect("supported redirect should be followed");
assert_eq!(
(
redirected.method().clone(),
redirected.url().clone(),
redirected.headers().clone(),
redirected.version(),
redirected.timeout().copied(),
redirected
.body()
.and_then(reqwest::Body::as_bytes)
.map(<[u8]>::to_vec),
),
(
expected_method,
redirected_url.clone(),
expected_headers,
http::Version::HTTP_2,
Some(Duration::from_secs(7)),
expected_body,
),
"redirect behavior for {status} {method}",
);
}
}
#[test]
fn redirect_referer_follows_strict_origin_when_cross_origin() {
let previous =
reqwest::Url::parse("https://user:password@example.com/start?access_token=secret#fragment")
.expect("valid URL");
let mut same_origin_headers = HeaderMap::new();
let same_origin = reqwest::Url::parse("https://example.com/next").expect("valid URL");
insert_referer(&mut same_origin_headers, &previous, &same_origin);
assert_eq!(
same_origin_headers.get(REFERER),
Some(&HeaderValue::from_static(
"https://example.com/start?access_token=secret"
))
);
let mut cross_origin_headers = HeaderMap::new();
let cross_origin = reqwest::Url::parse("https://other.example/next").expect("valid URL");
insert_referer(&mut cross_origin_headers, &previous, &cross_origin);
assert_eq!(
cross_origin_headers.get(REFERER),
Some(&HeaderValue::from_static("https://example.com/"))
);
let mut downgrade_headers = HeaderMap::from_iter([(
REFERER,
HeaderValue::from_static("https://stale.example/path?secret=value"),
)]);
let downgrade = reqwest::Url::parse("http://other.example/next").expect("valid URL");
insert_referer(&mut downgrade_headers, &previous, &downgrade);
assert_eq!(downgrade_headers.get(REFERER), None);
}
#[test]
fn non_replayable_redirect_is_not_followed_regardless_of_target_scheme() {
let next_url = reqwest::Url::parse("ftp://example.com/next").expect("valid URL");
let redirected = redirect_request(
StatusCode::TEMPORARY_REDIRECT,
Method::POST,
HeaderMap::new(),
http::Version::HTTP_11,
/*timeout*/ None,
/*replay*/ None,
next_url,
);
assert!(redirected.is_none());
}
#[test]
fn redirect_credentials_are_retained_only_for_the_same_origin() {
for (previous, next, retain_credentials) in [
(
"https://example.com:8080/start",
"https://example.com:8080/next",
true,
),
(
"https://example.com:8080/start",
"http://example.com:8080/next",
false,
),
(
"https://example.com:8080/start",
"https://other.example:8080/next",
false,
),
(
"https://example.com:8080/start",
"https://example.com:8081/next",
false,
),
] {
let previous = reqwest::Url::parse(previous).expect("previous URL should parse");
let next = reqwest::Url::parse(next).expect("next URL should parse");
let mut headers = HeaderMap::from_iter([
(AUTHORIZATION, HeaderValue::from_static("Bearer secret")),
(COOKIE, HeaderValue::from_static("session=secret")),
]);
remove_sensitive_headers(
&mut headers,
&previous,
&next,
/*protect_sensitive_headers*/ false,
);
assert_eq!(
(
headers.contains_key(AUTHORIZATION),
headers.contains_key(COOKIE),
),
(retain_credentials, retain_credentials),
"credential handling for {previous} -> {next}"
);
}
}

View File

@@ -0,0 +1,546 @@
use std::io;
use std::io::Read;
use std::io::Write;
use std::net::TcpListener;
use std::sync::Arc;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use bytes::Bytes;
use futures::stream;
use pretty_assertions::assert_eq;
use rcgen::CertifiedKey;
use rcgen::generate_simple_self_signed;
use rustls_pki_types::PrivateKeyDer;
use super::ClientRouteClass;
use super::HttpClientFactory;
use super::Method;
use super::OutboundProxyPolicy;
use super::OutboundProxyRoute;
use super::RouteAwareClientPool;
use super::RouteAwareRequestError;
use super::SelectedTlsBackend;
use crate::client::RequestLogging;
use crate::client::TransportClient;
use crate::tls_backend_fallback::should_retry_with_rustls;
const PROTOCOL_VERSION_TLS_ALERT: &[u8] = &[21, 3, 3, 0, 2, 2, 70];
// Schannel ARM needs TLS 1.1 to expose the protocol-version alert; the x64 CI image
// disables TLS 1.1, so x64 and other platforms retain TLS 1.2.
#[cfg(all(windows, target_arch = "aarch64"))]
const NATIVE_TLS_TEST_VERSION: reqwest::tls::Version = reqwest::tls::Version::TLS_1_1;
#[cfg(not(all(windows, target_arch = "aarch64")))]
const NATIVE_TLS_TEST_VERSION: reqwest::tls::Version = reqwest::tls::Version::TLS_1_2;
type SuccessfulTlsFallbackServer = (
String,
TransportClient,
mpsc::Receiver<io::Result<Vec<String>>>,
);
#[tokio::test]
async fn default_pool_does_not_retry_a_native_tls_protocol_failure() {
let (url, attempts, stop_server) =
spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2)
.expect("TLS rejection server should start");
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Other,
);
use_native_tls_for_direct_route(&pool);
let request = reqwest::Request::new(
Method::POST,
reqwest::Url::parse(&url).expect("valid HTTPS URL"),
);
let error = pool
.send_with_resolver(request, |_| async { Ok(OutboundProxyRoute::Direct) })
.await
.expect_err("ordinary traffic should preserve the native TLS failure");
let _ = stop_server.send(());
assert!(error.is_connect());
assert_eq!(
attempts
.recv()
.expect("TLS server should finish")
.expect("TLS server should reject one connection"),
1
);
}
#[tokio::test]
async fn retries_a_native_tls_protocol_failure_once_with_rustls() {
let (url, attempts, stop_server) =
spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2)
.expect("TLS rejection server should start");
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Other,
)
.with_tls_backend_fallback();
use_native_tls_for_direct_route(&pool);
let destination = reqwest::Url::parse(&url).expect("valid HTTPS URL");
let mut request = reqwest::Request::new(Method::POST, destination.clone());
*request.body_mut() = Some(Bytes::from_static(b"mcp-initialize").into());
let error = pool
.send_with_resolver(request, |_| async { Ok(OutboundProxyRoute::Direct) })
.await
.expect_err("both TLS handshakes should be rejected");
let _ = stop_server.send(());
assert!(error.is_connect());
assert_eq!(
attempts
.recv()
.expect("TLS server should finish")
.expect("TLS server should reject both connections"),
2,
"native TLS protocol failure should retry with rustls: {error:?}"
);
let rustls_clients = pool.rustls_clients.as_ref().expect("TLS fallback cache");
assert_eq!(
(
rustls_clients.requires_rustls(&destination, &OutboundProxyRoute::Direct),
rustls_clients
.client_for_route(&OutboundProxyRoute::Direct)
.is_some(),
),
(false, false)
);
}
#[tokio::test]
async fn retries_a_native_tls_failure_after_another_request_caches_rustls() {
let (url, attempts, stop_server) =
spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2)
.expect("TLS rejection server should start");
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Other,
)
.with_tls_backend_fallback();
use_native_tls_for_direct_route(&pool);
let destination = reqwest::Url::parse(&url).expect("valid HTTPS URL");
let (route, native_client, selected_tls_backend) = pool
.client_for_url_with_resolver(destination.as_str(), |_| async {
Ok(OutboundProxyRoute::Direct)
})
.await
.expect("native TLS client should resolve");
assert_eq!(selected_tls_backend, SelectedTlsBackend::TransportDefault);
let request = reqwest::Request::new(Method::POST, destination.clone());
let replay = request.try_clone().expect("request should be replayable");
let error = native_client
.execute_without_request_logging(request)
.await
.expect_err("native TLS handshake should fail");
let rustls_client = pool
.rustls_client_for_route(&route)
.expect("rustls fallback client should build");
pool.rustls_clients
.as_ref()
.expect("TLS fallback cache")
.remember(&destination, &route, rustls_client);
let error = pool
.retry_with_rustls(
&route,
selected_tls_backend,
Some(&replay),
#[cfg(windows)]
/*proxy_pipe*/
None,
error,
/*timeout_deadline*/ None,
)
.await
.expect_err("both TLS handshakes should be rejected");
let _ = stop_server.send(());
assert!(error.is_connect());
assert_eq!(
attempts
.recv()
.expect("TLS server should finish")
.expect("TLS server should reject both connections"),
2,
"an in-flight native TLS failure should retry despite a concurrent cache update"
);
}
#[tokio::test]
async fn does_not_retry_a_cached_rustls_tls_protocol_failure() {
let (url, attempts, stop_server) =
spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2)
.expect("TLS rejection server should start");
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Other,
)
.with_tls_backend_fallback();
let destination = reqwest::Url::parse(&url).expect("valid HTTPS URL");
let rustls_client = pool
.rustls_client_for_route(&OutboundProxyRoute::Direct)
.expect("rustls fallback client should build");
pool.rustls_clients
.as_ref()
.expect("TLS fallback cache")
.remember(&destination, &OutboundProxyRoute::Direct, rustls_client);
let request = reqwest::Request::new(Method::POST, destination);
let error = pool
.send_with_resolver(request, |_| async { Ok(OutboundProxyRoute::Direct) })
.await
.expect_err("cached rustls TLS handshake should fail");
let _ = stop_server.send(());
assert!(error.is_connect());
assert_eq!(
attempts
.recv()
.expect("TLS server should finish")
.expect("TLS server should reject one connection"),
1,
"a cached rustls client must not retry against itself"
);
}
#[tokio::test]
async fn successful_rustls_fallback_replays_the_request_and_reuses_the_destination() {
let (url, trusted_rustls_client, observed_requests) =
spawn_successful_tls_fallback_server().expect("TLS fallback server should start");
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Other,
)
.with_tls_backend_fallback();
use_native_tls_for_direct_route(&pool);
let destination = reqwest::Url::parse(&url).expect("valid HTTPS URL");
let existing_destination =
reqwest::Url::parse("https://another-mcp.example.com/mcp").expect("valid HTTPS URL");
let rustls_clients = pool.rustls_clients.as_ref().expect("TLS fallback cache");
// Another destination may already have established a trusted rustls client on this route.
// The test destination must still attempt native TLS before reusing that route-level client.
rustls_clients.remember(
&existing_destination,
&OutboundProxyRoute::Direct,
trusted_rustls_client,
);
assert!(!rustls_clients.requires_rustls(&destination, &OutboundProxyRoute::Direct));
let mut initialize_request = reqwest::Request::new(Method::POST, destination.clone());
*initialize_request.body_mut() = Some(Bytes::from_static(b"mcp-initialize").into());
let initialize_response = pool
.send_with_resolver(initialize_request, |_| async {
Ok(OutboundProxyRoute::Direct)
})
.await
.expect("native TLS protocol failure should recover with rustls");
assert_eq!(
initialize_response
.text()
.await
.expect("fallback response body should be readable"),
"ok"
);
assert!(rustls_clients.requires_rustls(&destination, &OutboundProxyRoute::Direct));
let mut tool_request = reqwest::Request::new(Method::POST, destination);
*tool_request.body_mut() = Some(Bytes::from_static(b"mcp-tool-call").into());
let tool_response = pool
.send_with_resolver(tool_request, |_| async { Ok(OutboundProxyRoute::Direct) })
.await
.expect("remembered destination should reuse rustls without another native TLS attempt");
assert_eq!(
tool_response
.text()
.await
.expect("cached rustls response body should be readable"),
"ok"
);
assert_eq!(
observed_requests
.recv_timeout(Duration::from_secs(5))
.expect("TLS fallback server should finish")
.expect("TLS fallback server should capture both requests"),
vec!["mcp-initialize".to_string(), "mcp-tool-call".to_string()]
);
}
#[tokio::test]
async fn retries_a_tls_protocol_failure_when_request_url_contains_certificate_markers() {
let (url, attempts, stop_server) =
spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2)
.expect("TLS rejection server should start");
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Other,
)
.with_tls_backend_fallback();
use_native_tls_for_direct_route(&pool);
let mut destination = reqwest::Url::parse(&url).expect("valid HTTPS URL");
destination.set_path("/certificate/hostname/expired/revoked/mcp");
let request = reqwest::Request::new(Method::POST, destination);
let error = pool
.send_with_resolver(request, |_| async { Ok(OutboundProxyRoute::Direct) })
.await
.expect_err("both TLS handshakes should be rejected");
let _ = stop_server.send(());
assert!(error.is_connect());
assert_eq!(
attempts
.recv()
.expect("TLS server should finish")
.expect("TLS server should reject both connections"),
2,
"request URL text should not prevent TLS backend fallback: {error:?}"
);
}
#[tokio::test]
async fn does_not_retry_a_non_replayable_streaming_request() {
let (url, attempts, stop_server) =
spawn_protocol_version_rejection_server(/*maximum_attempts*/ 2)
.expect("TLS rejection server should start");
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Other,
)
.with_tls_backend_fallback();
use_native_tls_for_direct_route(&pool);
let mut request = reqwest::Request::new(
Method::POST,
reqwest::Url::parse(&url).expect("valid HTTPS URL"),
);
*request.body_mut() = Some(reqwest::Body::wrap_stream(stream::iter(vec![Ok::<
_,
io::Error,
>(
Bytes::from_static(b"streaming body"),
)])));
let error = pool
.send_with_resolver(request, |_| async { Ok(OutboundProxyRoute::Direct) })
.await
.expect_err("non-replayable request should preserve the native TLS failure");
let _ = stop_server.send(());
assert!(error.is_connect());
let RouteAwareRequestError::Request(ref request_error) = error else {
panic!("expected native TLS request error, got {error:?}");
};
assert!(
should_retry_with_rustls(request_error),
"native TLS protocol failure should be retryable: {request_error:?}"
);
assert_eq!(
attempts
.recv()
.expect("TLS server should finish")
.expect("TLS server should reject one connection"),
1
);
}
fn use_native_tls_for_direct_route(pool: &RouteAwareClientPool) {
// Start with reqwest's default native backend even when the environment supplies a CA bundle.
let client = reqwest::Client::builder()
.no_proxy()
.min_tls_version(NATIVE_TLS_TEST_VERSION)
.max_tls_version(NATIVE_TLS_TEST_VERSION)
.build()
.expect("native TLS client should build");
pool.clients.lock().expect("client cache lock").insert(
OutboundProxyRoute::Direct,
TransportClient::new(client, RequestLogging::Enabled, http::HeaderMap::new()),
);
}
fn spawn_successful_tls_fallback_server() -> io::Result<SuccessfulTlsFallbackServer> {
codex_utils_rustls_provider::ensure_rustls_crypto_provider();
let CertifiedKey { cert, signing_key } =
generate_simple_self_signed(vec!["127.0.0.1".to_string()]).map_err(io::Error::other)?;
let certificate = cert.der().clone();
let private_key = PrivateKeyDer::from(signing_key);
let tls_config = Arc::new(
rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(vec![certificate.clone()], private_key)
.map_err(io::Error::other)?,
);
let trusted_rustls_client = TransportClient::new(
reqwest::Client::builder()
.use_rustls_tls()
.add_root_certificate(
reqwest::Certificate::from_der(certificate.as_ref()).map_err(io::Error::other)?,
)
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(io::Error::other)?,
RequestLogging::Enabled,
http::HeaderMap::new(),
);
let listener = TcpListener::bind(("127.0.0.1", 0))?;
let address = listener.local_addr()?;
listener.set_nonblocking(true)?;
let (requests_tx, requests_rx) = mpsc::channel();
thread::spawn(move || {
let result = (|| -> io::Result<Vec<String>> {
let mut observed_requests = Vec::new();
for connection_index in 0..3 {
let deadline = Instant::now() + Duration::from_secs(5);
let mut stream = loop {
match listener.accept() {
Ok((stream, _)) => break stream,
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
if Instant::now() >= deadline {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"timed out waiting for the TLS fallback client",
));
}
thread::sleep(Duration::from_millis(10));
}
Err(error) => return Err(error),
}
};
stream.set_nonblocking(false)?;
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
stream.set_write_timeout(Some(Duration::from_secs(5)))?;
if connection_index == 0 {
let mut client_hello = [0_u8; 2_048];
if stream.read(&mut client_hello)? == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"native TLS peer closed before sending a ClientHello",
));
}
stream.write_all(PROTOCOL_VERSION_TLS_ALERT)?;
stream.flush()?;
continue;
}
let connection = rustls::ServerConnection::new(Arc::clone(&tls_config))
.map_err(io::Error::other)?;
let mut tls = rustls::StreamOwned::new(connection, stream);
let mut request = Vec::new();
let mut chunk = [0_u8; 1_024];
let header_end = loop {
let bytes_read = tls.read(&mut chunk)?;
if bytes_read == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"rustls peer closed before sending HTTP headers",
));
}
request.extend_from_slice(&chunk[..bytes_read]);
if let Some(header_end) =
request.windows(4).position(|window| window == b"\r\n\r\n")
{
break header_end + 4;
}
};
let headers =
std::str::from_utf8(&request[..header_end]).map_err(io::Error::other)?;
let content_length = headers
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then_some(value.trim())
})
.ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "missing Content-Length")
})?
.parse::<usize>()
.map_err(io::Error::other)?;
while request.len() < header_end + content_length {
let bytes_read = tls.read(&mut chunk)?;
if bytes_read == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"rustls peer closed before sending the HTTP body",
));
}
request.extend_from_slice(&chunk[..bytes_read]);
}
let body = std::str::from_utf8(&request[header_end..header_end + content_length])
.map_err(io::Error::other)?;
observed_requests.push(body.to_string());
tls.write_all(
b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
)?;
tls.flush()?;
}
Ok(observed_requests)
})();
let _ = requests_tx.send(result);
});
Ok((
format!("https://{address}/mcp"),
trusted_rustls_client,
requests_rx,
))
}
fn spawn_protocol_version_rejection_server(
maximum_attempts: usize,
) -> io::Result<(String, mpsc::Receiver<io::Result<usize>>, mpsc::Sender<()>)> {
let listener = TcpListener::bind(("127.0.0.1", 0))?;
let address = listener.local_addr()?;
listener.set_nonblocking(true)?;
let (attempts_tx, attempts_rx) = mpsc::channel();
let (stop_tx, stop_rx) = mpsc::channel();
thread::spawn(move || {
let result = (|| -> io::Result<usize> {
let mut attempts = 0;
let deadline = Instant::now() + Duration::from_secs(5);
while attempts < maximum_attempts && Instant::now() < deadline {
if stop_rx.try_recv().is_ok() {
break;
}
match listener.accept() {
Ok((mut stream, _)) => {
stream.set_nonblocking(false)?;
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
let mut client_hello = [0_u8; 2_048];
if stream.read(&mut client_hello)? == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"TLS peer closed before sending a ClientHello",
));
}
stream.write_all(PROTOCOL_VERSION_TLS_ALERT)?;
attempts += 1;
}
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(10));
}
Err(error) => return Err(error),
}
}
Ok(attempts)
})();
let _ = attempts_tx.send(result);
});
Ok((format!("https://{address}/mcp"), attempts_rx, stop_tx))
}

View File

@@ -0,0 +1,156 @@
//! Narrow TLS backend fallback for delegated requests that select their route per destination.
//!
//! Native TLS remains the default. A recognized connection-time protocol negotiation failure can
//! select rustls for one HTTPS origin and outbound route without changing other destinations.
use std::collections::HashMap;
use std::collections::HashSet;
use std::error::Error;
use std::sync::Arc;
use std::sync::Mutex;
use crate::OutboundProxyRoute;
use crate::client::TransportClient;
const MAX_CACHED_RUSTLS_DESTINATIONS: usize = 16;
// Schannel maps TLS alert 70 (protocol_version) to SEC_E_UNSUPPORTED_FUNCTION.
const SCHANNEL_PROTOCOL_VERSION_ERROR: i32 = 0x8009_0302_u32 as i32;
#[derive(Clone, Default)]
pub(crate) struct RustlsClientCache {
state: Arc<Mutex<RustlsClientCacheState>>,
}
#[derive(Default)]
struct RustlsClientCacheState {
destinations: HashSet<DestinationRoute>,
clients: HashMap<OutboundProxyRoute, TransportClient>,
}
#[derive(Clone, Hash, PartialEq, Eq)]
struct DestinationRoute {
host: String,
port: u16,
route: OutboundProxyRoute,
}
impl RustlsClientCache {
pub(crate) fn requires_rustls(&self, url: &reqwest::Url, route: &OutboundProxyRoute) -> bool {
let Some(destination) = DestinationRoute::new(url, route) else {
return false;
};
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.destinations
.contains(&destination)
}
pub(crate) fn client_for_route(&self, route: &OutboundProxyRoute) -> Option<TransportClient> {
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clients
.get(route)
.cloned()
}
pub(crate) fn remember(
&self,
url: &reqwest::Url,
route: &OutboundProxyRoute,
client: TransportClient,
) {
let Some(destination) = DestinationRoute::new(url, route) else {
return;
};
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state.destinations.contains(&destination) {
return;
}
if state.destinations.len() >= MAX_CACHED_RUSTLS_DESTINATIONS
&& let Some(destination_to_evict) = state.destinations.iter().next().cloned()
{
state.destinations.remove(&destination_to_evict);
if !state
.destinations
.iter()
.any(|destination| destination.route == destination_to_evict.route)
{
state.clients.remove(&destination_to_evict.route);
}
}
state.clients.entry(route.clone()).or_insert(client);
state.destinations.insert(destination);
}
}
impl DestinationRoute {
fn new(url: &reqwest::Url, route: &OutboundProxyRoute) -> Option<Self> {
if url.scheme() != "https" {
return None;
}
Some(Self {
host: url.host_str()?.to_ascii_lowercase(),
port: url.port_or_known_default()?,
route: route.clone(),
})
}
}
pub(crate) fn should_retry_with_rustls(error: &reqwest::Error) -> bool {
error.is_connect() && !error.is_timeout() && error.source().is_some_and(has_retryable_tls_error)
}
fn has_retryable_tls_error(error: &(dyn Error + 'static)) -> bool {
let mut source = Some(error);
let mut recognized_negotiation_failure = false;
while let Some(error) = source {
let message = error.to_string().to_ascii_lowercase();
if [
"certificate",
"unknown issuer",
"unknown ca",
"untrusted",
"self signed",
"self-signed",
"hostname",
"expired",
"revoked",
]
.iter()
.any(|marker| message.contains(marker))
{
return false;
}
// macOS Secure Transport reports the protocol alert as "bad protocol version".
let is_macos_protocol_version_error = message.contains("bad protocol version");
// Linux OpenSSL reports the peer's "tlsv1 alert protocol version".
let is_linux_protocol_version_error = message.contains("tlsv1 alert protocol version");
// Windows Schannel may expose the protocol alert as a raw or formatted OS error.
let is_schannel_protocol_version_error = error
.downcast_ref::<std::io::Error>()
.and_then(std::io::Error::raw_os_error)
== Some(SCHANNEL_PROTOCOL_VERSION_ERROR)
|| message.contains("(os error -2146893054)")
|| message.contains("0x80090302");
if is_macos_protocol_version_error
|| is_linux_protocol_version_error
|| is_schannel_protocol_version_error
{
recognized_negotiation_failure = true;
}
source = error.source();
}
recognized_negotiation_failure
}
#[cfg(test)]
#[path = "tls_backend_fallback_tests.rs"]
mod tests;

View File

@@ -0,0 +1,215 @@
use std::io;
use pretty_assertions::assert_eq;
use super::MAX_CACHED_RUSTLS_DESTINATIONS;
use super::RustlsClientCache;
use super::SCHANNEL_PROTOCOL_VERSION_ERROR;
use super::has_retryable_tls_error;
use crate::HttpClientBuilder;
use crate::OutboundProxyRoute;
#[test]
fn recognizes_platform_specific_tls_protocol_negotiation_failures() {
let errors = [
("client error (Connect): bad protocol version", true),
("BAD PROTOCOL VERSION", true),
(
"error:0A00042E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version",
true,
),
("TLSV1 ALERT PROTOCOL VERSION", true),
(
"The function requested is not supported. (os error -2146893054)",
true,
),
("Schannel protocol error 0x80090302", true),
("SCHANNEL PROTOCOL ERROR 0X80090302", true),
("certificate validation failed: bad protocol version", false),
("bad protocol version: certificate has expired", false),
(
"certificate validation failed: tlsv1 alert protocol version",
false,
),
(
"tlsv1 alert protocol version: certificate has expired",
false,
),
(
"certificate validation failed (os error -2146893054)",
false,
),
("certificate validation failed: 0x80090302", false),
("unknown issuer", false),
("self-signed certificate", false),
("hostname mismatch", false),
("connection refused", false),
("connection reset", false),
("dns lookup failed", false),
("tls handshake failed", false),
("unsupported protocol", false),
("wrong version number", false),
("The function requested is not supported.", false),
(
"The client and server cannot communicate. (os error -2146893007)",
false,
),
("operation timed out", false),
("407 Proxy Authentication Required", false),
];
for (message, expected) in errors {
let error = io::Error::other(message);
assert_eq!(has_retryable_tls_error(&error), expected, "{message}");
}
}
#[test]
fn recognizes_schannel_protocol_version_error_codes() {
let protocol_error = io::Error::from_raw_os_error(SCHANNEL_PROTOCOL_VERSION_ERROR);
let another_schannel_error = io::Error::from_raw_os_error(/*code*/ -2_146_893_007);
assert_eq!(
(
has_retryable_tls_error(&protocol_error),
has_retryable_tls_error(&another_schannel_error),
),
(true, false)
);
}
#[test]
fn certificate_errors_in_an_error_source_never_enable_fallback() {
for message in [
"certificate verification failed: bad protocol version",
"certificate verification failed: tlsv1 alert protocol version",
"certificate verification failed (os error -2146893054)",
"certificate verification failed: 0x80090302",
] {
let error = io::Error::other(io::Error::other(message));
assert!(!has_retryable_tls_error(&error), "{message}");
}
}
#[test]
fn rustls_fallback_decisions_are_scoped_to_origin_and_outbound_route() {
let cache = RustlsClientCache::default();
let destination = reqwest::Url::parse("https://mcp.example.com/first").expect("valid URL");
let same_origin = reqwest::Url::parse("https://mcp.example.com/second").expect("valid URL");
let another_host = reqwest::Url::parse("https://another.example.com/first").expect("valid URL");
let another_port =
reqwest::Url::parse("https://mcp.example.com:8443/first").expect("valid URL");
let insecure = reqwest::Url::parse("http://mcp.example.com/first").expect("valid URL");
let direct = OutboundProxyRoute::Direct;
let proxy = OutboundProxyRoute::Proxy {
url: "http://proxy.example.com".to_string(),
no_proxy: None,
};
let client = direct_rustls_client();
cache.remember(&destination, &direct, client);
assert_eq!(
[
cache.requires_rustls(&destination, &direct),
cache.requires_rustls(&same_origin, &direct),
cache.requires_rustls(&another_host, &direct),
cache.requires_rustls(&another_port, &direct),
cache.requires_rustls(&destination, &proxy),
cache.requires_rustls(&insecure, &direct),
],
[true, true, false, false, false, false]
);
}
#[test]
fn cached_rustls_clients_are_reused_for_the_same_outbound_route() {
let cache = RustlsClientCache::default();
let first_destination =
reqwest::Url::parse("https://first.example.com").expect("valid first URL");
let second_destination =
reqwest::Url::parse("https://second.example.com").expect("valid second URL");
let direct = OutboundProxyRoute::Direct;
let client = direct_rustls_client();
cache.remember(&first_destination, &direct, client.clone());
cache.remember(&second_destination, &direct, client);
assert_eq!(
(
cache.requires_rustls(&first_destination, &direct),
cache.requires_rustls(&second_destination, &direct),
cache.client_for_route(&direct).is_some(),
cache
.state
.lock()
.expect("rustls client cache lock")
.clients
.len(),
),
(true, true, true, 1)
);
}
#[test]
fn cached_rustls_destinations_remain_bounded_while_sharing_a_route_client() {
let cache = RustlsClientCache::default();
let client = direct_rustls_client();
for index in 0..=MAX_CACHED_RUSTLS_DESTINATIONS {
let destination =
reqwest::Url::parse(&format!("https://mcp-{index}.example.com")).expect("valid URL");
cache.remember(&destination, &OutboundProxyRoute::Direct, client.clone());
}
let state = cache.state.lock().expect("rustls client cache lock");
assert_eq!(
(state.destinations.len(), state.clients.len()),
(MAX_CACHED_RUSTLS_DESTINATIONS, 1)
);
}
#[test]
fn evicting_a_destination_removes_its_unshared_route_client() {
let cache = RustlsClientCache::default();
let client = direct_rustls_client();
for index in 0..=MAX_CACHED_RUSTLS_DESTINATIONS {
let destination =
reqwest::Url::parse(&format!("https://mcp-{index}.example.com")).expect("valid URL");
let route = OutboundProxyRoute::Proxy {
url: format!("http://proxy-{index}.example.com"),
no_proxy: None,
};
cache.remember(&destination, &route, client.clone());
}
let state = cache.state.lock().expect("rustls client cache lock");
assert_eq!(
(
state.destinations.len(),
state.clients.len(),
state
.destinations
.iter()
.all(|destination| state.clients.contains_key(&destination.route)),
),
(
MAX_CACHED_RUSTLS_DESTINATIONS,
MAX_CACHED_RUSTLS_DESTINATIONS,
true,
)
);
}
fn direct_rustls_client() -> crate::client::TransportClient {
HttpClientBuilder::new()
.with_rustls_tls()
.build_for_resolved_route(
&crate::HttpClientFactory::new(crate::OutboundProxyPolicy::ReqwestDefault),
crate::ClientRouteClass::Api,
&OutboundProxyRoute::Direct,
)
.expect("rustls client should build without proxy autodiscovery")
}

View File

@@ -0,0 +1,318 @@
//! Shared HTTP transport for fixed clients and route-aware pools, with optional response limits.
//!
//! Each request's limit applies to observed body bytes, including unsuccessful responses;
//! declared content lengths are only an additional early-rejection check.
use crate::HttpResponse;
use crate::RouteAwareClientPool;
use crate::RouteAwareRequestError;
use crate::client::HttpClient;
use crate::client::HttpClientBackend;
use crate::error::TransportError;
use crate::request::Request;
use crate::request::RequestBody;
use crate::request::Response;
use crate::request_draft::RequestDraft;
use crate::retry_after::RetryAfter;
use bytes::Bytes;
use bytes::BytesMut;
use futures::StreamExt;
use futures::stream::BoxStream;
use http::HeaderMap;
use http::Method;
use http::StatusCode;
use tracing::Level;
use tracing::enabled;
use tracing::trace;
pub type ByteStream = BoxStream<'static, Result<Bytes, TransportError>>;
pub struct StreamResponse {
pub status: StatusCode,
pub headers: HeaderMap,
pub bytes: ByteStream,
}
pub trait HttpTransport: Send + Sync {
fn execute(
&self,
req: Request,
) -> impl std::future::Future<Output = Result<Response, TransportError>> + Send;
fn stream(
&self,
req: Request,
) -> impl std::future::Future<Output = Result<StreamResponse, TransportError>> + Send;
}
#[derive(Clone, Debug)]
pub struct ReqwestTransport {
client: TransportClient,
}
#[derive(Clone, Debug)]
enum TransportClient {
Fixed(HttpClient),
RouteAware(Box<RouteAwareClientPool>),
}
impl ReqwestTransport {
pub fn new(client: reqwest::Client) -> Self {
Self::from_http_client(HttpClient::new(client))
}
pub fn from_http_client(client: HttpClient) -> Self {
Self {
client: TransportClient::Fixed(client),
}
}
/// Uses the pool to resolve the route for every request and redirect URL.
pub fn from_route_aware_client_pool(client: RouteAwareClientPool) -> Self {
Self {
client: TransportClient::RouteAware(Box::new(client)),
}
}
async fn send(&self, req: Request) -> Result<HttpResponse, TransportError> {
let prepared = req.prepare_body_for_send().map_err(TransportError::Build)?;
let Request {
method,
url,
headers: _,
body: _,
compression: _,
timeout,
response_body_limit_bytes: _,
} = req;
let method = Method::from_bytes(method.as_str().as_bytes()).unwrap_or(Method::GET);
let mut request =
RequestDraft::new(method, url).map_err(|error| Self::map_error(error.into()))?;
request.extend_headers(prepared.headers);
*request.request.timeout_mut() = timeout;
*request.request.body_mut() = prepared.body.map(Into::into);
match &self.client {
TransportClient::Fixed(client) => match &client.backend {
HttpClientBackend::Routed(pool) => pool
.send(request)
.await
.map_err(Self::map_route_aware_error),
HttpClientBackend::Direct(client) => {
let request = request
.build(client)
.map_err(|error| Self::map_error(error.into()))?;
client
.execute(request)
.await
.map(HttpResponse::from)
.map_err(|error| Self::map_error(error.into()))
}
},
TransportClient::RouteAware(client) => client
.send(request)
.await
.map_err(Self::map_route_aware_error),
}
}
fn map_error(err: crate::HttpError) -> TransportError {
let err = err.without_url();
if let crate::HttpError::Policy(denied) = err {
TransportError::Policy(denied)
} else if err.is_connect() {
TransportError::Connection(err.without_url())
} else if err.is_timeout() {
TransportError::Timeout
} else {
TransportError::Network(err.to_string())
}
}
fn map_route_aware_error(error: RouteAwareRequestError) -> TransportError {
match error.without_url() {
RouteAwareRequestError::Policy(denied) => TransportError::Policy(denied),
RouteAwareRequestError::Request(error) => Self::map_error(error.into()),
RouteAwareRequestError::Timeout => TransportError::Timeout,
RouteAwareRequestError::Route(error) => TransportError::Build(error.to_string()),
RouteAwareRequestError::Build(error) => TransportError::Build(error),
error @ (RouteAwareRequestError::UnsupportedRedirectScheme(_)
| RouteAwareRequestError::TooManyRedirects) => {
TransportError::Network(error.to_string())
}
}
}
fn trace_request(&self, req: &Request) {
let request_logging_enabled = match &self.client {
TransportClient::Fixed(client) => client.request_logging_enabled(),
TransportClient::RouteAware(client) => client.request_logging_enabled(),
};
if request_logging_enabled && enabled!(Level::TRACE) {
trace!(
"{} to {}: {}",
req.method,
req.url,
request_body_for_trace(req)
);
}
}
}
fn request_body_for_trace(req: &Request) -> String {
match req.body.as_ref() {
Some(RequestBody::Json(body)) => body.to_string(),
Some(RequestBody::EncodedJson(body)) => {
String::from_utf8_lossy(body.trace_bytes()).into_owned()
}
Some(RequestBody::Raw(body)) => format!("<raw body: {} bytes>", body.len()),
None => String::new(),
}
}
impl HttpTransport for ReqwestTransport {
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
self.trace_request(&req);
let url = req.url.clone();
let response_body_limit_bytes = req.response_body_limit_bytes;
let resp = self.send(req).await?;
let status = resp.status();
let headers = resp.headers().clone();
let retry_after = RetryAfter::from_headers(&headers);
let bytes = match response_body_limit_bytes {
Some(max_bytes) => bounded_response_bytes(resp, max_bytes).await,
None => resp.bytes().await.map_err(Self::map_error),
};
if !status.is_success() {
let body = match bytes {
Ok(bytes) => String::from_utf8(bytes.to_vec()).ok(),
Err(
error @ (TransportError::ResponseTooLarge { .. } | TransportError::Policy(_)),
) => return Err(error),
// Keep bounded diagnostic-body failures from hiding HTTP auth/retry status.
Err(_) if response_body_limit_bytes.is_some() => None,
// TODO(anp): Preserve retry advice on body failures without changing their
// network/timeout classification to HTTP status handling.
Err(error) => return Err(error),
};
return Err(TransportError::Http {
status,
url: Some(url),
headers: Some(headers),
body,
retry_after,
});
}
Ok(Response {
status,
headers,
body: bytes?,
})
}
async fn stream(&self, req: Request) -> Result<StreamResponse, TransportError> {
self.trace_request(&req);
let url = req.url.clone();
let response_body_limit_bytes = req.response_body_limit_bytes;
let resp = self.send(req).await?;
let status = resp.status();
let headers = resp.headers().clone();
if !status.is_success() {
let retry_after = RetryAfter::from_headers(&headers);
let body = match response_body_limit_bytes {
Some(max_bytes) => match bounded_response_bytes(resp, max_bytes).await {
Ok(bytes) => {
// Reuse the unbounded path's charset, BOM and replacement decoding,
// but only after the body has passed the byte limit.
let mut buffered = http::Response::new(bytes);
*buffered.headers_mut() = headers.clone();
reqwest::Response::from(buffered).text().await.ok()
}
Err(
error @ (TransportError::ResponseTooLarge { .. }
| TransportError::Policy(_)),
) => return Err(error),
// A failed diagnostic body must not hide HTTP auth or retry semantics.
Err(_) => None,
},
None => match resp.text().await {
Err(crate::HttpError::Policy(denied)) => return Err(denied.into()),
body => body.ok(),
},
};
return Err(TransportError::Http {
status,
url: Some(url),
headers: Some(headers),
body,
retry_after,
});
}
let bytes = match response_body_limit_bytes {
Some(max_bytes) => bounded_response_stream(resp, max_bytes)?,
None => Box::pin(
resp.bytes_stream()
.map(|result| result.map_err(Self::map_error)),
),
};
Ok(StreamResponse {
status,
headers,
bytes,
})
}
}
fn bounded_response_stream(
response: HttpResponse,
max_bytes: usize,
) -> Result<ByteStream, TransportError> {
if response
.content_length()
.is_some_and(|length| length > max_bytes as u64)
{
return Err(TransportError::ResponseTooLarge { max_bytes });
}
let stream = futures::stream::try_unfold(
(response, max_bytes),
move |(mut response, remaining)| async move {
match response
.chunk()
.await
.map_err(|error| ReqwestTransport::map_error(error.without_url()))?
{
Some(chunk) if chunk.len() <= remaining => {
let remaining = remaining - chunk.len();
Ok(Some((chunk, (response, remaining))))
}
Some(_) => Err(TransportError::ResponseTooLarge { max_bytes }),
None => Ok(None),
}
},
);
Ok(Box::pin(stream))
}
pub async fn bounded_response_bytes(
response: HttpResponse,
max_bytes: usize,
) -> Result<Bytes, TransportError> {
let mut stream = bounded_response_stream(response, max_bytes)?;
let mut body = BytesMut::new();
while let Some(chunk) = stream.next().await {
body.extend_from_slice(&chunk?);
}
Ok(body.freeze())
}
#[cfg(test)]
#[path = "transport_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "transport_limit_tests.rs"]
mod limit_tests;

View File

@@ -0,0 +1,492 @@
//! HTTP fixtures exercise opt-in body limits for both buffered and streaming callers.
use super::*;
use pretty_assertions::assert_eq;
use std::io::Read;
use std::io::Write;
use std::net::TcpListener;
use std::net::TcpStream;
use std::time::Duration;
use std::time::Instant;
#[derive(Clone, Copy, Debug)]
enum Delivery {
Buffered,
Streamed,
}
#[tokio::test]
async fn accepts_complete_bodies_at_the_limit() {
for delivery in [Delivery::Buffered, Delivery::Streamed] {
for (framing, wire_body, max_bytes, expected_body) in [
("Content-Length: 4\r\n", "test", 4, "test"),
("", "test", 4, "test"),
(
"Transfer-Encoding: chunked\r\n",
"2\r\nte\r\n2\r\nst\r\n0\r\n\r\n",
4,
"test",
),
("Content-Length: 0\r\n", "", 0, ""),
] {
let response = receive_response(
format!("HTTP/1.1 200 OK\r\n{framing}Connection: close\r\n\r\n{wire_body}"),
&transport(),
Some(max_bytes),
delivery,
)
.await
.expect("a complete body within the limit should succeed");
let mut expected_headers = HeaderMap::new();
expected_headers.insert("connection", "close".parse().unwrap());
for line in framing.lines() {
let (name, value) = line.split_once(':').unwrap();
expected_headers.insert(
http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
value.trim().parse().unwrap(),
);
}
assert_eq!(
(response.status, response.headers, response.body),
(
StatusCode::OK,
expected_headers,
Bytes::copy_from_slice(expected_body.as_bytes()),
),
"{delivery:?} with framing {framing:?}",
);
}
}
}
#[tokio::test]
async fn rejects_oversized_success_and_error_bodies_without_sensitive_diagnostics() {
for delivery in [Delivery::Buffered, Delivery::Streamed] {
for status in ["200 OK", "500 Internal Server Error"] {
for (framing, wire_body) in [
("Content-Length: 11\r\n", "body-secret"),
("", "body-secret"),
(
"Transfer-Encoding: chunked\r\n",
"4\r\nbody\r\n7\r\n-secret\r\n0\r\n\r\n",
),
(
"Transfer-Encoding: chunked\r\nContent-Length: 1\r\n",
"4\r\nbody\r\n7\r\n-secret\r\n0\r\n\r\n",
),
] {
let error = receive_response(
format!(
"HTTP/1.1 {status}\r\n{framing}X-Secret: header-secret\r\nConnection: close\r\n\r\n{wire_body}"
),
&transport(),
Some(4),
delivery,
)
.await
.expect_err("the observed body must not exceed the limit");
assert_eq!(
(error.to_string(), format!("{error:?}")),
(
"response body exceeds the 4 byte limit".to_string(),
"ResponseTooLarge { max_bytes: 4 }".to_string(),
),
"{delivery:?}, {status}, framing {framing:?}",
);
}
}
}
}
#[tokio::test]
async fn rejects_oversized_declared_lengths_before_reading_the_body() {
for delivery in [Delivery::Buffered, Delivery::Streamed] {
for status in [
StatusCode::OK,
StatusCode::UNAUTHORIZED,
StatusCode::TOO_MANY_REQUESTS,
] {
let error = receive_response(
format!(
"HTTP/1.1 {status}\r\nContent-Length: 1000000\r\nConnection: close\r\n\r\n"
),
&transport(),
Some(4),
delivery,
)
.await
.expect_err("an oversized declaration should fail before the incomplete body");
assert!(matches!(
error,
TransportError::ResponseTooLarge { max_bytes: 4 }
));
}
}
}
#[tokio::test]
async fn bounded_stream_retains_account_revocation() {
let (finish, finished) = std::sync::mpsc::channel();
let (url, server) = start_server(move |connection| {
connection
.write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\npart\r\n")
.unwrap();
finished.recv().unwrap();
});
let controller = crate::NetworkPolicyController::default();
let policy = controller.policy();
assert!(controller.publish(policy.revision(), crate::DestinationPolicy::Unrestricted));
let factory = crate::HttpClientFactory::new(crate::OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy.clone().for_current_account());
let client = factory
.build_client(&url, crate::ClientRouteClass::Api)
.unwrap();
let transport = ReqwestTransport::from_http_client(client);
let mut request = Request::new(Method::GET, url);
request.response_body_limit_bytes = Some(5);
let mut response = transport.stream(request).await.unwrap();
assert_eq!(
response.bytes.next().await.unwrap().unwrap(),
Bytes::from_static(b"part")
);
policy.invalidate();
let error = tokio::time::timeout(Duration::from_secs(/*secs*/ 1), response.bytes.next())
.await
.unwrap()
.unwrap()
.unwrap_err();
assert!(matches!(
error,
TransportError::Policy(crate::NetworkPolicyDenied::Revoked)
));
assert!(response.bytes.next().await.is_none());
finish.send(()).unwrap();
server.join().unwrap();
}
#[tokio::test]
async fn streaming_limit_counts_across_chunks_and_terminates_on_error() {
let (continue_tx, continue_rx) = std::sync::mpsc::channel();
let (url, server) = start_server(move |connection| {
connection
.write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\npart\r\n")
.expect("write the first chunk");
continue_rx
.recv_timeout(Duration::from_secs(5))
.expect("client should consume the first chunk");
connection
.write_all(b"4\r\nnext\r\n0\r\n\r\n")
.expect("write the second chunk");
});
let mut request = Request::new(Method::GET, url);
request.response_body_limit_bytes = Some(6);
let mut response = transport()
.stream(request)
.await
.expect("stream should open before the body limit is reached");
assert_eq!(
response.bytes.next().await.unwrap().unwrap(),
Bytes::from_static(b"part"),
);
continue_tx.send(()).expect("release the second chunk");
let error = response
.bytes
.next()
.await
.expect("second chunk should produce the limit error")
.expect_err("two individually small chunks should exceed the total limit");
assert!(matches!(
error,
TransportError::ResponseTooLarge { max_bytes: 6 }
));
assert!(response.bytes.next().await.is_none());
server.join().expect("HTTP fixture should finish");
}
#[tokio::test]
async fn preserves_http_failures_within_the_limit() {
for delivery in [Delivery::Buffered, Delivery::Streamed] {
let error = receive_response(
"HTTP/1.1 403 Forbidden\r\nContent-Length: 6\r\nConnection: close\r\n\r\ndenied"
.to_string(),
&transport(),
Some(6),
delivery,
)
.await
.expect_err("a small error body should retain HTTP error semantics");
let TransportError::Http {
status,
headers,
body,
..
} = error
else {
panic!("expected HTTP error, got {error:?}");
};
assert_eq!(
(status, headers, body),
(
StatusCode::FORBIDDEN,
Some(HeaderMap::from_iter([
(http::header::CONTENT_LENGTH, "6".parse().unwrap()),
(http::header::CONNECTION, "close".parse().unwrap()),
])),
Some("denied".to_string()),
),
);
}
}
#[tokio::test]
async fn bounded_errors_preserve_status_when_the_body_is_interrupted() {
for delivery in [Delivery::Buffered, Delivery::Streamed] {
for status in [StatusCode::UNAUTHORIZED, StatusCode::TOO_MANY_REQUESTS] {
for max_bytes in [None, Some(5), Some(4), Some(3)] {
// The first chunk is complete, but the peer closes before the next chunk.
let error = receive_response(
format!(
"HTTP/1.1 {status}\r\nTransfer-Encoding: chunked\r\nRetry-After: 7\r\nWWW-Authenticate: Bearer\r\nConnection: close\r\n\r\n4\r\npart\r\n"
),
&transport(),
max_bytes,
delivery,
)
.await
.expect_err("an interrupted error body must still fail");
if matches!(delivery, Delivery::Buffered) && max_bytes.is_none() {
assert!(matches!(error, TransportError::Network(_)));
continue;
}
if max_bytes == Some(3) {
assert!(matches!(
error,
TransportError::ResponseTooLarge { max_bytes: 3 }
));
continue;
}
let TransportError::Http {
status: actual_status,
headers,
body,
..
} = error
else {
panic!("expected preserved HTTP error, got {error:?}");
};
assert_eq!(
(actual_status, headers, body),
(
status,
Some(HeaderMap::from_iter([
(http::header::TRANSFER_ENCODING, "chunked".parse().unwrap()),
(http::header::RETRY_AFTER, "7".parse().unwrap()),
(http::header::WWW_AUTHENTICATE, "Bearer".parse().unwrap()),
(http::header::CONNECTION, "close".parse().unwrap()),
])),
None,
),
"{delivery:?}, max_bytes={max_bytes:?}",
);
}
}
}
}
#[tokio::test]
async fn bounded_successes_report_interrupted_bodies_as_network_errors() {
for delivery in [Delivery::Buffered, Delivery::Streamed] {
let error = receive_response(
"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n4\r\npart\r\n"
.to_string(),
&transport(),
Some(4),
delivery,
)
.await
.expect_err("a successful status cannot hide an incomplete response body");
assert!(matches!(error, TransportError::Network(_)));
}
}
#[tokio::test]
async fn bounded_streamed_errors_preserve_text_decoding() {
for (content_type, bytes, expected) in [
(
"text/plain; charset=windows-1252",
[0x63, 0x61, 0x66, 0xe9].as_slice(),
"café",
),
(
"text/plain; charset=utf-8",
b"error: \xff".as_slice(),
"error: <20>",
),
(
"text/plain; charset=unknown",
b"error: \xff".as_slice(),
"error: <20>",
),
("text/plain", b"\xef\xbb\xbfdenied".as_slice(), "denied"),
] {
for bounded in [false, true] {
let mut wire = format!(
"HTTP/1.1 403 Forbidden\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
bytes.len()
)
.into_bytes();
wire.extend_from_slice(bytes);
let error = receive_response(
wire,
&transport(),
bounded.then_some(bytes.len()),
Delivery::Streamed,
)
.await
.expect_err("retain the HTTP error and decoded diagnostics");
let TransportError::Http {
status,
headers,
body,
..
} = error
else {
panic!("expected HTTP error, got {error:?}");
};
assert_eq!(
(status, headers, body),
(
StatusCode::FORBIDDEN,
Some(HeaderMap::from_iter([
(http::header::CONTENT_TYPE, content_type.parse().unwrap()),
(
http::header::CONTENT_LENGTH,
bytes.len().to_string().parse().unwrap()
),
(http::header::CONNECTION, "close".parse().unwrap()),
])),
Some(expected.to_string()),
),
"{content_type}, bounded={bounded}",
);
}
}
}
#[tokio::test]
async fn shared_transport_keeps_each_requests_response_limit_independent() {
let transport = transport();
for delivery in [Delivery::Buffered, Delivery::Streamed] {
for max_bytes in [Some(4), None, Some(11), Some(0), None] {
let response = receive_response(
"HTTP/1.1 200 OK\r\nContent-Length: 11\r\nConnection: close\r\n\r\nbody-secret"
.to_string(),
&transport,
max_bytes,
delivery,
)
.await;
match max_bytes {
Some(max_bytes) if max_bytes < 11 => assert!(matches!(
response,
Err(TransportError::ResponseTooLarge { max_bytes: actual }) if actual == max_bytes
)),
_ => assert_eq!(
response.expect("only this request's limit applies").body,
Bytes::from_static(b"body-secret"),
),
}
}
}
}
fn transport() -> ReqwestTransport {
ReqwestTransport::new(
reqwest::Client::builder()
.no_proxy()
.build()
.expect("test client should build"),
)
}
async fn receive_response(
wire_response: impl Into<Vec<u8>>,
transport: &ReqwestTransport,
response_body_limit_bytes: Option<usize>,
delivery: Delivery,
) -> Result<Response, TransportError> {
let wire_response = wire_response.into();
let (url, server) = start_server(move |connection| {
connection
.write_all(&wire_response)
.expect("write HTTP response");
});
let mut request = Request::new(Method::GET, url);
request.headers.insert(
http::header::AUTHORIZATION,
"Bearer auth-secret".parse().unwrap(),
);
request.timeout = Some(Duration::from_secs(5));
request.response_body_limit_bytes = response_body_limit_bytes;
let result = match delivery {
Delivery::Buffered => transport.execute(request).await,
Delivery::Streamed => {
async {
let mut response = transport.stream(request).await?;
let mut body = BytesMut::new();
while let Some(chunk) = response.bytes.next().await {
body.extend_from_slice(&chunk?);
}
Ok(Response {
status: response.status,
headers: response.headers,
body: body.freeze(),
})
}
.await
}
};
server.join().expect("HTTP fixture should finish");
result
}
fn start_server(
respond: impl FnOnce(&mut TcpStream) + Send + 'static,
) -> (String, std::thread::JoinHandle<()>) {
let listener = TcpListener::bind(("127.0.0.1", 0)).expect("HTTP fixture should bind");
let address = listener.local_addr().expect("HTTP fixture address");
listener
.set_nonblocking(true)
.expect("nonblocking listener");
let server = std::thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(5);
let (mut connection, _) = loop {
match listener.accept() {
Ok(connection) => break connection,
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
assert!(Instant::now() < deadline, "HTTP fixture accept timed out");
std::thread::sleep(Duration::from_millis(1));
}
Err(error) => panic!("HTTP fixture should accept: {error}"),
}
};
connection
.set_nonblocking(false)
.expect("HTTP fixture connection should use blocking reads");
connection
.set_read_timeout(Some(Duration::from_secs(5)))
.expect("HTTP fixture read timeout");
let mut request = Vec::new();
let mut buffer = [0; 1024];
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
let count = connection.read(&mut buffer).expect("read HTTP request");
assert_ne!(count, 0, "HTTP request should contain complete headers");
request.extend_from_slice(&buffer[..count]);
}
respond(&mut connection);
});
(
format!("http://{address}/models?credential=url-secret"),
server,
)
}

View File

@@ -0,0 +1,128 @@
use super::*;
use serde_json::json;
use std::io::Write;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::SubscriberExt;
#[tokio::test]
async fn enabled_request_logging_emits_transport_url_and_body() {
let logs = capture_transport_logs(HttpClient::new(test_reqwest_client())).await;
assert!(logs.contains("log capture sentinel"));
assert!(logs.contains("url-secret"));
assert!(logs.contains("body-secret"));
}
#[tokio::test]
async fn disabled_request_logging_suppresses_transport_url_and_body() {
let logs =
capture_transport_logs(HttpClient::new(test_reqwest_client()).without_request_logging())
.await;
assert!(logs.contains("log capture sentinel"));
assert!(!logs.contains("url-secret"));
assert!(!logs.contains("body-secret"));
let controller = crate::NetworkPolicyController::default();
let policy = controller.policy();
controller.publish(policy.revision(), crate::DestinationPolicy::Unrestricted);
let factory = crate::HttpClientFactory::new(crate::OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy);
let client =
crate::RouteAwareClientPool::new(factory, crate::ClientRouteClass::Api).into_client();
let logs = capture_transport_logs(client.clone()).await;
assert!(logs.contains("url-secret"));
let logs = capture_transport_logs(client.clone().without_request_logging()).await;
assert!(!logs.contains("url-secret"), "{logs}");
assert!(!logs.contains("body-secret"));
assert!(capture_transport_logs(client).await.contains("url-secret"));
}
#[tokio::test]
async fn connection_failures_are_classified_without_exposing_request_urls() {
let unavailable_server =
std::net::TcpListener::bind(("127.0.0.1", 0)).expect("server port should bind");
let server_addr = unavailable_server
.local_addr()
.expect("server listener should have an address");
drop(unavailable_server);
let transport = ReqwestTransport::from_http_client(HttpClient::new(test_reqwest_client()));
let request = Request::new(
Method::POST,
format!("http://{server_addr}/responses?token=url-secret"),
);
let error = match transport.stream(request).await {
Err(TransportError::Connection(error)) => error,
Err(error) => panic!("expected a connection failure, got {error}"),
Ok(_) => panic!("an unavailable server should not return a response"),
};
assert!(!error.to_string().contains("url-secret"));
}
fn test_reqwest_client() -> reqwest::Client {
reqwest::Client::builder()
.no_proxy()
.build()
.expect("HTTP client should build")
}
async fn capture_transport_logs(client: HttpClient) -> String {
let unavailable_server =
std::net::TcpListener::bind(("127.0.0.1", 0)).expect("server port should bind");
let server_addr = unavailable_server
.local_addr()
.expect("server listener should have an address");
drop(unavailable_server);
let transport = ReqwestTransport::from_http_client(client);
let log_buffer = Arc::new(Mutex::new(Vec::new()));
let writer_buffer = Arc::clone(&log_buffer);
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(move || TestLogWriter(Arc::clone(&writer_buffer)))
.with_filter(
tracing_subscriber::filter::Targets::new()
.with_target("codex_http_client::transport", tracing::Level::TRACE)
.with_target("codex_http_client::client", tracing::Level::DEBUG),
),
);
let _guard = tracing::subscriber::set_default(subscriber);
tracing::trace!(target: "codex_http_client::transport", "log capture sentinel");
let mut request = Request::new(
Method::POST,
format!("http://{server_addr}/request?token=url-secret"),
)
.with_json(&json!({"token": "body-secret"}));
request.timeout = Some(Duration::from_secs(1));
let _ = transport.execute(request).await;
String::from_utf8(
log_buffer
.lock()
.expect("log buffer should not be poisoned")
.clone(),
)
.expect("captured logs should be UTF-8")
}
#[derive(Clone)]
struct TestLogWriter(Arc<Mutex<Vec<u8>>>);
impl Write for TestLogWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0
.lock()
.map_err(|_| std::io::Error::other("log buffer should not be poisoned"))?
.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

View File

@@ -0,0 +1,282 @@
//! Authenticates a connection to a Windows proxy after a CONNECT 407.
//! Codex owns the connection. Curl reaches it through a local socket used only for
//! authentication. The caller receives the authenticated connection and buffered data.
//! HTTPS proxies that require authentication tokens bound to their TLS connection
//! are not supported because curl does not own that connection.
mod pipe;
pub(crate) use pipe::ProxyPipe;
pub(crate) use pipe::pipe_for;
use std::io;
use std::io::Cursor;
use std::net::Ipv4Addr;
use std::net::SocketAddr;
use std::os::windows::io::IntoRawSocket;
use std::os::windows::io::RawSocket;
use std::sync::Arc;
use std::sync::Mutex;
use curl::easy::Auth;
use curl::easy::Easy2;
use curl::easy::Handler;
use curl::easy::List;
use reqwest::Url;
use rustls::ClientConfig;
use rustls::pki_types::ServerName;
use socket2::Socket;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::io::Interest;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::sync::watch;
use tokio::task::JoinSet;
use tokio_rustls::TlsConnector;
use url::Host;
use crate::OutboundProxyRoute;
use crate::build_rustls_client_config_with_custom_ca;
/// Reads and writes a TCP or TLS connection to the proxy.
trait ProxyIo: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> ProxyIo for T {}
struct CurlSocket {
// After CONNECT, this duplicate lets Tokio wait for curl's socket without polling.
// All reads still go through curl so bytes in curl's own buffers are preserved.
readiness: Option<std::net::TcpStream>,
expected_peer: Arc<Mutex<Option<SocketAddr>>>,
cancellation: watch::Sender<()>,
}
impl Handler for CurlSocket {
fn open_socket(&mut self, family: i32, kind: i32, protocol: i32) -> Option<RawSocket> {
let socket = Socket::new(family.into(), kind.into(), Some(protocol.into())).ok()?;
socket
.bind(&SocketAddr::from((Ipv4Addr::LOCALHOST, 0)).into())
.ok()?;
self.readiness = Some(socket.try_clone().ok()?.into());
*self.expected_peer.lock().ok()? = Some(socket.local_addr().ok()?.as_socket()?);
Some(socket.into_raw_socket())
}
fn progress(&mut self, _dltotal: f64, _dlnow: f64, _ultotal: f64, _ulnow: f64) -> bool {
!self.cancellation.is_closed()
}
}
/// TLS configuration for the connection to an HTTPS proxy.
#[derive(Clone)]
pub enum WindowsProxyTls {
/// Use the shared default roots and custom CA configuration.
Default,
/// Reuse the caller's TLS configuration.
Custom(Arc<ClientConfig>),
}
pub(crate) fn can_authenticate_route(target: &str, route: &OutboundProxyRoute) -> bool {
matches!(route, OutboundProxyRoute::Proxy { url, .. }
if Url::parse(target).is_ok_and(|target| target.scheme() == "https")
&& parse_proxy_url(url).is_ok())
}
fn parse_proxy_url(proxy_url: &str) -> io::Result<Url> {
let proxy = Url::parse(proxy_url).map_err(|_| invalid_proxy())?;
if !matches!(proxy.scheme(), "http" | "https")
|| !proxy.username().is_empty()
|| proxy.password().is_some()
{
return Err(invalid_proxy());
}
Ok(proxy)
}
/// Opens a new connection to the selected proxy and authenticates a CONNECT tunnel.
/// Call only after the proxy rejects a CONNECT request with 407.
pub async fn connect_windows_proxy(
proxy_url: &str,
target: &Url,
proxy_tls: WindowsProxyTls,
) -> io::Result<impl AsyncRead + AsyncWrite + Unpin + Send + use<>> {
let proxy = parse_proxy_url(proxy_url)?;
let proxy_host = proxy.host_str().ok_or_else(invalid_proxy)?;
let target_host = target.host_str().ok_or_else(invalid_proxy)?;
let target_port = target.port_or_known_default().ok_or_else(invalid_proxy)?;
let listener = Arc::new(TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?);
let local_port = listener.local_addr()?.port();
// Keep the real hostname for Windows' HTTP/<proxy host> identity. Resolve it to our
// local socket for this handle only; Codex connects to the original proxy URL below.
let mut dns = List::new();
dns.append(&format!("{proxy_host}:{local_port}:127.0.0.1"))
.map_err(io::Error::other)?;
let mut auth = Auth::new();
// Curl uses the signed-in user for Negotiate and separately advertised NTLM.
// libcurl 8.22 removes NTLM from Windows Negotiate; check this behavior on upgrades.
auth.gssnegotiate(true).ntlm(true);
let expected_peer = Arc::new(Mutex::new(None));
let (cancellation, _authentication_alive) = watch::channel(());
let mut curl = Easy2::new(CurlSocket {
readiness: None,
expected_peer: Arc::clone(&expected_peer),
cancellation,
});
curl.proxy(&format!("http://{proxy_host}:{local_port}"))
.map_err(io::Error::other)?;
curl.resolve(dns).map_err(io::Error::other)?;
curl.noproxy("").map_err(io::Error::other)?;
curl.url(&format!("http://{target_host}:{target_port}/"))
.map_err(io::Error::other)?;
curl.http_proxy_tunnel(true).map_err(io::Error::other)?;
curl.connect_only(true).map_err(io::Error::other)?;
curl.proxy_username("").map_err(io::Error::other)?;
curl.proxy_password("").map_err(io::Error::other)?;
curl.proxy_auth(&auth).map_err(io::Error::other)?;
curl.progress(true).map_err(io::Error::other)?;
let listener_guard = Arc::clone(&listener);
let mut authentication = tokio::task::spawn_blocking(move || {
// Keep the port reserved until curl stops, even if the caller cancels.
let _listener_guard = listener_guard;
curl.perform().map_err(io::Error::other)?;
Ok::<_, io::Error>(curl)
});
// Curl can reconnect. Keep the proxy connection that completed authentication.
let (authenticated, _) = watch::channel(None);
// Owning the jobs here also closes the real and local sockets if the caller cancels.
let mut connections = JoinSet::new();
let mut curl = loop {
tokio::select! {
result = &mut authentication => break result.map_err(io::Error::other)??,
accepted = listener.accept() => {
let (local, peer) = accepted?;
{
let mut expected = expected_peer
.lock()
.map_err(|_| io::Error::other("proxy socket state is poisoned"))?;
if *expected != Some(peer) {
continue;
}
*expected = None;
}
// Curl has moved to this socket, so earlier attempts cannot authenticate.
connections.shutdown().await;
let proxy = proxy.clone();
let proxy_tls = proxy_tls.clone();
let mut done = authenticated.subscribe();
connections.spawn(async move {
let upstream = connect_to_proxy(&proxy, proxy_tls).await?;
let (mut from_curl, mut to_curl) = local.into_split();
let (from_proxy, mut to_proxy) = tokio::io::split(upstream);
let mut from_proxy = BufReader::new(from_proxy);
tokio::select! {
changed = done.changed() => {
changed.map_err(io::Error::other)?;
let selected = *done.borrow_and_update() == Some(peer.port());
if selected {
// Do not shut down the real writer. EOF on this side lets
// curl return all bytes already sent to its local socket.
to_curl.shutdown().await?;
return Ok(Some((from_proxy, to_proxy)));
}
}
result = async {
tokio::try_join!(
// copy flushes before waiting for more input, so Rustls
// sends CONNECT before curl waits for the proxy response.
tokio::io::copy(&mut from_curl, &mut to_proxy),
async {
tokio::io::copy_buf(&mut from_proxy, &mut to_curl).await?;
to_curl.shutdown().await
},
)
} => { result?; }
}
Ok::<_, io::Error>(None)
});
}
_ = connections.join_next(), if !connections.is_empty() => {}
}
};
authenticated.send_replace(Some(curl.local_port().map_err(io::Error::other)?));
let (from_proxy, to_proxy) = loop {
match connections.join_next().await {
Some(Ok(Ok(Some(halves)))) => break halves,
Some(_) => {}
None => return Err(io::Error::other("authenticated proxy connection ended")),
}
};
let readiness = curl
.get_mut()
.readiness
.take()
.ok_or_else(|| io::Error::other("curl did not open a proxy connection"))?;
let readiness = TcpStream::from_std(readiness)?;
let mut prefix = Vec::new();
let mut buffer = [0; 8192];
loop {
// curl can hold bytes even while the socket isn't readable.
let read = match curl.recv(&mut buffer) {
Ok(read) => read,
Err(error) if error.is_again() => {
readiness
.async_io(Interest::READABLE, || {
curl.recv(&mut buffer).map_err(|error| {
if error.is_again() {
io::ErrorKind::WouldBlock.into()
} else {
io::Error::other(error)
}
})
})
.await?
}
Err(error) => return Err(io::Error::other(error)),
};
if read == 0 {
break;
}
prefix.extend_from_slice(&buffer[..read]);
}
Ok(tokio::io::join(
Cursor::new(prefix).chain(from_proxy),
to_proxy,
))
}
async fn connect_to_proxy(proxy: &Url, proxy_tls: WindowsProxyTls) -> io::Result<Box<dyn ProxyIo>> {
let host = match proxy.host().ok_or_else(invalid_proxy)? {
Host::Domain(domain) => domain.to_owned(),
Host::Ipv4(address) => address.to_string(),
Host::Ipv6(address) => address.to_string(),
};
let port = proxy.port_or_known_default().ok_or_else(invalid_proxy)?;
let tcp = TcpStream::connect((host.as_str(), port)).await?;
tcp.set_nodelay(true)?;
if proxy.scheme() == "https" {
let config = match proxy_tls {
WindowsProxyTls::Default => {
build_rustls_client_config_with_custom_ca().map_err(io::Error::other)?
}
WindowsProxyTls::Custom(config) => config,
};
let server_name = ServerName::try_from(host).map_err(|_| invalid_proxy())?;
Ok(Box::new(
TlsConnector::from(config).connect(server_name, tcp).await?,
))
} else {
Ok(Box::new(tcp))
}
}
fn invalid_proxy() -> io::Error {
io::Error::new(
io::ErrorKind::InvalidInput,
"invalid Windows authentication proxy route",
)
}

View File

@@ -0,0 +1,121 @@
//! Adapts an authenticated tunnel to reqwest's Windows named-pipe connector.
//! Each listener serves one proxy and destination; only an accepted connection can outlive it.
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use reqwest::Url;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio::net::windows::named_pipe::ServerOptions;
use tokio::task::JoinHandle;
use super::WindowsProxyTls;
use super::connect_windows_proxy;
use crate::HttpClientTlsConfig;
static NEXT_PIPE: AtomicU64 = AtomicU64::new(0);
pub(crate) struct ProxyPipe {
path: PathBuf,
listener: JoinHandle<()>,
}
impl ProxyPipe {
pub(crate) fn path(&self) -> &Path {
&self.path
}
}
impl Drop for ProxyPipe {
fn drop(&mut self) {
self.listener.abort();
}
}
/// Called only on a confirmed proxy CONNECT 407. A pipe cannot route an arbitrary URL:
/// reqwest sends TLS first, so the pipe must already know its proxy and destination.
pub(crate) async fn pipe_for(
proxy_url: &str,
target: &Url,
tls: &HttpClientTlsConfig,
connect_timeout: Option<Duration>,
) -> io::Result<ProxyPipe> {
let proxy_tls = if Url::parse(proxy_url).map_err(io::Error::other)?.scheme() == "https" {
tls.windows_proxy_tls()?
} else {
WindowsProxyTls::Default
};
// Surface auth failure before reqwest starts TLS on the pipe and obscures the error.
let upstream =
connect_with_timeout(proxy_url, target, proxy_tls.clone(), connect_timeout).await?;
let id = NEXT_PIPE.fetch_add(1, Ordering::Relaxed);
let path = PathBuf::from(format!(
r"\\.\pipe\codex-proxy-auth-{}-{id}",
std::process::id(),
));
let first = ServerOptions::new()
.first_pipe_instance(true)
.reject_remote_clients(true)
.create(&path)?;
let proxy_url = proxy_url.to_owned();
let target = target.clone();
let listen_path = path.clone();
let listener = tokio::spawn(async move {
let mut next = first;
let mut first_upstream = Some(upstream);
while next.connect().await.is_ok() {
// Always prepare the next instance before serving this connection.
// Reqwest opens pipes without retrying ERROR_PIPE_BUSY.
let mut accepted = next;
let Ok(server) = ServerOptions::new()
.reject_remote_clients(true)
.create(&listen_path)
else {
break;
};
next = server;
let proxy_url = proxy_url.clone();
let target = target.clone();
let proxy_tls = proxy_tls.clone();
let connected = first_upstream.take();
tokio::spawn(async move {
let result = async {
let mut upstream = match connected {
Some(upstream) => upstream,
None => {
connect_with_timeout(&proxy_url, &target, proxy_tls, connect_timeout)
.await?
}
};
tokio::io::copy_bidirectional(&mut accepted, &mut upstream).await?;
Ok::<(), io::Error>(())
}
.await;
if let Err(error) = result {
tracing::debug!(kind = ?error.kind(), "Windows proxy pipe ended");
}
});
}
});
Ok(ProxyPipe { path, listener })
}
async fn connect_with_timeout(
proxy_url: &str,
target: &Url,
proxy_tls: WindowsProxyTls,
connect_timeout: Option<Duration>,
) -> io::Result<impl AsyncRead + AsyncWrite + Unpin + Send + use<>> {
let connect = connect_windows_proxy(proxy_url, target, proxy_tls);
match connect_timeout {
Some(timeout) => tokio::time::timeout(timeout, connect).await.map_err(|_| {
io::Error::new(io::ErrorKind::TimedOut, "proxy authentication timed out")
})?,
None => connect.await,
}
}

View File

@@ -0,0 +1,22 @@
//! Windows certificate validation for callers without a custom CA bundle.
//!
//! Unlike a snapshot of installed roots, Windows can retrieve missing trusted roots on demand.
//! Callers must retain the custom-CA configuration path when a bundle is configured.
use std::sync::Arc;
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
use rustls::ClientConfig;
use rustls_platform_verifier::ConfigVerifierExt;
/// Builds a TLS configuration that validates server certificates using Windows trust policy.
///
/// This does not load Codex custom CA settings; callers must check those before selecting it.
pub fn build_windows_platform_tls_config() -> Result<Arc<ClientConfig>, rustls::Error> {
ensure_rustls_crypto_provider();
ClientConfig::with_platform_verifier().map(Arc::new)
}
#[cfg(test)]
#[path = "windows_tls_tests.rs"]
mod tests;

View File

@@ -0,0 +1,58 @@
//! Certificate rejection coverage for Windows platform TLS.
use super::build_windows_platform_tls_config;
use std::sync::Arc;
#[test]
fn platform_tls_rejects_a_self_signed_server() {
let client_config =
build_windows_platform_tls_config().expect("configure platform verification");
let certified_key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])
.expect("generate untrusted certificate");
let server_config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(
vec![certified_key.cert.der().clone()],
certified_key.signing_key.into(),
)
.expect("configure test server");
let mut client = rustls::ClientConnection::new(
client_config,
"localhost".try_into().expect("valid server name"),
)
.expect("create client");
let mut server = rustls::ServerConnection::new(Arc::new(server_config)).expect("create server");
// Drive the real handshake without opening ports or changing system trust.
for _ in 0..10 {
let mut outbound = Vec::new();
client
.write_tls(&mut outbound)
.expect("write client records");
server
.read_tls(&mut outbound.as_slice())
.expect("read client records");
server
.process_new_packets()
.expect("process client records");
outbound.clear();
server
.write_tls(&mut outbound)
.expect("write server records");
client
.read_tls(&mut outbound.as_slice())
.expect("read server records");
if let Err(error) = client.process_new_packets() {
assert!(
matches!(error, rustls::Error::InvalidCertificate(_)),
"{error:?}"
);
return;
}
assert!(
client.is_handshaking(),
"untrusted server must not complete TLS"
);
}
panic!("expected certificate rejection during handshake");
}