mirror of
https://github.com/openai/codex.git
synced 2026-11-17 22:10:37 +00:00
Route MCP auth discovery through runtime HTTP clients (#35239)
## Why MCP authentication checks need to use the same HTTP routing as the MCP transport so servers reached through configured proxies can be discovered reliably. ## What changed - Resolve OAuth discovery and authentication status through each server's runtime HTTP client for both local and managed environments. - Keep local discovery capped at five seconds while allowing explicit login requests to retain their requested timeout. - Resolve refreshed MCP configuration and its runtime context from the same snapshot. ## Testing - Cover OAuth discovery through an environment proxy and macOS system proxy resolution. - Cover proxied MCP startup and runtime refresh with updated authorization headers. - Verify capped and preserved OAuth discovery timeout policies. GitOrigin-RevId: 461fb1d4786e547df8b1e6b2215a8ac40438a3aa
This commit is contained in:
@@ -1,4 +1,9 @@
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::net::TcpListener;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
@@ -10,6 +15,16 @@ use pretty_assertions::assert_eq;
|
||||
use serde_json::Value as JsonValue;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
#[cfg(target_os = "macos")]
|
||||
use wiremock::Mock;
|
||||
#[cfg(target_os = "macos")]
|
||||
use wiremock::MockServer;
|
||||
#[cfg(target_os = "macos")]
|
||||
use wiremock::ResponseTemplate;
|
||||
#[cfg(target_os = "macos")]
|
||||
use wiremock::matchers::method;
|
||||
#[cfg(target_os = "macos")]
|
||||
use wiremock::matchers::path;
|
||||
|
||||
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
|
||||
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
@@ -17,6 +32,18 @@ fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
async fn configure_http_oauth_server(codex_home: &Path, url: &str) -> Result<()> {
|
||||
let mut servers = load_global_mcp_servers(codex_home).await?;
|
||||
servers.insert(
|
||||
"oauth".to_string(),
|
||||
toml::from_str(&format!("url = \"{url}\""))?,
|
||||
);
|
||||
ConfigEditsBuilder::new(codex_home)
|
||||
.replace_mcp_servers(&servers)
|
||||
.apply_blocking()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_shows_empty_state() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
@@ -30,6 +57,175 @@ fn list_shows_empty_state() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_discovers_local_oauth_server_through_environment_proxy() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
configure_http_oauth_server(codex_home.path(), "http://mcp-proxy.invalid/mcp").await?;
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0")?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let proxy_url = format!("http://{}", listener.local_addr()?);
|
||||
let proxy = std::thread::spawn(move || -> Result<Vec<String>> {
|
||||
let resource_metadata = json!({
|
||||
"resource": "http://mcp-proxy.invalid/mcp",
|
||||
"authorization_servers": ["http://mcp-proxy.invalid"],
|
||||
})
|
||||
.to_string();
|
||||
let authorization_metadata = json!({
|
||||
"authorization_endpoint": "https://oauth.example/authorize",
|
||||
"token_endpoint": "https://oauth.example/token",
|
||||
})
|
||||
.to_string();
|
||||
let responses = [
|
||||
concat!(
|
||||
"HTTP/1.1 401 Unauthorized\r\n",
|
||||
"www-authenticate: Bearer resource_metadata=\"http://mcp-proxy.invalid/oauth-resource\"\r\n",
|
||||
"content-length: 0\r\n",
|
||||
"connection: close\r\n\r\n"
|
||||
)
|
||||
.to_string(),
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{resource_metadata}",
|
||||
resource_metadata.len()
|
||||
),
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{authorization_metadata}",
|
||||
authorization_metadata.len()
|
||||
),
|
||||
];
|
||||
|
||||
let mut requests = Vec::new();
|
||||
for response in responses {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let mut stream = loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => break stream,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
anyhow::ensure!(
|
||||
Instant::now() < deadline,
|
||||
"proxy did not receive OAuth discovery request {}",
|
||||
requests.len() + 1
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
};
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
let mut request = Vec::new();
|
||||
let mut buffer = [0_u8; 1024];
|
||||
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
|
||||
let bytes_read = stream.read(&mut buffer)?;
|
||||
anyhow::ensure!(bytes_read > 0, "proxy request ended before its headers");
|
||||
request.extend_from_slice(&buffer[..bytes_read]);
|
||||
anyhow::ensure!(
|
||||
request.len() <= 64 * 1024,
|
||||
"proxy request headers are too large"
|
||||
);
|
||||
}
|
||||
let request = String::from_utf8(request)?;
|
||||
requests.push(request.lines().next().unwrap_or_default().to_string());
|
||||
stream.write_all(response.as_bytes())?;
|
||||
}
|
||||
|
||||
Ok(requests)
|
||||
});
|
||||
|
||||
let mut command = codex_command(codex_home.path())?;
|
||||
command
|
||||
.env("HTTP_PROXY", &proxy_url)
|
||||
.env("http_proxy", &proxy_url)
|
||||
.env_remove("HTTPS_PROXY")
|
||||
.env_remove("https_proxy")
|
||||
.env_remove("ALL_PROXY")
|
||||
.env_remove("all_proxy")
|
||||
.env_remove("NO_PROXY")
|
||||
.env_remove("no_proxy")
|
||||
.args([
|
||||
"-c",
|
||||
"mcp_oauth_credentials_store=\"file\"",
|
||||
"mcp",
|
||||
"list",
|
||||
"--json",
|
||||
]);
|
||||
let output = command.output()?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"mcp list failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let proxy_requests = proxy
|
||||
.join()
|
||||
.expect("OAuth discovery proxy thread should finish")?;
|
||||
|
||||
assert_eq!(
|
||||
proxy_requests,
|
||||
vec![
|
||||
"GET http://mcp-proxy.invalid/mcp HTTP/1.1",
|
||||
"GET http://mcp-proxy.invalid/oauth-resource HTTP/1.1",
|
||||
"GET http://mcp-proxy.invalid/.well-known/oauth-authorization-server HTTP/1.1",
|
||||
]
|
||||
);
|
||||
let entries: JsonValue = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(entries[0]["name"], "oauth");
|
||||
assert_eq!(
|
||||
entries[0]["auth_status"],
|
||||
"not_logged_in",
|
||||
"OAuth discovery failed after proxy requests {proxy_requests:?}; stderr: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn list_with_macos_proxy_resolution_does_not_panic() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/.well-known/oauth-authorization-server/mcp"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"authorization_endpoint": "https://oauth.example/authorize",
|
||||
"token_endpoint": "https://oauth.example/token",
|
||||
})))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
configure_http_oauth_server(codex_home.path(), &format!("{}/mcp", server.uri())).await?;
|
||||
|
||||
for respect_system_proxy in [false, true] {
|
||||
let system_proxy_override = format!("features.respect_system_proxy={respect_system_proxy}");
|
||||
let mut command = codex_command(codex_home.path())?;
|
||||
command
|
||||
.env_remove("HTTP_PROXY")
|
||||
.env_remove("http_proxy")
|
||||
.env_remove("HTTPS_PROXY")
|
||||
.env_remove("https_proxy")
|
||||
.env_remove("ALL_PROXY")
|
||||
.env_remove("all_proxy")
|
||||
.env_remove("NO_PROXY")
|
||||
.env_remove("no_proxy")
|
||||
.args([
|
||||
"-c",
|
||||
&system_proxy_override,
|
||||
"-c",
|
||||
"mcp_oauth_credentials_store=\"file\"",
|
||||
"mcp",
|
||||
"list",
|
||||
"--json",
|
||||
]);
|
||||
let output = command.output()?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"macOS proxy resolution should not panic with respect_system_proxy={respect_system_proxy}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let entries: JsonValue = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(entries[0]["auth_status"], "not_logged_in");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_and_get_render_expected_output() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
Reference in New Issue
Block a user