Base: codex-main originale (prima del fork aKode)
This commit is contained in:
258
codex-rs/websocket-client/src/cookie_tests.rs
Normal file
258
codex-rs/websocket-client/src/cookie_tests.rs
Normal file
@@ -0,0 +1,258 @@
|
||||
//! Real WebSocket handshakes exercising shared routing cookies and their transport boundaries.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::OutboundProxyRoute;
|
||||
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rcgen::CertifiedKey;
|
||||
use rcgen::generate_simple_self_signed;
|
||||
use rustls::ClientConfig;
|
||||
use rustls::RootCertStore;
|
||||
use rustls::ServerConfig;
|
||||
use rustls::pki_types::PrivateKeyDer;
|
||||
use rustls::pki_types::PrivatePkcs8KeyDer;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tokio_tungstenite::accept_hdr_async;
|
||||
use tokio_tungstenite::tungstenite::Error as WebSocketError;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::handshake::server::Request;
|
||||
use tokio_tungstenite::tungstenite::handshake::server::Response;
|
||||
use tokio_tungstenite::tungstenite::http::HeaderValue;
|
||||
use tokio_tungstenite::tungstenite::http::StatusCode;
|
||||
use tokio_tungstenite::tungstenite::http::header::COOKIE;
|
||||
use tokio_tungstenite::tungstenite::http::header::SET_COOKIE;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
|
||||
use crate::AsyncIo;
|
||||
use crate::TcpNodelay;
|
||||
use crate::WebSocketConnector;
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_handshakes_share_routing_cookies_and_respect_cookie_scope() {
|
||||
ensure_rustls_crypto_provider();
|
||||
let host = "websocket-cookie-test.chatgpt.com";
|
||||
let other_host = "other-websocket-cookie-test.chatgpt.com";
|
||||
let CertifiedKey { cert, signing_key } = generate_simple_self_signed(vec![
|
||||
host.to_string(),
|
||||
other_host.to_string(),
|
||||
"api.openai.com".to_string(),
|
||||
])
|
||||
.unwrap();
|
||||
let server_config = ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(
|
||||
vec![cert.der().clone()],
|
||||
PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(signing_key.serialize_der())),
|
||||
)
|
||||
.unwrap();
|
||||
let acceptor = TlsAcceptor::from(Arc::new(server_config));
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots.add(cert.der().clone()).unwrap();
|
||||
let tls_config = Arc::new(
|
||||
ClientConfig::builder()
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth(),
|
||||
);
|
||||
|
||||
let parent_url = format!("wss://{host}/backend-api/codex/responses");
|
||||
let review_url = format!("wss://{host}/backend-api/codex/guardian");
|
||||
let requests = [
|
||||
(parent_url.clone(), None),
|
||||
(review_url.clone(), None),
|
||||
(review_url.clone(), Some("explicit=keep")),
|
||||
(format!("wss://{host}/outside"), None),
|
||||
(
|
||||
format!("wss://{other_host}/backend-api/codex/responses"),
|
||||
None,
|
||||
),
|
||||
("wss://api.openai.com/v1/responses".to_string(), None),
|
||||
("wss://api.openai.com/v1/responses".to_string(), None),
|
||||
(format!("ws://{host}/backend-api/codex/responses"), None),
|
||||
(review_url.clone(), None),
|
||||
(review_url.clone(), None),
|
||||
(review_url, None),
|
||||
(parent_url, None),
|
||||
];
|
||||
let responses: Vec<(StatusCode, Vec<&str>)> = vec![
|
||||
(
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
vec![
|
||||
"__oailb=west; Path=/backend-api; Secure; HttpOnly",
|
||||
"__cflb=west; Path=/backend-api; Secure; HttpOnly",
|
||||
"chatgpt_session=never-store; Path=/; Secure",
|
||||
],
|
||||
),
|
||||
// Even a failed upgrade can refresh a cookie used by the next connection.
|
||||
(
|
||||
StatusCode::FORBIDDEN,
|
||||
vec![
|
||||
"__oailb=east; Path=/backend-api; Secure",
|
||||
"__cflb=east; Path=/backend-api; Secure",
|
||||
],
|
||||
),
|
||||
(StatusCode::SWITCHING_PROTOCOLS, vec![]),
|
||||
(StatusCode::SWITCHING_PROTOCOLS, vec![]),
|
||||
(StatusCode::SWITCHING_PROTOCOLS, vec![]),
|
||||
(
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
vec!["__oailb=untrusted; Path=/; Secure"],
|
||||
),
|
||||
(StatusCode::SWITCHING_PROTOCOLS, vec![]),
|
||||
(
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
vec!["__oailb=insecure; Path=/backend-api"],
|
||||
),
|
||||
(StatusCode::SWITCHING_PROTOCOLS, vec![]),
|
||||
(
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
vec![
|
||||
"__oailb=; Path=/backend-api; Max-Age=0; Secure",
|
||||
"__cflb=; Path=/backend-api; Max-Age=0; Secure",
|
||||
],
|
||||
),
|
||||
(StatusCode::SWITCHING_PROTOCOLS, vec![]),
|
||||
];
|
||||
let mut responses = responses;
|
||||
responses.push((StatusCode::SWITCHING_PROTOCOLS, vec![]));
|
||||
let expected_statuses = responses
|
||||
.iter()
|
||||
.map(|(status, _)| *status)
|
||||
.collect::<Vec<_>>();
|
||||
let secure = requests
|
||||
.iter()
|
||||
.map(|(url, _)| url.starts_with("wss:"))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Terminate CONNECT locally so the real TLS/upgrade path can use ChatGPT hostnames without DNS
|
||||
// overrides, environment changes, or external traffic.
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy_url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let mut received_cookies = Vec::new();
|
||||
for ((status, cookies), secure) in responses.into_iter().zip(secure) {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut connect = Vec::new();
|
||||
while !connect.ends_with(b"\r\n\r\n") {
|
||||
connect.push(stream.read_u8().await.unwrap());
|
||||
}
|
||||
stream
|
||||
.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
.await
|
||||
.unwrap();
|
||||
let stream: Box<dyn AsyncIo> = if secure {
|
||||
Box::new(acceptor.accept(stream).await.unwrap())
|
||||
} else {
|
||||
Box::new(stream)
|
||||
};
|
||||
let result = accept_hdr_async(stream, |request: &Request, mut response: Response| {
|
||||
received_cookies.push(request.headers().get(COOKIE).cloned());
|
||||
for cookie in cookies {
|
||||
response
|
||||
.headers_mut()
|
||||
.append(SET_COOKIE, HeaderValue::from_static(cookie));
|
||||
}
|
||||
if status == StatusCode::SWITCHING_PROTOCOLS {
|
||||
Ok(response)
|
||||
} else {
|
||||
*response.status_mut() = status;
|
||||
Err(response.map(|()| None))
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if status == StatusCode::SWITCHING_PROTOCOLS {
|
||||
drop(result.unwrap());
|
||||
} else {
|
||||
assert!(matches!(result, Err(WebSocketError::Http(_))));
|
||||
}
|
||||
}
|
||||
received_cookies
|
||||
});
|
||||
|
||||
let mut actual_statuses = Vec::new();
|
||||
let mut parent_affinity: Option<codex_http_client::ChatGptRoutingAffinity> = None;
|
||||
let last_request = requests.len() - 1;
|
||||
for (index, (url, explicit_cookie)) in requests.into_iter().enumerate() {
|
||||
// Separate connector/factory instances must still see the shared routing cookie.
|
||||
let connector = WebSocketConnector {
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
tls_config: Some(Arc::clone(&tls_config)),
|
||||
tcp_nodelay: TcpNodelay::Default,
|
||||
};
|
||||
let mut request = url.into_client_request().unwrap();
|
||||
if let Some(cookie) = explicit_cookie {
|
||||
request
|
||||
.headers_mut()
|
||||
.insert(COOKIE, HeaderValue::from_static(cookie));
|
||||
}
|
||||
// Replay the parent's captured pin after other traffic changed and deleted the shared pin.
|
||||
if index == last_request {
|
||||
let pin = parent_affinity
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.cookie_header(request.uri())
|
||||
.unwrap();
|
||||
request.headers_mut().insert(COOKIE, pin);
|
||||
}
|
||||
let result = connector
|
||||
.connect_with_route(
|
||||
request,
|
||||
WebSocketConfig::default(),
|
||||
std::future::ready(Ok(OutboundProxyRoute::Proxy {
|
||||
url: proxy_url.clone(),
|
||||
no_proxy: None,
|
||||
})),
|
||||
/*loopback_direct*/ false,
|
||||
)
|
||||
.await;
|
||||
let status = match result {
|
||||
Ok((connection, response)) => {
|
||||
if index == 0 {
|
||||
parent_affinity = connection.routing_affinity().cloned();
|
||||
} else {
|
||||
// All later successful handshakes return no usable routing cookie.
|
||||
assert!(connection.routing_affinity().is_none());
|
||||
}
|
||||
drop(connection);
|
||||
response.status()
|
||||
}
|
||||
Err(WebSocketError::Http(response)) => response.status(),
|
||||
Err(error) => panic!("unexpected handshake error: {error}"),
|
||||
};
|
||||
actual_statuses.push(status);
|
||||
}
|
||||
assert_eq!(actual_statuses, expected_statuses);
|
||||
assert_eq!(
|
||||
server
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|cookie| cookie.map(|value| {
|
||||
let mut parts = value.to_str().unwrap().split("; ").collect::<Vec<_>>();
|
||||
parts.sort_unstable();
|
||||
HeaderValue::from_str(&parts.join("; ")).unwrap()
|
||||
}))
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
None,
|
||||
Some("__cflb=west; __oailb=west"),
|
||||
Some("explicit=keep"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some("__cflb=east; __oailb=east"),
|
||||
Some("__cflb=east; __oailb=east"),
|
||||
None,
|
||||
Some("__cflb=west; __oailb=west"),
|
||||
]
|
||||
.map(|cookie| cookie.map(HeaderValue::from_static))
|
||||
.to_vec(),
|
||||
);
|
||||
}
|
||||
374
codex-rs/websocket-client/src/dialer.rs
Normal file
374
codex-rs/websocket-client/src/dialer.rs
Normal file
@@ -0,0 +1,374 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_http_client::OutboundProxyRoute;
|
||||
#[cfg(windows)]
|
||||
use codex_http_client::WindowsProxyTls;
|
||||
use codex_http_client::build_rustls_client_config_with_custom_ca;
|
||||
#[cfg(windows)]
|
||||
use codex_http_client::connect_windows_proxy;
|
||||
use futures::StreamExt;
|
||||
use futures::stream::FuturesUnordered;
|
||||
use rustls::ClientConfig;
|
||||
use rustls::pki_types::ServerName;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::sleep_until;
|
||||
use tokio_rustls::TlsConnector;
|
||||
use tokio_tungstenite::Connector;
|
||||
use tokio_tungstenite::client_async_tls_with_config;
|
||||
use tokio_tungstenite::connect_async_tls_with_config;
|
||||
use tokio_tungstenite::proxy::connect_via_proxy;
|
||||
use tokio_tungstenite::tungstenite::Error as WebSocketError;
|
||||
use tokio_tungstenite::tungstenite::error::TlsError;
|
||||
use tokio_tungstenite::tungstenite::error::UrlError;
|
||||
use tokio_tungstenite::tungstenite::handshake::client::Request;
|
||||
use tokio_tungstenite::tungstenite::handshake::client::Response;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
use tokio_tungstenite::tungstenite::proxy::ProxyConfig;
|
||||
#[cfg(windows)]
|
||||
use tokio_tungstenite::tungstenite::proxy::ProxyScheme;
|
||||
|
||||
use crate::AsyncIo;
|
||||
use crate::ConnectionInner;
|
||||
use crate::TcpNodelay;
|
||||
|
||||
const HAPPY_EYEBALLS_DELAY: Duration = Duration::from_millis(250);
|
||||
|
||||
pub(crate) async fn connect(
|
||||
request: Request,
|
||||
config: WebSocketConfig,
|
||||
tls_config: Option<Arc<ClientConfig>>,
|
||||
proxy_route: OutboundProxyRoute,
|
||||
tcp_nodelay: TcpNodelay,
|
||||
loopback_direct: bool,
|
||||
) -> Result<(ConnectionInner, Response), WebSocketError> {
|
||||
let disable_nagle = tcp_nodelay == TcpNodelay::Enabled;
|
||||
let proxy_url = match proxy_route {
|
||||
OutboundProxyRoute::TransportDefault => {
|
||||
// The workspace enables tokio-tungstenite's `proxy` feature, so its default dialer
|
||||
// resolves HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and NO_PROXY before opening the socket.
|
||||
let (stream, response) = connect_async_tls_with_config(
|
||||
request,
|
||||
Some(config),
|
||||
disable_nagle,
|
||||
tls_config.map(Connector::Rustls),
|
||||
)
|
||||
.await?;
|
||||
return Ok((ConnectionInner::Left(stream), response));
|
||||
}
|
||||
OutboundProxyRoute::Direct => None,
|
||||
OutboundProxyRoute::Proxy {
|
||||
url,
|
||||
no_proxy: None,
|
||||
} => Some(url),
|
||||
// Use the explicit CONNECT path so it can retry a proxy 407.
|
||||
#[cfg(windows)]
|
||||
OutboundProxyRoute::Proxy {
|
||||
url,
|
||||
no_proxy: Some(_),
|
||||
} if matches!(
|
||||
(ProxyConfig::from_env(request.uri()), ProxyConfig::parse(&url)),
|
||||
(Ok(Some(selected)), Ok(route))
|
||||
if selected.scheme == ProxyScheme::Http
|
||||
&& selected.auth.is_none()
|
||||
&& selected == route
|
||||
) =>
|
||||
{
|
||||
Some(url)
|
||||
}
|
||||
OutboundProxyRoute::Proxy {
|
||||
url,
|
||||
no_proxy: Some(_),
|
||||
} => {
|
||||
// Let Tungstenite apply its complete NO_PROXY semantics. Its environment parser does
|
||||
// not accept HTTPS proxy URLs, but that error occurs only after it decides the target
|
||||
// is not bypassed, so retry that case through the explicit TLS-to-proxy path below.
|
||||
match connect_async_tls_with_config(
|
||||
request.clone(),
|
||||
Some(config),
|
||||
disable_nagle,
|
||||
tls_config.clone().map(Connector::Rustls),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((stream, response)) => {
|
||||
return Ok((ConnectionInner::Left(stream), response));
|
||||
}
|
||||
Err(WebSocketError::Url(UrlError::UnsupportedProxyScheme)) => Some(url),
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let stream: Box<dyn AsyncIo> = match proxy_url {
|
||||
None => {
|
||||
let host = websocket_host(&request)?;
|
||||
let port = websocket_port(&request)?;
|
||||
let address = host_port(host, port);
|
||||
let stream = if loopback_direct {
|
||||
connect_loopback_tcp(address, tcp_nodelay).await
|
||||
} else {
|
||||
connect_tcp(address, tcp_nodelay).await
|
||||
}
|
||||
.map_err(WebSocketError::Io)?;
|
||||
Box::new(stream)
|
||||
}
|
||||
Some(url) => {
|
||||
let proxy = ProxyEndpoint::parse(&url)?;
|
||||
let host = websocket_host(&request)?;
|
||||
let port = websocket_port(&request)?;
|
||||
let stream = connect_tcp(proxy.config.authority(), tcp_nodelay)
|
||||
.await
|
||||
.map_err(WebSocketError::Io)?;
|
||||
let stream: Box<dyn AsyncIo> = if proxy.tls {
|
||||
let proxy_tls_config = match &tls_config {
|
||||
Some(tls_config) => Arc::clone(tls_config),
|
||||
None => build_rustls_client_config_with_custom_ca()
|
||||
.map_err(|error| WebSocketError::Io(error.into()))?,
|
||||
};
|
||||
let server_name = ServerName::try_from(proxy.config.host.clone())
|
||||
.map_err(|_| WebSocketError::Tls(TlsError::InvalidDnsName))?;
|
||||
let stream = TlsConnector::from(proxy_tls_config)
|
||||
.connect(server_name, stream)
|
||||
.await
|
||||
.map_err(WebSocketError::Io)?;
|
||||
Box::new(stream)
|
||||
} else {
|
||||
Box::new(stream)
|
||||
};
|
||||
match connect_via_proxy(stream, &proxy.config, host, port).await {
|
||||
Ok(stream) => stream,
|
||||
#[cfg(windows)]
|
||||
Err(WebSocketError::Url(UrlError::ProxyConnect(message)))
|
||||
if proxy.config.scheme == ProxyScheme::Http
|
||||
&& proxy.config.auth.is_none()
|
||||
&& message == "HTTP CONNECT failed with status 407" =>
|
||||
{
|
||||
// Reconnect so curl can authenticate the proxy tunnel.
|
||||
let target = url::Url::parse(&request.uri().to_string())
|
||||
.map_err(|_| WebSocketError::Url(UrlError::UnsupportedUrlScheme))?;
|
||||
Box::new(
|
||||
connect_windows_proxy(
|
||||
&url,
|
||||
&target,
|
||||
tls_config
|
||||
.clone()
|
||||
.map_or(WindowsProxyTls::Default, WindowsProxyTls::Custom),
|
||||
)
|
||||
.await
|
||||
.map_err(WebSocketError::Io)?,
|
||||
)
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let (stream, response) = client_async_tls_with_config(
|
||||
request,
|
||||
stream,
|
||||
Some(config),
|
||||
tls_config.map(Connector::Rustls),
|
||||
)
|
||||
.await?;
|
||||
Ok((ConnectionInner::Right(stream), response))
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct ProxyEndpoint {
|
||||
config: ProxyConfig,
|
||||
tls: bool,
|
||||
}
|
||||
|
||||
impl ProxyEndpoint {
|
||||
fn parse(url: &str) -> Result<Self, WebSocketError> {
|
||||
let mut parsed_url = url::Url::parse(url).map_err(|_| invalid_proxy_config())?;
|
||||
let tls = parsed_url.scheme() == "https";
|
||||
if tls {
|
||||
// Capture the HTTPS default before changing schemes: `Url` normalizes default ports,
|
||||
// so setting 443 before rewriting to HTTP would discard it and later imply port 80.
|
||||
let port = parsed_url
|
||||
.port_or_known_default()
|
||||
.ok_or_else(invalid_proxy_config)?;
|
||||
parsed_url
|
||||
.set_scheme("http")
|
||||
.map_err(|_| invalid_proxy_config())?;
|
||||
parsed_url
|
||||
.set_port(Some(port))
|
||||
.map_err(|_| invalid_proxy_config())?;
|
||||
}
|
||||
let config = ProxyConfig::parse(parsed_url.as_str()).map_err(|error| match error {
|
||||
WebSocketError::Url(UrlError::UnsupportedProxyScheme) => error,
|
||||
_ => invalid_proxy_config(),
|
||||
})?;
|
||||
Ok(Self { config, tls })
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_proxy_config() -> WebSocketError {
|
||||
WebSocketError::Url(UrlError::InvalidProxyConfig("<redacted>".to_string()))
|
||||
}
|
||||
|
||||
fn websocket_host(request: &Request) -> Result<&str, WebSocketError> {
|
||||
request
|
||||
.uri()
|
||||
.host()
|
||||
.ok_or(WebSocketError::Url(UrlError::NoHostName))
|
||||
}
|
||||
|
||||
fn websocket_port(request: &Request) -> Result<u16, WebSocketError> {
|
||||
request
|
||||
.uri()
|
||||
.port_u16()
|
||||
.or_else(|| match request.uri().scheme_str() {
|
||||
Some("ws") => Some(80),
|
||||
Some("wss") => Some(443),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or(WebSocketError::Url(UrlError::UnsupportedUrlScheme))
|
||||
}
|
||||
|
||||
fn host_port(host: &str, port: u16) -> String {
|
||||
if host.contains(':') && !host.starts_with('[') {
|
||||
format!("[{host}]:{port}")
|
||||
} else {
|
||||
format!("{host}:{port}")
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_tcp(address: String, tcp_nodelay: TcpNodelay) -> io::Result<TcpStream> {
|
||||
let addresses = tokio::net::lookup_host(address).await?.collect::<Vec<_>>();
|
||||
connect_resolved_tcp(addresses, tcp_nodelay).await
|
||||
}
|
||||
|
||||
async fn connect_loopback_tcp(address: String, tcp_nodelay: TcpNodelay) -> io::Result<TcpStream> {
|
||||
let addresses = tokio::net::lookup_host(address).await?.collect::<Vec<_>>();
|
||||
connect_resolved_tcp(loopback_addresses(addresses)?, tcp_nodelay).await
|
||||
}
|
||||
|
||||
async fn connect_resolved_tcp(
|
||||
addresses: Vec<SocketAddr>,
|
||||
tcp_nodelay: TcpNodelay,
|
||||
) -> io::Result<TcpStream> {
|
||||
let stream = connect_happy_eyeballs(addresses, TcpStream::connect).await?;
|
||||
if tcp_nodelay == TcpNodelay::Enabled {
|
||||
stream.set_nodelay(/*nodelay*/ true)?;
|
||||
}
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
fn loopback_addresses(addresses: Vec<SocketAddr>) -> io::Result<Vec<SocketAddr>> {
|
||||
let loopback_addresses = addresses
|
||||
.into_iter()
|
||||
.filter(|address| address.ip().is_loopback())
|
||||
.collect::<Vec<_>>();
|
||||
if loopback_addresses.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"direct WebSocket connections must resolve to a loopback address",
|
||||
));
|
||||
}
|
||||
Ok(loopback_addresses)
|
||||
}
|
||||
|
||||
async fn connect_happy_eyeballs<T, F, Fut>(
|
||||
addresses: Vec<SocketAddr>,
|
||||
mut connect: F,
|
||||
) -> io::Result<T>
|
||||
where
|
||||
F: FnMut(SocketAddr) -> Fut,
|
||||
Fut: Future<Output = io::Result<T>>,
|
||||
{
|
||||
let mut addresses = addresses.into_iter();
|
||||
let Some(first_address) = addresses.next() else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"could not resolve to any address",
|
||||
));
|
||||
};
|
||||
|
||||
let first_is_ipv4 = first_address.is_ipv4();
|
||||
let mut preferred = VecDeque::new();
|
||||
let mut alternate = VecDeque::new();
|
||||
for address in addresses {
|
||||
if address.is_ipv4() == first_is_ipv4 {
|
||||
preferred.push_back(address);
|
||||
} else {
|
||||
alternate.push_back(address);
|
||||
}
|
||||
}
|
||||
|
||||
let mut addresses = VecDeque::new();
|
||||
while !preferred.is_empty() || !alternate.is_empty() {
|
||||
if let Some(address) = alternate.pop_front() {
|
||||
addresses.push_back(address);
|
||||
}
|
||||
if let Some(address) = preferred.pop_front() {
|
||||
addresses.push_back(address);
|
||||
}
|
||||
}
|
||||
|
||||
let mut attempts = FuturesUnordered::new();
|
||||
attempts.push(connect(first_address));
|
||||
let mut next_attempt_at = Instant::now() + HAPPY_EYEBALLS_DELAY;
|
||||
let mut last_error = None;
|
||||
|
||||
loop {
|
||||
if addresses.is_empty() {
|
||||
match attempts.next().await {
|
||||
Some(Ok(stream)) => return Ok(stream),
|
||||
Some(Err(error)) => {
|
||||
if attempts.is_empty() {
|
||||
return Err(error);
|
||||
}
|
||||
last_error = Some(error);
|
||||
}
|
||||
None => {
|
||||
return Err(last_error.unwrap_or_else(|| {
|
||||
io::Error::other("connection attempts ended without an error")
|
||||
}));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
result = attempts.next() => {
|
||||
match result {
|
||||
Some(Ok(stream)) => return Ok(stream),
|
||||
Some(Err(error)) => {
|
||||
last_error = Some(error);
|
||||
let address = take_next_address(&mut addresses)?;
|
||||
attempts.push(connect(address));
|
||||
next_attempt_at = Instant::now() + HAPPY_EYEBALLS_DELAY;
|
||||
}
|
||||
None => {
|
||||
let address = take_next_address(&mut addresses)?;
|
||||
attempts.push(connect(address));
|
||||
next_attempt_at = Instant::now() + HAPPY_EYEBALLS_DELAY;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = sleep_until(next_attempt_at) => {
|
||||
let address = take_next_address(&mut addresses)?;
|
||||
attempts.push(connect(address));
|
||||
next_attempt_at = Instant::now() + HAPPY_EYEBALLS_DELAY;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn take_next_address(addresses: &mut VecDeque<SocketAddr>) -> io::Result<SocketAddr> {
|
||||
addresses
|
||||
.pop_front()
|
||||
.ok_or_else(|| io::Error::other("connection address queue unexpectedly empty"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "dialer_tests.rs"]
|
||||
mod tests;
|
||||
715
codex-rs/websocket-client/src/dialer_tests.rs
Normal file
715
codex-rs/websocket-client/src/dialer_tests.rs
Normal file
@@ -0,0 +1,715 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::OutboundProxyRoute;
|
||||
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rcgen::CertifiedKey;
|
||||
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;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tokio_tungstenite::MaybeTlsStream;
|
||||
use tokio_tungstenite::accept_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
use tokio_tungstenite::tungstenite::proxy::ProxyScheme;
|
||||
|
||||
use super::*;
|
||||
use crate::AsyncIo;
|
||||
use crate::WebSocketConnection;
|
||||
use crate::WebSocketConnector;
|
||||
use crate::WebSocketTlsMode;
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_connector_uses_factory_and_exposes_stream_and_sink() {
|
||||
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");
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
let connector = WebSocketConnector::new(&factory).expect("connector should build");
|
||||
|
||||
let (mut websocket, _) = connector
|
||||
.connect(request, WebSocketConfig::default())
|
||||
.await
|
||||
.expect("websocket handshake should succeed");
|
||||
assert!(!websocket_tcp_nodelay(&websocket));
|
||||
let expected = Message::Text("hello".into());
|
||||
websocket
|
||||
.send(expected.clone())
|
||||
.await
|
||||
.expect("websocket should send");
|
||||
let actual = websocket
|
||||
.next()
|
||||
.await
|
||||
.expect("websocket should receive a message")
|
||||
.expect("websocket message should be valid");
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
target_task.await.expect("target task should finish");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_connector_enables_tcp_nodelay_when_requested() {
|
||||
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");
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
let connector = WebSocketConnector::new(&factory)
|
||||
.expect("connector should build")
|
||||
.with_tcp_nodelay();
|
||||
|
||||
let (mut websocket, _) = connector
|
||||
.connect(request, WebSocketConfig::default())
|
||||
.await
|
||||
.expect("websocket handshake should succeed");
|
||||
assert!(websocket_tcp_nodelay(&websocket));
|
||||
let expected = Message::Text("latency-sensitive".into());
|
||||
websocket
|
||||
.send(expected.clone())
|
||||
.await
|
||||
.expect("websocket should send");
|
||||
assert_eq!(
|
||||
websocket
|
||||
.next()
|
||||
.await
|
||||
.expect("websocket should receive a message")
|
||||
.expect("websocket message should be valid"),
|
||||
expected
|
||||
);
|
||||
|
||||
target_task.await.expect("target task should finish");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tungstenite_default_tls_mode_ignores_invalid_custom_ca_in_a_subprocess() {
|
||||
let (target_addr, target_task) = start_echo_websocket_server(/*acceptor*/ None).await;
|
||||
let target_url = format!("ws://127.0.0.1:{}/v1/responses", target_addr.port());
|
||||
let executable = std::env::current_exe().expect("test executable should be available");
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
let mut command = Command::new(executable);
|
||||
command.args([
|
||||
"--exact",
|
||||
"dialer::tests::tungstenite_default_tls_mode_subprocess_probe",
|
||||
"--nocapture",
|
||||
]);
|
||||
for key in [
|
||||
"HTTP_PROXY",
|
||||
"http_proxy",
|
||||
"HTTPS_PROXY",
|
||||
"https_proxy",
|
||||
"ALL_PROXY",
|
||||
"all_proxy",
|
||||
"NO_PROXY",
|
||||
"no_proxy",
|
||||
"SSL_CERT_FILE",
|
||||
] {
|
||||
command.env_remove(key);
|
||||
}
|
||||
command
|
||||
.env(
|
||||
"CODEX_CA_CERTIFICATE",
|
||||
"/codex-websocket-client-nonexistent-custom-ca.pem",
|
||||
)
|
||||
.env("CODEX_WEBSOCKET_DEFAULT_TLS_PROBE_URL", target_url)
|
||||
.output()
|
||||
.expect("WebSocket default-TLS subprocess should run")
|
||||
})
|
||||
.await
|
||||
.expect("WebSocket default-TLS subprocess should join");
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"WebSocket default-TLS 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");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tungstenite_default_tls_mode_subprocess_probe() {
|
||||
let Ok(url) = std::env::var("CODEX_WEBSOCKET_DEFAULT_TLS_PROBE_URL") else {
|
||||
return;
|
||||
};
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
assert!(
|
||||
WebSocketConnector::new(&factory).is_err(),
|
||||
"explicit Codex TLS should reject the invalid custom CA"
|
||||
);
|
||||
let connector =
|
||||
WebSocketConnector::new_with_tls_mode(&factory, WebSocketTlsMode::TungsteniteDefault)
|
||||
.expect("Tungstenite-default TLS should ignore custom CA configuration");
|
||||
let request = url
|
||||
.into_client_request()
|
||||
.expect("websocket request should build");
|
||||
let (mut websocket, _) = connector
|
||||
.connect(request, WebSocketConfig::default())
|
||||
.await
|
||||
.expect("WebSocket should connect without constructing Codex TLS");
|
||||
let expected = Message::Text("Tungstenite default TLS".into());
|
||||
websocket
|
||||
.send(expected.clone())
|
||||
.await
|
||||
.expect("WebSocket should send");
|
||||
assert_eq!(
|
||||
websocket
|
||||
.next()
|
||||
.await
|
||||
.expect("WebSocket should receive a message")
|
||||
.expect("WebSocket message should be valid"),
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_route_connects_secure_websocket() {
|
||||
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()
|
||||
.expect("websocket request should build");
|
||||
|
||||
let (inner, _) = connect(
|
||||
request,
|
||||
WebSocketConfig::default(),
|
||||
Some(tls_config),
|
||||
OutboundProxyRoute::Direct,
|
||||
TcpNodelay::Enabled,
|
||||
/*loopback_direct*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("direct websocket handshake should succeed");
|
||||
drop(test_connection(inner));
|
||||
|
||||
target_task.await.expect("target task should finish");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_proxy_tunnels_secure_websocket_before_handshake() {
|
||||
assert_proxy_tunnels_secure_websocket(/*proxy_tls*/ false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
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(),
|
||||
Some(tls_config),
|
||||
OutboundProxyRoute::Proxy {
|
||||
url: proxy_url,
|
||||
no_proxy: Some(no_proxy),
|
||||
},
|
||||
TcpNodelay::Enabled,
|
||||
/*loopback_direct*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("websocket handshake should succeed");
|
||||
let mut websocket = test_connection(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")
|
||||
.expect("HTTPS proxy without a port should parse");
|
||||
let explicit_port = ProxyEndpoint::parse("https://proxy.example:8443")
|
||||
.expect("HTTPS proxy with a port should parse");
|
||||
|
||||
assert_eq!(
|
||||
default_port,
|
||||
ProxyEndpoint {
|
||||
config: ProxyConfig {
|
||||
scheme: ProxyScheme::Http,
|
||||
host: "proxy.example".to_string(),
|
||||
port: 443,
|
||||
auth: None,
|
||||
},
|
||||
tls: true,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
explicit_port,
|
||||
ProxyEndpoint {
|
||||
config: ProxyConfig {
|
||||
scheme: ProxyScheme::Http,
|
||||
host: "proxy.example".to_string(),
|
||||
port: 8443,
|
||||
auth: None,
|
||||
},
|
||||
tls: true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn happy_eyeballs_does_not_wait_for_stalled_preferred_family() {
|
||||
let stalled = "[2001:db8::1]:443"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("stalled address should parse");
|
||||
let reachable = "127.0.0.1:443"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("reachable address should parse");
|
||||
|
||||
let connected = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
connect_happy_eyeballs(vec![stalled, reachable], |address| async move {
|
||||
if address == stalled {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
Ok(address)
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("alternate family should start before timeout")
|
||||
.expect("alternate family should connect");
|
||||
|
||||
assert_eq!(connected, reachable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_direct_drops_non_loopback_resolved_addresses() {
|
||||
let loopback = "127.0.0.1:8080"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("loopback address should parse");
|
||||
let remote = "192.0.2.1:8080"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("remote address should parse");
|
||||
|
||||
assert_eq!(
|
||||
loopback_addresses(vec![remote, loopback]).expect("loopback result should remain"),
|
||||
vec![loopback]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_direct_rejects_localhost_resolution_without_loopback_addresses() {
|
||||
let remote = "192.0.2.1:8080"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("remote address should parse");
|
||||
|
||||
let error = loopback_addresses(vec![remote])
|
||||
.expect_err("localhost resolution without loopback addresses must fail");
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn routed_tcp_connections_only_enable_nodelay_when_requested() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("listener should have an address")
|
||||
.to_string();
|
||||
|
||||
let default_stream = connect_tcp(address.clone(), TcpNodelay::Default)
|
||||
.await
|
||||
.expect("default TCP connection should succeed");
|
||||
assert!(!default_stream.nodelay().expect("TCP_NODELAY should read"));
|
||||
|
||||
let low_latency_stream = connect_tcp(address, TcpNodelay::Enabled)
|
||||
.await
|
||||
.expect("low-latency TCP connection should succeed");
|
||||
assert!(
|
||||
low_latency_stream
|
||||
.nodelay()
|
||||
.expect("TCP_NODELAY should read")
|
||||
);
|
||||
}
|
||||
|
||||
fn websocket_tcp_nodelay(websocket: &WebSocketConnection) -> bool {
|
||||
let Some(ConnectionInner::Left(stream)) = &websocket.inner else {
|
||||
panic!("default connector should use Tungstenite's transport");
|
||||
};
|
||||
let MaybeTlsStream::Plain(stream) = stream.get_ref() else {
|
||||
panic!("test websocket should use a plain TCP stream");
|
||||
};
|
||||
stream.nodelay().expect("TCP_NODELAY should read")
|
||||
}
|
||||
|
||||
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");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.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");
|
||||
let message = websocket
|
||||
.next()
|
||||
.await
|
||||
.expect("target should receive a message")
|
||||
.expect("target websocket message should be valid");
|
||||
websocket
|
||||
.send(message)
|
||||
.await
|
||||
.expect("target should echo the message");
|
||||
});
|
||||
(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 (target_addr, target_task) = start_tls_websocket_server(acceptor.clone()).await;
|
||||
|
||||
let proxy_listener = 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 connect_request = Arc::new(Mutex::new(None));
|
||||
let proxy_connect_request = Arc::clone(&connect_request);
|
||||
let proxy_task = tokio::spawn(async move {
|
||||
let (client, _) = proxy_listener.accept().await.expect("proxy should accept");
|
||||
let mut client: Box<dyn AsyncIo> = if proxy_tls {
|
||||
Box::new(
|
||||
acceptor
|
||||
.accept(client)
|
||||
.await
|
||||
.expect("proxy TLS handshake should succeed"),
|
||||
)
|
||||
} else {
|
||||
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]);
|
||||
}
|
||||
*proxy_connect_request.lock().await =
|
||||
Some(String::from_utf8(request).expect("CONNECT request should contain valid UTF-8"));
|
||||
|
||||
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;
|
||||
});
|
||||
|
||||
let target_authority = format!("localhost:{}", target_addr.port());
|
||||
let proxy_scheme = if proxy_tls { "https" } else { "http" };
|
||||
let request = format!("wss://{target_authority}/v1/responses")
|
||||
.into_client_request()
|
||||
.expect("websocket request should build");
|
||||
let (inner, _) = connect(
|
||||
request,
|
||||
WebSocketConfig::default(),
|
||||
Some(tls_config),
|
||||
OutboundProxyRoute::Proxy {
|
||||
url: format!("{proxy_scheme}://localhost:{}", proxy_addr.port()),
|
||||
no_proxy: None,
|
||||
},
|
||||
TcpNodelay::Enabled,
|
||||
/*loopback_direct*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("proxied websocket handshake should succeed");
|
||||
drop(test_connection(inner));
|
||||
|
||||
target_task.await.expect("target task should finish");
|
||||
proxy_task.await.expect("proxy task should finish");
|
||||
let request = connect_request
|
||||
.lock()
|
||||
.await
|
||||
.clone()
|
||||
.expect("proxy should record CONNECT request");
|
||||
let expected_request_line = format!("CONNECT {target_authority} HTTP/1.1");
|
||||
assert_eq!(request.lines().next(), Some(expected_request_line.as_str()));
|
||||
}
|
||||
|
||||
async fn start_tls_websocket_server(acceptor: TlsAcceptor) -> (SocketAddr, JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("target listener should bind");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("target listener should have an address");
|
||||
let task = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.expect("target should accept");
|
||||
let stream = acceptor
|
||||
.accept(stream)
|
||||
.await
|
||||
.expect("target TLS handshake should succeed");
|
||||
let mut websocket = accept_async(stream)
|
||||
.await
|
||||
.expect("target websocket handshake should succeed");
|
||||
let _ = websocket.close(None).await;
|
||||
});
|
||||
(address, task)
|
||||
}
|
||||
|
||||
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()])
|
||||
.expect("test certificate should generate");
|
||||
let certificate = cert.der().clone();
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(signing_key.serialize_der()));
|
||||
let server_config = ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![certificate.clone()], private_key)
|
||||
.expect("test server config should build");
|
||||
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots
|
||||
.add(certificate.clone())
|
||||
.expect("test certificate should be trusted");
|
||||
let client_config = ClientConfig::builder()
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth();
|
||||
|
||||
(
|
||||
Arc::new(client_config),
|
||||
TlsAcceptor::from(Arc::new(server_config)),
|
||||
certificate,
|
||||
)
|
||||
}
|
||||
|
||||
fn test_connection(inner: ConnectionInner) -> WebSocketConnection {
|
||||
let policy = codex_http_client::NetworkPolicy::unmanaged();
|
||||
let lease = policy
|
||||
.acquire(&url::Url::parse("wss://localhost/").unwrap())
|
||||
.unwrap();
|
||||
WebSocketConnection::new(inner, lease)
|
||||
}
|
||||
397
codex-rs/websocket-client/src/lib.rs
Normal file
397
codex-rs/websocket-client/src/lib.rs
Normal file
@@ -0,0 +1,397 @@
|
||||
//! Proxy-aware WebSocket connection setup shared by Codex API clients, reusing the HTTP factory's
|
||||
//! ChatGPT cookie store for secure handshakes.
|
||||
|
||||
mod dialer;
|
||||
|
||||
use std::io;
|
||||
use std::net::IpAddr;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
|
||||
use codex_http_client::BuildCustomCaTransportError;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPermit;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use codex_http_client::OutboundProxyRoute;
|
||||
use codex_http_client::build_rustls_client_config_with_custom_ca;
|
||||
use futures::FutureExt;
|
||||
use futures::Sink;
|
||||
use futures::Stream;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::future::Either;
|
||||
use rustls::ClientConfig;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_tungstenite::MaybeTlsStream;
|
||||
use tokio_tungstenite::WebSocketStream as TungsteniteStream;
|
||||
use tokio_tungstenite::tungstenite::Error as WebSocketError;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::handshake::client::Request;
|
||||
use tokio_tungstenite::tungstenite::handshake::client::Response;
|
||||
use tokio_tungstenite::tungstenite::http::Uri;
|
||||
use tokio_tungstenite::tungstenite::http::header::COOKIE;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
|
||||
/// Recovers a deterministic policy denial from Tungstenite's I/O error boundary.
|
||||
/// Callers must preserve this distinction when deciding whether to retry.
|
||||
pub fn network_policy_denial(error: &WebSocketError) -> Option<NetworkPolicyDenied> {
|
||||
match error {
|
||||
WebSocketError::Io(error) => error
|
||||
.get_ref()?
|
||||
.downcast_ref::<NetworkPolicyDenied>()
|
||||
.copied(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects WebSockets using the outbound proxy policy resolved by application configuration.
|
||||
///
|
||||
/// Construct this from the effective [`HttpClientFactory`] rather than selecting proxy behavior at
|
||||
/// individual call sites. Each connection resolves its destination through that factory before
|
||||
/// opening a socket.
|
||||
#[derive(Clone)]
|
||||
pub struct WebSocketConnector {
|
||||
http_client_factory: HttpClientFactory,
|
||||
tls_config: Option<Arc<ClientConfig>>,
|
||||
tcp_nodelay: TcpNodelay,
|
||||
}
|
||||
|
||||
/// Selects the TLS configuration used for WebSocket connections.
|
||||
#[derive(Clone)]
|
||||
pub enum WebSocketTlsMode {
|
||||
/// Build an explicit TLS configuration from native roots and configured Codex custom CAs.
|
||||
ExplicitCodexTls,
|
||||
/// Use an existing Rustls configuration.
|
||||
Rustls(Arc<ClientConfig>),
|
||||
/// Let Tungstenite build its default TLS configuration when the target requires TLS.
|
||||
TungsteniteDefault,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum TcpNodelay {
|
||||
Default,
|
||||
Enabled,
|
||||
}
|
||||
|
||||
impl WebSocketConnector {
|
||||
/// Creates a connector using native roots and any configured Codex custom CA bundle.
|
||||
pub fn new(
|
||||
http_client_factory: &HttpClientFactory,
|
||||
) -> Result<Self, BuildCustomCaTransportError> {
|
||||
Self::new_with_tls_mode(http_client_factory, WebSocketTlsMode::ExplicitCodexTls)
|
||||
}
|
||||
|
||||
/// Creates a connector with the selected WebSocket TLS configuration.
|
||||
///
|
||||
/// With [`WebSocketTlsMode::TungsteniteDefault`], HTTPS proxy connections still build Codex
|
||||
/// TLS configuration when they establish their proxy tunnel.
|
||||
pub fn new_with_tls_mode(
|
||||
http_client_factory: &HttpClientFactory,
|
||||
tls_mode: WebSocketTlsMode,
|
||||
) -> Result<Self, BuildCustomCaTransportError> {
|
||||
let tls_config = match tls_mode {
|
||||
WebSocketTlsMode::ExplicitCodexTls => {
|
||||
Some(build_rustls_client_config_with_custom_ca()?)
|
||||
}
|
||||
WebSocketTlsMode::Rustls(config) => Some(config),
|
||||
WebSocketTlsMode::TungsteniteDefault => None,
|
||||
};
|
||||
Ok(Self {
|
||||
http_client_factory: http_client_factory.clone(),
|
||||
tls_config,
|
||||
tcp_nodelay: TcpNodelay::Default,
|
||||
})
|
||||
}
|
||||
|
||||
/// Disables Nagle's algorithm for latency-sensitive WebSocket connections.
|
||||
pub fn with_tcp_nodelay(mut self) -> Self {
|
||||
self.tcp_nodelay = TcpNodelay::Enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Reuse the TLS/proxy configuration with a captured credential's account policy.
|
||||
pub fn with_account_binding(&self, policy: &codex_http_client::NetworkPolicy) -> Option<Self> {
|
||||
let policy = self
|
||||
.http_client_factory
|
||||
.network_policy()
|
||||
.clone()
|
||||
.with_account_binding(policy)?;
|
||||
Some(Self {
|
||||
http_client_factory: self.http_client_factory.clone().with_network_policy(policy),
|
||||
tls_config: self.tls_config.clone(),
|
||||
tcp_nodelay: self.tcp_nodelay,
|
||||
})
|
||||
}
|
||||
|
||||
/// Connects a WebSocket after resolving the request destination through the configured proxy
|
||||
/// policy.
|
||||
pub async fn connect(
|
||||
&self,
|
||||
request: Request,
|
||||
config: WebSocketConfig,
|
||||
) -> Result<(WebSocketConnection, Response), WebSocketError> {
|
||||
let route = self
|
||||
.http_client_factory
|
||||
.resolve_proxy_route_async(request.uri().to_string());
|
||||
self.connect_with_route(request, config, route, /*loopback_direct*/ false)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Connects to a validated loopback destination without consulting proxy settings.
|
||||
/// Application destination policy still applies before dialing.
|
||||
pub async fn connect_loopback_direct(
|
||||
&self,
|
||||
request: Request,
|
||||
config: WebSocketConfig,
|
||||
) -> Result<(WebSocketConnection, Response), WebSocketError> {
|
||||
if !is_loopback_destination(request.uri()) {
|
||||
return Err(WebSocketError::Io(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"direct WebSocket connections require a loopback destination",
|
||||
)));
|
||||
}
|
||||
self.connect_with_route(
|
||||
request,
|
||||
config,
|
||||
std::future::ready(Ok(OutboundProxyRoute::Direct)),
|
||||
/*loopback_direct*/ true,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn connect_with_route(
|
||||
&self,
|
||||
mut request: Request,
|
||||
config: WebSocketConfig,
|
||||
route: impl std::future::Future<Output = io::Result<OutboundProxyRoute>>,
|
||||
loopback_direct: bool,
|
||||
) -> Result<(WebSocketConnection, Response), WebSocketError> {
|
||||
let uri = request.uri().clone();
|
||||
let url = url::Url::parse(&uri.to_string()).map_err(|_| {
|
||||
WebSocketError::Io(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid WebSocket URL",
|
||||
))
|
||||
})?;
|
||||
let permit = self
|
||||
.http_client_factory
|
||||
.network_policy()
|
||||
.acquire(&url)
|
||||
.map_err(policy_error)?;
|
||||
let connect = async {
|
||||
if !request.headers().contains_key(COOKIE)
|
||||
&& let Some(cookies) = self.http_client_factory.chatgpt_cookie_header(&uri)
|
||||
{
|
||||
request.headers_mut().insert(COOKIE, cookies);
|
||||
}
|
||||
let proxy_route = route.await.map_err(WebSocketError::Io)?;
|
||||
let result = dialer::connect(
|
||||
request,
|
||||
config,
|
||||
self.tls_config.clone(),
|
||||
proxy_route,
|
||||
self.tcp_nodelay,
|
||||
loopback_direct,
|
||||
)
|
||||
.boxed()
|
||||
.await;
|
||||
// Like HTTP responses, rejected upgrades can also refresh infrastructure cookies.
|
||||
match &result {
|
||||
Ok((_, response)) => self
|
||||
.http_client_factory
|
||||
.store_chatgpt_response_cookies(&uri, response.headers()),
|
||||
Err(WebSocketError::Http(response)) => self
|
||||
.http_client_factory
|
||||
.store_chatgpt_response_cookies(&uri, response.headers()),
|
||||
Err(_) => {}
|
||||
}
|
||||
result.map(|(inner, response)| {
|
||||
let routing_affinity = codex_http_client::ChatGptRoutingAffinity::from_response(
|
||||
&uri,
|
||||
response.headers(),
|
||||
);
|
||||
(inner, response, routing_affinity)
|
||||
})
|
||||
};
|
||||
let (inner, response, routing_affinity) =
|
||||
permit.run(connect).await.map_err(policy_error)??;
|
||||
let mut connection = WebSocketConnection::new(inner, permit);
|
||||
connection.routing_affinity = routing_affinity;
|
||||
Ok((connection, response))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_loopback_destination(uri: &Uri) -> bool {
|
||||
let Some(host) = uri.host() else {
|
||||
return false;
|
||||
};
|
||||
let ip_address = host
|
||||
.strip_prefix('[')
|
||||
.and_then(|host| host.strip_suffix(']'))
|
||||
.unwrap_or(host);
|
||||
host.eq_ignore_ascii_case("localhost")
|
||||
|| ip_address
|
||||
.parse::<IpAddr>()
|
||||
.is_ok_and(|address| address.is_loopback())
|
||||
}
|
||||
|
||||
/// An established WebSocket independent of its direct, proxy, and TLS transport layers.
|
||||
///
|
||||
/// This implements [`Stream`] and [`Sink`] so protocol clients can process Tungstenite messages
|
||||
/// without knowing which concrete network stream route selection produced. Independent revocation
|
||||
/// waits preserve both task wakers when the stream and sink are split.
|
||||
pub struct WebSocketConnection {
|
||||
routing_affinity: Option<codex_http_client::ChatGptRoutingAffinity>,
|
||||
inner: Option<ConnectionInner>,
|
||||
permit: NetworkPermit,
|
||||
read_revoked: BoxFuture<'static, ()>,
|
||||
write_revoked: BoxFuture<'static, ()>,
|
||||
read_terminated: bool,
|
||||
}
|
||||
|
||||
enum ConnectionDirection {
|
||||
Read,
|
||||
Write,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for WebSocketConnection {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("WebSocketConnection")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl WebSocketConnection {
|
||||
fn new(inner: ConnectionInner, permit: NetworkPermit) -> Self {
|
||||
let read_permit = permit.clone();
|
||||
let write_permit = permit.clone();
|
||||
Self {
|
||||
routing_affinity: None,
|
||||
inner: Some(inner),
|
||||
permit,
|
||||
read_revoked: async move { read_permit.revoked().await }.boxed(),
|
||||
write_revoked: async move { write_permit.revoked().await }.boxed(),
|
||||
read_terminated: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The scoped routing cookie from this connection's handshake, never account cookies.
|
||||
pub fn routing_affinity(&self) -> Option<&codex_http_client::ChatGptRoutingAffinity> {
|
||||
self.routing_affinity.as_ref()
|
||||
}
|
||||
|
||||
fn poll_policy(
|
||||
&mut self,
|
||||
context: &mut Context<'_>,
|
||||
direction: ConnectionDirection,
|
||||
) -> Result<(), WebSocketError> {
|
||||
let revoked = match direction {
|
||||
ConnectionDirection::Read => &mut self.read_revoked,
|
||||
ConnectionDirection::Write => &mut self.write_revoked,
|
||||
};
|
||||
if self.permit.check().is_err() || revoked.poll_unpin(context).is_ready() {
|
||||
self.inner = None;
|
||||
return Err(policy_error(NetworkPolicyDenied::Revoked));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn policy_error(denied: NetworkPolicyDenied) -> WebSocketError {
|
||||
WebSocketError::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
denied,
|
||||
))
|
||||
}
|
||||
|
||||
impl Stream for WebSocketConnection {
|
||||
type Item = Result<Message, WebSocketError>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let connection = self.get_mut();
|
||||
if connection.read_terminated {
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
if let Err(error) = connection.poll_policy(context, ConnectionDirection::Read) {
|
||||
connection.read_terminated = true;
|
||||
return Poll::Ready(Some(Err(error)));
|
||||
}
|
||||
let next = match &mut connection.inner {
|
||||
Some(stream) => Pin::new(stream).poll_next(context),
|
||||
None => Poll::Ready(None),
|
||||
};
|
||||
if matches!(&next, Poll::Ready(None)) {
|
||||
connection.read_terminated = true;
|
||||
}
|
||||
next
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<Message> for WebSocketConnection {
|
||||
type Error = WebSocketError;
|
||||
|
||||
fn poll_ready(
|
||||
self: Pin<&mut Self>,
|
||||
context: &mut Context<'_>,
|
||||
) -> Poll<Result<(), Self::Error>> {
|
||||
let connection = self.get_mut();
|
||||
connection.poll_policy(context, ConnectionDirection::Write)?;
|
||||
match &mut connection.inner {
|
||||
Some(stream) => Pin::new(stream).poll_ready(context),
|
||||
None => Poll::Ready(Err(WebSocketError::ConnectionClosed)),
|
||||
}
|
||||
}
|
||||
|
||||
fn start_send(self: Pin<&mut Self>, message: Message) -> Result<(), Self::Error> {
|
||||
let connection = self.get_mut();
|
||||
if let Err(error) = connection.permit.check() {
|
||||
connection.inner = None;
|
||||
return Err(policy_error(error));
|
||||
}
|
||||
match &mut connection.inner {
|
||||
Some(stream) => Pin::new(stream).start_send(message),
|
||||
None => Err(WebSocketError::ConnectionClosed),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(
|
||||
self: Pin<&mut Self>,
|
||||
context: &mut Context<'_>,
|
||||
) -> Poll<Result<(), Self::Error>> {
|
||||
let connection = self.get_mut();
|
||||
connection.poll_policy(context, ConnectionDirection::Write)?;
|
||||
match &mut connection.inner {
|
||||
Some(stream) => Pin::new(stream).poll_flush(context),
|
||||
None => Poll::Ready(Err(WebSocketError::ConnectionClosed)),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_close(
|
||||
self: Pin<&mut Self>,
|
||||
context: &mut Context<'_>,
|
||||
) -> Poll<Result<(), Self::Error>> {
|
||||
let connection = self.get_mut();
|
||||
connection.poll_policy(context, ConnectionDirection::Write)?;
|
||||
match &mut connection.inner {
|
||||
Some(stream) => Pin::new(stream).poll_close(context),
|
||||
None => Poll::Ready(Ok(())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type ConnectionInner = Either<
|
||||
TungsteniteStream<MaybeTlsStream<TcpStream>>,
|
||||
TungsteniteStream<MaybeTlsStream<Box<dyn AsyncIo>>>,
|
||||
>;
|
||||
|
||||
/// Async network I/O carried through optional proxy and target TLS handshakes.
|
||||
pub(crate) trait AsyncIo: AsyncRead + AsyncWrite + Send + Unpin {}
|
||||
|
||||
impl<T> AsyncIo for T where T: AsyncRead + AsyncWrite + Send + Unpin {}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
39
codex-rs/websocket-client/src/lib_tests.rs
Normal file
39
codex-rs/websocket-client/src/lib_tests.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use tokio_tungstenite::tungstenite::http::Uri;
|
||||
|
||||
use super::is_loopback_destination;
|
||||
|
||||
#[test]
|
||||
fn recognizes_loopback_websocket_destinations() {
|
||||
for destination in [
|
||||
"ws://localhost:8080",
|
||||
"ws://LOCALHOST:8080",
|
||||
"ws://127.0.0.1:8080",
|
||||
"ws://[::1]:8080",
|
||||
] {
|
||||
let uri = destination.parse::<Uri>().unwrap();
|
||||
assert!(
|
||||
is_loopback_destination(&uri),
|
||||
"expected loopback destination: {destination}; parsed host: {:?}",
|
||||
uri.host()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_loopback_websocket_destinations() {
|
||||
for destination in [
|
||||
"ws://relay.example:8080",
|
||||
"ws://192.0.2.1:8080",
|
||||
"ws://[2001:db8::1]:8080",
|
||||
"/missing-host",
|
||||
] {
|
||||
assert!(!is_loopback_destination(
|
||||
&destination.parse::<Uri>().unwrap()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "cookie_tests.rs"]
|
||||
mod cookie_tests;
|
||||
#[path = "network_policy_tests.rs"]
|
||||
mod network_policy_tests;
|
||||
54
codex-rs/websocket-client/src/network_policy_tests.rs
Normal file
54
codex-rs/websocket-client/src/network_policy_tests.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
//! Split readers keep their revocation wakeup and report denial even when writers fail first.
|
||||
|
||||
use crate::*;
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::NetworkPolicyController;
|
||||
use codex_http_client::OutboundProxyPolicy::ReqwestDefault;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
|
||||
struct WakeFlag(AtomicBool);
|
||||
|
||||
impl futures::task::ArcWake for WakeFlag {
|
||||
fn wake_by_ref(waker: &Arc<Self>) {
|
||||
waker.0.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revocation_wakes_split_reader_and_survives_writer_observing_it_first() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/", listener.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut websocket = tokio_tungstenite::accept_async(stream).await.unwrap();
|
||||
let _ = websocket.next().await;
|
||||
});
|
||||
let controller = NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
let factory = HttpClientFactory::new(ReqwestDefault).with_network_policy(policy.clone());
|
||||
let connector = WebSocketConnector::new(&factory).unwrap();
|
||||
let request = url.into_client_request().unwrap();
|
||||
let (connection, _) = connector
|
||||
.connect(request, WebSocketConfig::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let (mut writer, mut reader) = connection.split();
|
||||
let wake = Arc::new(WakeFlag(AtomicBool::new(false)));
|
||||
let waker = futures::task::waker(Arc::clone(&wake));
|
||||
let mut context = Context::from_waker(&waker);
|
||||
assert!(Pin::new(&mut reader).poll_next(&mut context).is_pending());
|
||||
writer.flush().await.unwrap();
|
||||
policy.invalidate();
|
||||
assert!(wake.0.load(Ordering::SeqCst));
|
||||
let error = writer.flush().await.unwrap_err();
|
||||
assert!(network_policy_denial(&error).is_some());
|
||||
let error = reader.next().await.unwrap().unwrap_err();
|
||||
assert!(network_policy_denial(&error).is_some());
|
||||
assert!(reader.next().await.is_none());
|
||||
server.abort();
|
||||
}
|
||||
Reference in New Issue
Block a user