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:
Brent Traut
2026-11-24 02:20:22 +00:00
committed by copyberry
parent 188940258d
commit 6aaf2a86b1
10 changed files with 270 additions and 14 deletions
+1
View File
@@ -4241,6 +4241,7 @@ dependencies = [
"codex-protocol",
"codex-rmcp-client",
"codex-runtime-agent-instance",
"codex-uds",
"codex-utils-absolute-path",
"codex-utils-cargo-bin",
"codex-utils-path-uri",
@@ -86,6 +86,70 @@ use wiremock::matchers::path;
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
#[cfg(unix)]
#[test_case("codex_app", Some("Bearer desktop"), true; "authenticated Desktop")]
#[test_case("codex_app", None, false; "helper alone cannot authorize Desktop")]
#[test_case("other", Some("Bearer desktop"), false; "another server cannot use the socket")]
#[tokio::test]
async fn desktop_socket_mcp_startup(
name: &str,
authorization: Option<&str>,
expect_connection: bool,
) -> Result<()> {
let id = uuid::Uuid::now_v7();
let path =
codex_uds::prepare_shared_daemon_socket_directory()?.join(format!("desktop-{id}.sock"));
let listener = tokio::net::UnixListener::bind(&path)?;
let _socket = tempfile::TempPath::try_from_path(path)?;
let (seen, mut requests) = mpsc::unbounded_channel();
let router = mcp_status_router("lookup", /*tools_error*/ None, "desktop".to_owned()).layer(
axum::middleware::from_fn(
move |headers: HeaderMap, request, next: axum::middleware::Next| {
let _ = seen.send(headers);
async move { next.run(request).await }
},
),
);
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let mut config = json!({
"url": format!("codex-desktop://{id}"),
"required": true,
"http_headers_helper": r#"printf '%s' '{"X-Extra":"from-helper","Authorization":"Bearer helper","Proxy-Authorization":"Basic test-proxy"}'"#,
});
if let Some(value) = authorization {
config["http_headers"] = json!({"Authorization": value});
}
let mut app = TestAppServer::builder().build_initialized().await?;
let params = ThreadStartParams {
config: Some([("mcp_servers".into(), json!({name: config}))].into()),
..Default::default()
};
if expect_connection {
app.start_thread(params).await?;
let captured: Vec<_> = std::iter::from_fn(|| requests.try_recv().ok()).collect();
assert!(!captured.is_empty());
for headers in captured {
assert_eq!(
["authorization", "x-extra", "proxy-authorization"]
.map(|name| headers.get(name).map(axum::http::HeaderValue::as_bytes)),
[authorization.map(str::as_bytes), Some(b"from-helper"), None],
);
}
} else {
let id = app.send_thread_start_request_with_auto_env(params).await?;
let error = timeout(
DEFAULT_READ_TIMEOUT,
app.read_stream_until_error_message(RequestId::Integer(id)),
)
.await??
.error;
assert!(error.message.contains("Desktop MCP requires"), "{error:?}");
assert!(requests.try_recv().is_err());
}
server.abort();
Ok(())
}
async fn recording_widget_server() -> (MockServer, serde_json::Value) {
let server = MockServer::start().await;
let tool = json!({
@@ -1972,26 +2036,32 @@ async fn start_mcp_server(
tools_error: Option<rmcp::ErrorData>,
) -> Result<(String, JoinHandle<()>)> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let addr = listener.local_addr()?;
let origin = format!("http://{}", listener.local_addr()?);
let router = mcp_status_router(tool_name, tools_error, origin.clone());
let handle = tokio::spawn(async move {
let _ = axum::serve(listener, router).await;
});
Ok((origin, handle))
}
fn mcp_status_router(
tool_name: &str,
tools_error: Option<rmcp::ErrorData>,
origin: String,
) -> Router {
let tool_name = Arc::new(tool_name.to_string());
let mcp_service = StreamableHttpService::new(
move || {
Ok(McpStatusServer {
tool_name: Arc::clone(&tool_name),
tools_error: tools_error.clone(),
origin: format!("http://{addr}"),
origin: origin.clone(),
})
},
Arc::new(LocalSessionManager::default()),
StreamableHttpServerConfig::default(),
);
let router = Router::new().nest_service("/mcp", mcp_service);
let handle = tokio::spawn(async move {
let _ = axum::serve(listener, router).await;
});
Ok((format!("http://{addr}"), handle))
Router::new().nest_service("/mcp", mcp_service)
}
async fn start_slow_inventory_mcp_server(tool_name: &str) -> Result<(String, JoinHandle<()>)> {
+1
View File
@@ -31,6 +31,7 @@ codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-rmcp-client = { workspace = true }
codex-runtime-agent-instance = { workspace = true }
codex-uds = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-path-uri = { workspace = true }
codex-utils-plugins = { workspace = true }
+34 -3
View File
@@ -1610,9 +1610,40 @@ pub(crate) async fn make_rmcp_client(
}
None => (None, runtime_context),
};
let http_client = runtime_context
.http_client_for_server(server.config(), resolved_environment.as_ref())
.map_err(|error| StartupOutcomeError::from(anyhow!(error)))?;
let (url, http_client) = match url.strip_prefix("codex-desktop://") {
#[cfg(unix)]
Some(id) => {
if server_name != "codex_app"
|| !is_local_environment
|| !has_explicit_http_authorization(server.config())
{
return Err(anyhow!(
"Desktop MCP requires a local, authenticated codex_app server"
)
.into());
}
let id = uuid::Uuid::parse_str(id).map_err(anyhow::Error::from)?;
let client = runtime_context
.desktop_http_client(id)
.map_err(anyhow::Error::from)?;
// Only the HTTP path and Host go on the wire. The socket supplies the peer.
let url = "http://127.0.0.1:0/mcp";
let client = crate::runtime::apply_http_headers_helper_at(
client,
server.config(),
runtime_context.local_process_cwd(),
Some(url),
)
.map_err(anyhow::Error::msg)?;
(url.to_owned(), client)
}
_ => {
let client = runtime_context
.http_client_for_server(server.config(), resolved_environment.as_ref())
.map_err(|error| StartupOutcomeError::from(anyhow!(error)))?;
(url, client)
}
};
let http_client = maybe_with_openai_docs_source_attribution(&url, http_client);
let executor_resolves_bearer_token = if !is_local_environment
&& bearer_token_env_var.is_some()
+23 -1
View File
@@ -1219,6 +1219,15 @@ pub fn apply_http_headers_helper(
client: Arc<dyn HttpClient>,
config: &codex_config::McpServerConfig,
local_process_cwd: PathBuf,
) -> Result<Arc<dyn HttpClient>, String> {
apply_http_headers_helper_at(client, config, local_process_cwd, /*wire_url*/ None)
}
pub(crate) fn apply_http_headers_helper_at(
client: Arc<dyn HttpClient>,
config: &codex_config::McpServerConfig,
local_process_cwd: PathBuf,
wire_url: Option<&str>,
) -> Result<Arc<dyn HttpClient>, String> {
if matches!(
config.disabled_reason,
@@ -1240,7 +1249,7 @@ pub fn apply_http_headers_helper(
if !config.is_local_environment() {
return Err("HTTP headers helpers can only run in the local environment".to_string());
}
with_http_headers_helper(client, url, command, local_process_cwd)
with_http_headers_helper(client, wire_url.unwrap_or(url), command, local_process_cwd)
.map_err(|error| error.to_string())
}
@@ -1293,6 +1302,19 @@ impl McpRuntimeContext {
Arc::clone(&self.local_http_client)
}
#[cfg(unix)]
pub(crate) fn desktop_http_client(
&self,
id: uuid::Uuid,
) -> std::io::Result<Arc<dyn HttpClient>> {
let path =
codex_uds::prepare_shared_daemon_socket_directory()?.join(format!("desktop-{id}.sock"));
Ok(Arc::new(RouteAwareHttpClient::for_unix_socket(
self.environment_manager.http_client_factory().clone(),
path,
)))
}
pub(crate) fn resolve_server_environment(
&self,
server_name: &str,
@@ -79,6 +79,16 @@ pub(crate) struct RouteAwareHttpRequestRunner {
}
impl RouteAwareHttpClient {
/// HTTP over a local socket never follows redirects to another server.
#[cfg(unix)]
pub fn for_unix_socket(factory: HttpClientFactory, path: std::path::PathBuf) -> Self {
let pool = RouteAwareClientPool::for_unix_socket(factory, path);
Self {
follow_redirects: pool.clone(),
stop_redirects: pool,
}
}
pub fn new(http_client_factory: HttpClientFactory) -> Self {
Self {
follow_redirects: RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging(
@@ -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 [