diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 0c1ac879b6..6b95e9f6ca 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -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", diff --git a/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs b/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs index d522b3c1b9..24525959f9 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs @@ -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, ) -> 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, + 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<()>)> { diff --git a/codex-rs/codex-mcp/Cargo.toml b/codex-rs/codex-mcp/Cargo.toml index ab46c5fec0..7ec044f54b 100644 --- a/codex-rs/codex-mcp/Cargo.toml +++ b/codex-rs/codex-mcp/Cargo.toml @@ -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 } diff --git a/codex-rs/codex-mcp/src/rmcp_client.rs b/codex-rs/codex-mcp/src/rmcp_client.rs index 672eeaf967..de6b9162a8 100644 --- a/codex-rs/codex-mcp/src/rmcp_client.rs +++ b/codex-rs/codex-mcp/src/rmcp_client.rs @@ -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() diff --git a/codex-rs/codex-mcp/src/runtime.rs b/codex-rs/codex-mcp/src/runtime.rs index 096d94f6e1..b134d0bb47 100644 --- a/codex-rs/codex-mcp/src/runtime.rs +++ b/codex-rs/codex-mcp/src/runtime.rs @@ -1219,6 +1219,15 @@ pub fn apply_http_headers_helper( client: Arc, config: &codex_config::McpServerConfig, local_process_cwd: PathBuf, +) -> Result, String> { + apply_http_headers_helper_at(client, config, local_process_cwd, /*wire_url*/ None) +} + +pub(crate) fn apply_http_headers_helper_at( + client: Arc, + config: &codex_config::McpServerConfig, + local_process_cwd: PathBuf, + wire_url: Option<&str>, ) -> Result, 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> { + 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, diff --git a/codex-rs/exec-server/src/client/route_aware_http_client.rs b/codex-rs/exec-server/src/client/route_aware_http_client.rs index 66c82bc9e5..e852fa8c9f 100644 --- a/codex-rs/exec-server/src/client/route_aware_http_client.rs +++ b/codex-rs/exec-server/src/client/route_aware_http_client.rs @@ -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( diff --git a/codex-rs/http-client/src/client_builder.rs b/codex-rs/http-client/src/client_builder.rs index 11bda2acae..982402ac26 100644 --- a/codex-rs/http-client/src/client_builder.rs +++ b/codex-rs/http-client/src/client_builder.rs @@ -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, #[cfg(windows)] windows_proxy_pipe_path: Option, } @@ -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, } diff --git a/codex-rs/http-client/src/route_aware_client_pool.rs b/codex-rs/http-client/src/route_aware_client_pool.rs index 796a4a2659..558a58fccb 100644 --- a/codex-rs/http-client/src/route_aware_client_pool.rs +++ b/codex-rs/http-client/src/route_aware_client_pool.rs @@ -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>>, - client_build: Arc>, + client_build: Arc>, rustls_clients: Option, } @@ -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) diff --git a/codex-rs/http-client/src/route_aware_client_pool/execution.rs b/codex-rs/http-client/src/route_aware_client_pool/execution.rs index 06be14c9a5..b141447f31 100644 --- a/codex-rs/http-client/src/route_aware_client_pool/execution.rs +++ b/codex-rs/http-client/src/route_aware_client_pool/execution.rs @@ -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() diff --git a/codex-rs/http-client/src/route_aware_client_pool_tests.rs b/codex-rs/http-client/src/route_aware_client_pool_tests.rs index d02f8814a1..c3cd386e9d 100644 --- a/codex-rs/http-client/src/route_aware_client_pool_tests.rs +++ b/codex-rs/http-client/src/route_aware_client_pool_tests.rs @@ -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) { + 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 [