mirror of
https://github.com/openai/codex.git
synced 2026-11-24 07:20:27 +00:00
Resolve outbound proxy routes explicitly (#34435)
## Why System proxy discovery can block, and delegating fallback to each transport can repeat discovery or apply inconsistent environment proxy behavior. ## What changed - Resolve unavailable system proxy decisions to an explicit environment proxy or direct route, including `NO_PROXY` settings and WebSocket-specific fallbacks. - Add asynchronous system proxy resolution that uses cached decisions first and serializes blocking platform lookups on Windows and macOS. - Preserve `NO_PROXY` handling for WebSocket connections, including HTTP and HTTPS proxies, and hash proxy cache keys on every platform. ## Testing - Add coverage for explicit environment fallback, cached asynchronous resolution, and proxied or bypassed WebSocket connections. GitOrigin-RevId: 3b7cf170dcfe639eec53c3c1514f92bfcf13e7e9
This commit is contained in:
1 parent
2be7d3bcd9
commit
c9ef7eff00
5 files changed
+529
-82
No files matched your search
@@ -1,4 +1,5 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -14,6 +15,7 @@ use rcgen::generate_simple_self_signed;
|
||||
use rustls::ClientConfig;
|
||||
use rustls::RootCertStore;
|
||||
use rustls::ServerConfig;
|
||||
use rustls::pki_types::CertificateDer;
|
||||
use rustls::pki_types::PrivateKeyDer;
|
||||
use rustls::pki_types::PrivatePkcs8KeyDer;
|
||||
use tokio::io::AsyncReadExt;
|
||||
@@ -35,7 +37,7 @@ use crate::WebSocketConnector;
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_connector_uses_factory_and_exposes_stream_and_sink() {
|
||||
let (target_addr, target_task) = start_plain_echo_websocket_server().await;
|
||||
let (target_addr, target_task) = start_echo_websocket_server(/*acceptor*/ None).await;
|
||||
let request = format!("ws://localhost:{}/v1/responses", target_addr.port())
|
||||
.into_client_request()
|
||||
.expect("websocket request should build");
|
||||
@@ -63,7 +65,7 @@ async fn public_connector_uses_factory_and_exposes_stream_and_sink() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_route_connects_secure_websocket() {
|
||||
let (tls_config, acceptor) = test_tls_configs();
|
||||
let (tls_config, acceptor, _) = test_tls_configs();
|
||||
let (target_addr, target_task) = start_tls_websocket_server(acceptor).await;
|
||||
let request = format!("wss://localhost:{}/v1/responses", target_addr.port())
|
||||
.into_client_request()
|
||||
@@ -92,6 +94,92 @@ async fn https_proxy_tunnels_secure_websocket_before_handshake() {
|
||||
assert_proxy_tunnels_secure_websocket(/*proxy_tls*/ true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn environment_proxy_route_honors_no_proxy_in_a_subprocess() {
|
||||
assert_no_proxy_subprocess(
|
||||
"127.0.0.1",
|
||||
/*expect_proxy*/ false,
|
||||
/*proxy_tls*/ false,
|
||||
)
|
||||
.await;
|
||||
assert_no_proxy_subprocess(
|
||||
"unrelated.example",
|
||||
/*expect_proxy*/ true,
|
||||
/*proxy_tls*/ false,
|
||||
)
|
||||
.await;
|
||||
assert_no_proxy_subprocess(
|
||||
"unrelated.example",
|
||||
/*expect_proxy*/ true,
|
||||
/*proxy_tls*/ true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_proxy_subprocess_probe() {
|
||||
let Ok(url) = std::env::var("CODEX_WEBSOCKET_NO_PROXY_PROBE_URL") else {
|
||||
return;
|
||||
};
|
||||
let proxy_url = std::env::var("CODEX_WEBSOCKET_NO_PROXY_PROBE_PROXY")
|
||||
.expect("parent test should provide a proxy URL");
|
||||
let no_proxy = std::env::var("NO_PROXY").expect("parent test should provide a no-proxy value");
|
||||
let request = url
|
||||
.into_client_request()
|
||||
.expect("websocket request should build");
|
||||
let tls_config =
|
||||
if let Ok(certificate_hex) = std::env::var("CODEX_WEBSOCKET_NO_PROXY_PROBE_CA_DER") {
|
||||
ensure_rustls_crypto_provider();
|
||||
assert_eq!(
|
||||
certificate_hex.len() % 2,
|
||||
0,
|
||||
"encoded certificate should contain complete bytes"
|
||||
);
|
||||
let certificate = (0..certificate_hex.len())
|
||||
.step_by(2)
|
||||
.map(|index| {
|
||||
u8::from_str_radix(&certificate_hex[index..index + 2], 16)
|
||||
.expect("encoded certificate should contain hexadecimal bytes")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots
|
||||
.add(CertificateDer::from(certificate))
|
||||
.expect("proxy certificate should be trusted");
|
||||
Arc::new(
|
||||
ClientConfig::builder()
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth(),
|
||||
)
|
||||
} else {
|
||||
test_tls_configs().0
|
||||
};
|
||||
let (inner, _) = connect(
|
||||
request,
|
||||
WebSocketConfig::default(),
|
||||
tls_config,
|
||||
OutboundProxyRoute::Proxy {
|
||||
url: proxy_url,
|
||||
no_proxy: Some(no_proxy),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("websocket handshake should succeed");
|
||||
let mut websocket = WebSocketConnection { inner };
|
||||
websocket
|
||||
.send(Message::Text("probe".into()))
|
||||
.await
|
||||
.expect("probe should send");
|
||||
assert_eq!(
|
||||
websocket
|
||||
.next()
|
||||
.await
|
||||
.expect("probe should receive a message")
|
||||
.expect("probe message should be valid"),
|
||||
Message::Text("probe".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn https_proxy_defaults_to_port_443_and_preserves_explicit_port() {
|
||||
let default_port = ProxyEndpoint::parse("https://proxy.example")
|
||||
@@ -150,7 +238,9 @@ async fn happy_eyeballs_does_not_wait_for_stalled_preferred_family() {
|
||||
assert_eq!(connected, reachable);
|
||||
}
|
||||
|
||||
async fn start_plain_echo_websocket_server() -> (SocketAddr, JoinHandle<()>) {
|
||||
async fn start_echo_websocket_server(
|
||||
acceptor: Option<TlsAcceptor>,
|
||||
) -> (SocketAddr, JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("target listener should bind");
|
||||
@@ -159,6 +249,15 @@ async fn start_plain_echo_websocket_server() -> (SocketAddr, JoinHandle<()>) {
|
||||
.expect("target listener should have an address");
|
||||
let task = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.expect("target should accept");
|
||||
let stream: Box<dyn AsyncIo> = match acceptor {
|
||||
Some(acceptor) => Box::new(
|
||||
acceptor
|
||||
.accept(stream)
|
||||
.await
|
||||
.expect("target TLS handshake should succeed"),
|
||||
),
|
||||
None => Box::new(stream),
|
||||
};
|
||||
let mut websocket = accept_async(stream)
|
||||
.await
|
||||
.expect("target websocket handshake should succeed");
|
||||
@@ -175,8 +274,133 @@ async fn start_plain_echo_websocket_server() -> (SocketAddr, JoinHandle<()>) {
|
||||
(address, task)
|
||||
}
|
||||
|
||||
async fn assert_no_proxy_subprocess(no_proxy: &str, expect_proxy: bool, proxy_tls: bool) {
|
||||
let (target_acceptor, proxy_acceptor, certificate) = if proxy_tls {
|
||||
let (_, acceptor, certificate) = test_tls_configs();
|
||||
(Some(acceptor.clone()), Some(acceptor), Some(certificate))
|
||||
} else {
|
||||
(None, None, None)
|
||||
};
|
||||
let (target_addr, target_task) = start_echo_websocket_server(target_acceptor).await;
|
||||
let proxy_listener = Arc::new(
|
||||
TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("proxy listener should bind"),
|
||||
);
|
||||
let proxy_addr = proxy_listener
|
||||
.local_addr()
|
||||
.expect("proxy listener should have an address");
|
||||
let proxy_task = if expect_proxy {
|
||||
let proxy_listener = Arc::clone(&proxy_listener);
|
||||
Some(tokio::spawn(async move {
|
||||
let (client, _) = proxy_listener.accept().await.expect("proxy should accept");
|
||||
let mut client: Box<dyn AsyncIo> = match proxy_acceptor {
|
||||
Some(acceptor) => Box::new(
|
||||
acceptor
|
||||
.accept(client)
|
||||
.await
|
||||
.expect("proxy TLS handshake should succeed"),
|
||||
),
|
||||
None => Box::new(client),
|
||||
};
|
||||
let mut request = Vec::new();
|
||||
let mut byte = [0_u8; 1];
|
||||
while !request.ends_with(b"\r\n\r\n") {
|
||||
client
|
||||
.read_exact(&mut byte)
|
||||
.await
|
||||
.expect("proxy should read CONNECT request");
|
||||
request.push(byte[0]);
|
||||
}
|
||||
let mut target = tokio::net::TcpStream::connect(target_addr)
|
||||
.await
|
||||
.expect("proxy should connect to target");
|
||||
client
|
||||
.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
.await
|
||||
.expect("proxy should acknowledge CONNECT");
|
||||
let _ = tokio::io::copy_bidirectional(&mut client, &mut target).await;
|
||||
String::from_utf8(request).expect("CONNECT request should be UTF-8")
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let executable = std::env::current_exe().expect("test executable should be available");
|
||||
let target_scheme = if proxy_tls { "wss" } else { "ws" };
|
||||
let proxy_scheme = if proxy_tls { "https" } else { "http" };
|
||||
let target_host = if proxy_tls { "localhost" } else { "127.0.0.1" };
|
||||
let target_url = format!(
|
||||
"{target_scheme}://{target_host}:{}/v1/responses",
|
||||
target_addr.port()
|
||||
);
|
||||
let proxy_url = format!("{proxy_scheme}://localhost:{}", proxy_addr.port());
|
||||
let no_proxy = no_proxy.to_string();
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
let mut command = Command::new(executable);
|
||||
command.args([
|
||||
"--exact",
|
||||
"dialer::tests::no_proxy_subprocess_probe",
|
||||
"--nocapture",
|
||||
]);
|
||||
for key in [
|
||||
"HTTP_PROXY",
|
||||
"http_proxy",
|
||||
"HTTPS_PROXY",
|
||||
"https_proxy",
|
||||
"ALL_PROXY",
|
||||
"all_proxy",
|
||||
"NO_PROXY",
|
||||
"no_proxy",
|
||||
] {
|
||||
command.env_remove(key);
|
||||
}
|
||||
command
|
||||
.env(
|
||||
if proxy_tls {
|
||||
"HTTPS_PROXY"
|
||||
} else {
|
||||
"HTTP_PROXY"
|
||||
},
|
||||
&proxy_url,
|
||||
)
|
||||
.env("NO_PROXY", no_proxy)
|
||||
.env("CODEX_WEBSOCKET_NO_PROXY_PROBE_URL", target_url)
|
||||
.env("CODEX_WEBSOCKET_NO_PROXY_PROBE_PROXY", proxy_url);
|
||||
command.env_remove("CODEX_WEBSOCKET_NO_PROXY_PROBE_CA_DER");
|
||||
if let Some(certificate) = certificate {
|
||||
let certificate_hex = certificate
|
||||
.as_ref()
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<String>();
|
||||
command.env("CODEX_WEBSOCKET_NO_PROXY_PROBE_CA_DER", certificate_hex);
|
||||
}
|
||||
command
|
||||
.output()
|
||||
.expect("WebSocket no-proxy subprocess should run")
|
||||
})
|
||||
.await
|
||||
.expect("WebSocket no-proxy subprocess should join");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"WebSocket no-proxy subprocess failed\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
|
||||
target_task.await.expect("target task should finish");
|
||||
// In the bypass case no task services the proxy listener, so the successful child connection
|
||||
// above also proves that the matching NO_PROXY value selected the target directly.
|
||||
if let Some(proxy_task) = proxy_task {
|
||||
let request = proxy_task.await.expect("proxy task should finish");
|
||||
let expected_request_line =
|
||||
format!("CONNECT {target_host}:{} HTTP/1.1", target_addr.port());
|
||||
assert_eq!(request.lines().next(), Some(expected_request_line.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_proxy_tunnels_secure_websocket(proxy_tls: bool) {
|
||||
let (tls_config, acceptor) = test_tls_configs();
|
||||
let (tls_config, acceptor, _) = test_tls_configs();
|
||||
let (target_addr, target_task) = start_tls_websocket_server(acceptor.clone()).await;
|
||||
|
||||
let proxy_listener = TcpListener::bind("127.0.0.1:0")
|
||||
@@ -232,6 +456,7 @@ async fn assert_proxy_tunnels_secure_websocket(proxy_tls: bool) {
|
||||
tls_config,
|
||||
OutboundProxyRoute::Proxy {
|
||||
url: format!("{proxy_scheme}://localhost:{}", proxy_addr.port()),
|
||||
no_proxy: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
@@ -270,7 +495,7 @@ async fn start_tls_websocket_server(acceptor: TlsAcceptor) -> (SocketAddr, JoinH
|
||||
(address, task)
|
||||
}
|
||||
|
||||
fn test_tls_configs() -> (Arc<ClientConfig>, TlsAcceptor) {
|
||||
fn test_tls_configs() -> (Arc<ClientConfig>, TlsAcceptor, CertificateDer<'static>) {
|
||||
ensure_rustls_crypto_provider();
|
||||
let CertifiedKey { cert, signing_key } =
|
||||
generate_simple_self_signed(vec!["localhost".to_string()])
|
||||
@@ -284,7 +509,7 @@ fn test_tls_configs() -> (Arc<ClientConfig>, TlsAcceptor) {
|
||||
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots
|
||||
.add(certificate)
|
||||
.add(certificate.clone())
|
||||
.expect("test certificate should be trusted");
|
||||
let client_config = ClientConfig::builder()
|
||||
.with_root_certificates(roots)
|
||||
@@ -293,5 +518,6 @@ fn test_tls_configs() -> (Arc<ClientConfig>, TlsAcceptor) {
|
||||
(
|
||||
Arc::new(client_config),
|
||||
TlsAcceptor::from(Arc::new(server_config)),
|
||||
certificate,
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user