mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Connect Codex Desktop MCP over Unix sockets (#63497)
## Why An SSH forward can replace its Unix socket listener while the old keep-alive connection remains open. Reusing that connection can leave MCP requests waiting on the old listener. ## What changed Route `codex-desktop://<uuid>` endpoints to the corresponding Unix socket for local `codex_app` servers with explicit HTTP authorization. Allow `http_headers_helper` to supply supplemental headers while preserving the configured authorization. Socket requests bypass proxies, strip `Proxy-Authorization`, and disable redirects. Reuse pooled connections while the socket is unchanged and discard them when the listener is replaced or the socket disappears. ## Testing Add coverage for authenticated Desktop startup, rejection of helper-only authorization and other server names, and reconnection after socket replacement while the previous connection remains open. GitOrigin-RevId: a38e55d8cd726299506b487d1223fe64bd856e80
This commit is contained in:
@@ -46,6 +46,8 @@ pub struct HttpClientBuilder {
|
||||
pub(crate) request_logging: RequestLogging,
|
||||
tls_backend: TlsBackend,
|
||||
pub(crate) tls: HttpClientTlsConfig,
|
||||
#[cfg(unix)]
|
||||
pub(crate) unix_socket: Option<std::path::PathBuf>,
|
||||
#[cfg(windows)]
|
||||
windows_proxy_pipe_path: Option<std::path::PathBuf>,
|
||||
}
|
||||
@@ -397,6 +399,10 @@ impl HttpClientBuilder {
|
||||
|
||||
fn base_reqwest_builder(self) -> reqwest::ClientBuilder {
|
||||
let mut builder = reqwest::Client::builder();
|
||||
#[cfg(unix)]
|
||||
if let Some(path) = self.unix_socket {
|
||||
builder = builder.unix_socket(path);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if let Some(path) = self.windows_proxy_pipe_path {
|
||||
builder = builder.windows_named_pipe(path);
|
||||
@@ -460,6 +466,8 @@ impl Default for HttpClientBuilder {
|
||||
request_logging: RequestLogging::Enabled,
|
||||
tls_backend: TlsBackend::TransportDefault,
|
||||
tls: HttpClientTlsConfig::default(),
|
||||
#[cfg(unix)]
|
||||
unix_socket: None,
|
||||
#[cfg(windows)]
|
||||
windows_proxy_pipe_path: None,
|
||||
}
|
||||
|
||||
@@ -45,6 +45,12 @@ enum SelectedTlsBackend {
|
||||
RustlsFallback,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClientBuildState {
|
||||
#[cfg(unix)]
|
||||
socket_identity: Option<(u64, u64, i64, i64)>,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -59,7 +65,7 @@ pub struct RouteAwareClientPool {
|
||||
custom_ca_fallback: CustomCaFallback,
|
||||
direct_proxy: bool,
|
||||
clients: Arc<Mutex<HashMap<OutboundProxyRoute, TransportClient>>>,
|
||||
client_build: Arc<tokio::sync::Mutex<()>>,
|
||||
client_build: Arc<tokio::sync::Mutex<ClientBuildState>>,
|
||||
rustls_clients: Option<RustlsClientCache>,
|
||||
}
|
||||
|
||||
@@ -234,6 +240,16 @@ impl RouteAwareClientPool {
|
||||
Self::with_builder(http_client_factory, route_class, HttpClientBuilder::new())
|
||||
}
|
||||
|
||||
/// A Unix socket supplies the peer, so neither proxies nor redirects apply.
|
||||
#[cfg(unix)]
|
||||
pub fn for_unix_socket(factory: HttpClientFactory, path: std::path::PathBuf) -> Self {
|
||||
let mut pool =
|
||||
Self::new_without_redirects_or_request_logging(factory, ClientRouteClass::Other)
|
||||
.with_direct_proxy();
|
||||
pool.client_builder.unix_socket = Some(path);
|
||||
pool
|
||||
}
|
||||
|
||||
/// Creates a pool that returns redirect responses without following them.
|
||||
///
|
||||
/// This applies both when reqwest owns redirect handling and when the pool follows redirects
|
||||
@@ -508,6 +524,31 @@ impl RouteAwareClientPool {
|
||||
.await
|
||||
.map_err(RouteAwareClientPoolError::Resolve)?
|
||||
};
|
||||
#[cfg(unix)]
|
||||
if let Some(path) = self.client_builder.unix_socket.clone() {
|
||||
// SSH can replace the listener while the old keep-alive connection stays
|
||||
// open. Serialize the identity check and eviction with transport builds.
|
||||
let mut build = Arc::clone(&self.client_build).lock_owned().await;
|
||||
let clients = Arc::clone(&self.clients);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
// Include ctime in case the filesystem recycles the inode.
|
||||
let identity = std::fs::metadata(path)
|
||||
.ok()
|
||||
.map(|meta| (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec()));
|
||||
if identity.is_none() || identity != build.socket_identity {
|
||||
clients
|
||||
.lock()
|
||||
.unwrap_or_else(|error| {
|
||||
panic!("route-aware client cache lock should not be poisoned: {error}")
|
||||
})
|
||||
.clear();
|
||||
build.socket_identity = identity;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(RouteAwareClientPoolError::BuildTask)?;
|
||||
}
|
||||
if let Some(rustls_clients) = self.rustls_clients.as_ref()
|
||||
&& let Ok(url) = reqwest::Url::parse(request_url)
|
||||
&& rustls_clients.requires_rustls(&url, &route)
|
||||
|
||||
@@ -114,6 +114,10 @@ impl RouteAwareClientPool {
|
||||
request_url = request.url().to_string();
|
||||
apply_default_headers(request.headers_mut(), &self.default_headers);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if self.client_builder.unix_socket.is_some() {
|
||||
request.headers_mut().remove(PROXY_AUTHORIZATION);
|
||||
}
|
||||
let current_url = request.url().clone();
|
||||
if previous_route
|
||||
.as_ref()
|
||||
|
||||
@@ -23,6 +23,74 @@ use super::*;
|
||||
use crate::OutboundProxyPolicy;
|
||||
use crate::request_draft::RequestDraft;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn unix_socket_reuses_authenticated_connection_until_listener_is_replaced() {
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::net::UnixListener;
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
async fn respond(stream: &mut BufReader<UnixStream>) {
|
||||
let mut headers = String::new();
|
||||
while !headers.ends_with("\r\n\r\n") {
|
||||
assert_ne!(stream.read_line(&mut headers).await.unwrap(), 0);
|
||||
}
|
||||
let received = headers.to_ascii_lowercase();
|
||||
assert!(received.contains("\r\nauthorization: bearer desktop-test\r\n"));
|
||||
assert!(!received.contains("\r\nproxy-authorization:"));
|
||||
stream
|
||||
.get_mut()
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let dir = tempfile::tempdir_in("/tmp").unwrap();
|
||||
let path = dir.path().join("desktop.sock");
|
||||
let listener = UnixListener::bind(&path).unwrap();
|
||||
let pool = RouteAwareClientPool::for_unix_socket(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
|
||||
path.clone(),
|
||||
);
|
||||
let call = || async {
|
||||
let mut request =
|
||||
reqwest::Request::new(Method::POST, "http://127.0.0.1:0/mcp".parse().unwrap());
|
||||
request.headers_mut().insert(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer desktop-test"),
|
||||
);
|
||||
let response = pool
|
||||
.send_with_resolver(request, |_| async {
|
||||
Ok(OutboundProxyRoute::Proxy {
|
||||
url: "http://proxy-user:proxy-test@127.0.0.1:1".into(),
|
||||
no_proxy: None,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
let (_, mut old) = tokio::join!(call(), async {
|
||||
let mut stream = BufReader::new(listener.accept().await.unwrap().0);
|
||||
respond(&mut stream).await;
|
||||
stream
|
||||
});
|
||||
tokio::join!(call(), respond(&mut old));
|
||||
// The old SSH connection is still open but will never answer another request.
|
||||
let staged = dir.path().join("forward.sock");
|
||||
let replacement = UnixListener::bind(&staged).unwrap();
|
||||
std::fs::rename(staged, &path).unwrap();
|
||||
tokio::join!(call(), async {
|
||||
respond(&mut BufReader::new(replacement.accept().await.unwrap().0)).await;
|
||||
});
|
||||
})
|
||||
.await
|
||||
.expect("the same pool should reach the replacement socket");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redirects_honor_sensitive_header_protection_without_changing_default_behavior() {
|
||||
for policy in [
|
||||
|
||||
Reference in New Issue
Block a user