mirror of
https://github.com/openai/codex.git
synced 2026-11-17 14:58:36 +00:00
Add per-login MCP OAuth client registration selection (#38052)
## What changed - Add `--oauth-client-registration` with `auto` and `dcr` choices to `codex mcp add` and `codex mcp login`. - Add the equivalent optional `clientRegistration` field to `mcpServer/oauth/login` and the generated protocol schemas. - Keep automatic dynamic client registration as the default, prefer a configured OAuth client ID when present, and apply the selection only to the current login without persisting it in MCP configuration. ## Testing - Cover dynamic registration and configured-client OAuth flows through the app server. - Verify the CLI does not persist the per-login registration choice. GitOrigin-RevId: 653a4a1054ff43c2c5d52ae863b6a96d21692a53
This commit is contained in:
1 parent
965b9f263a
commit
6dc3ac8721
22 files changed
+407
-65
No files matched your search
@@ -8,6 +8,7 @@ mod incoming_jsonrpc;
|
||||
mod local_stdio_transport;
|
||||
mod logging_client_handler;
|
||||
mod oauth;
|
||||
mod oauth_client_registration;
|
||||
mod oauth_http_client;
|
||||
mod perform_oauth_login;
|
||||
mod program_resolver;
|
||||
@@ -35,6 +36,7 @@ pub use oauth::delete_oauth_tokens;
|
||||
pub use oauth::save_oauth_tokens;
|
||||
pub use oauth::stored_oauth_credential_snapshot;
|
||||
pub use oauth::stored_oauth_credentials;
|
||||
pub use oauth_client_registration::McpOAuthClientRegistration;
|
||||
pub use perform_oauth_login::OAuthProviderError;
|
||||
pub use perform_oauth_login::OauthLoginHandle;
|
||||
pub use perform_oauth_login::perform_oauth_login;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use rmcp::transport::AuthorizationManager;
|
||||
use rmcp::transport::AuthorizationRequest;
|
||||
use rmcp::transport::auth::OAuthHttpClient;
|
||||
use rmcp::transport::auth::OAuthState;
|
||||
|
||||
/// OAuth client-registration strategy for one interactive HTTP MCP login.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum McpOAuthClientRegistration {
|
||||
/// Preserve the current automatic Dynamic Client Registration flow.
|
||||
#[default]
|
||||
Auto,
|
||||
/// Require the authorization server's Dynamic Client Registration endpoint.
|
||||
Dcr,
|
||||
}
|
||||
|
||||
pub(crate) async fn start_authorization(
|
||||
server_url: &str,
|
||||
http_client: Arc<dyn OAuthHttpClient>,
|
||||
scopes: &[&str],
|
||||
redirect_uri: &str,
|
||||
client_registration: McpOAuthClientRegistration,
|
||||
) -> Result<OAuthState> {
|
||||
let request = match client_registration {
|
||||
McpOAuthClientRegistration::Auto | McpOAuthClientRegistration::Dcr => {
|
||||
AuthorizationRequest::new(redirect_uri)
|
||||
.with_scopes(scopes.iter().copied())
|
||||
.with_client_name("Codex")
|
||||
}
|
||||
};
|
||||
|
||||
let mut auth_manager =
|
||||
AuthorizationManager::new_with_oauth_http_client(server_url, http_client).await?;
|
||||
auth_manager.set_allow_missing_issuer(true);
|
||||
let mut oauth_state = OAuthState::Unauthorized(auth_manager);
|
||||
oauth_state.start_authorization(request).await?;
|
||||
Ok(oauth_state)
|
||||
}
|
||||
@@ -11,7 +11,6 @@ use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use codex_exec_server::HttpClient;
|
||||
use rmcp::transport::AuthorizationManager;
|
||||
use rmcp::transport::AuthorizationRequest;
|
||||
use rmcp::transport::AuthorizationSession;
|
||||
use rmcp::transport::auth::OAuthClientConfig;
|
||||
use rmcp::transport::auth::OAuthHttpClient;
|
||||
@@ -29,6 +28,8 @@ use crate::StoredOAuthTokens;
|
||||
use crate::WrappedOAuthTokenResponse;
|
||||
use crate::http_client_adapter::StreamableHttpRedirectMode;
|
||||
use crate::oauth::compute_expires_at_millis;
|
||||
use crate::oauth_client_registration::McpOAuthClientRegistration;
|
||||
use crate::oauth_client_registration::start_authorization as start_client_registration;
|
||||
use crate::oauth_http_client::OAuthHttpClientAdapter;
|
||||
use crate::save_oauth_tokens;
|
||||
use crate::utils::build_default_headers;
|
||||
@@ -92,6 +93,7 @@ pub async fn perform_oauth_login(
|
||||
env_http_headers: Option<HashMap<String, String>>,
|
||||
scopes: &[String],
|
||||
oauth_client_id: Option<&str>,
|
||||
client_registration: McpOAuthClientRegistration,
|
||||
oauth_resource: Option<&str>,
|
||||
callback_port: Option<u16>,
|
||||
callback_url: Option<&str>,
|
||||
@@ -106,6 +108,7 @@ pub async fn perform_oauth_login(
|
||||
env_http_headers,
|
||||
scopes,
|
||||
oauth_client_id,
|
||||
client_registration,
|
||||
oauth_resource,
|
||||
callback_port,
|
||||
callback_url,
|
||||
@@ -126,6 +129,7 @@ pub async fn perform_oauth_login_silent(
|
||||
env_http_headers: Option<HashMap<String, String>>,
|
||||
scopes: &[String],
|
||||
oauth_client_id: Option<&str>,
|
||||
client_registration: McpOAuthClientRegistration,
|
||||
oauth_resource: Option<&str>,
|
||||
callback_port: Option<u16>,
|
||||
callback_url: Option<&str>,
|
||||
@@ -141,6 +145,7 @@ pub async fn perform_oauth_login_silent(
|
||||
env_http_headers,
|
||||
scopes,
|
||||
oauth_client_id,
|
||||
client_registration,
|
||||
oauth_resource,
|
||||
callback_port,
|
||||
callback_url,
|
||||
@@ -161,6 +166,7 @@ async fn perform_oauth_login_with_browser_output(
|
||||
env_http_headers: Option<HashMap<String, String>>,
|
||||
scopes: &[String],
|
||||
oauth_client_id: Option<&str>,
|
||||
client_registration: McpOAuthClientRegistration,
|
||||
oauth_resource: Option<&str>,
|
||||
callback_port: Option<u16>,
|
||||
callback_url: Option<&str>,
|
||||
@@ -182,6 +188,7 @@ async fn perform_oauth_login_with_browser_output(
|
||||
http_context,
|
||||
scopes,
|
||||
oauth_client_id,
|
||||
client_registration,
|
||||
oauth_resource,
|
||||
/*launch_browser*/ true,
|
||||
callback_port,
|
||||
@@ -203,6 +210,7 @@ pub async fn perform_oauth_login_return_url(
|
||||
env_http_headers: Option<HashMap<String, String>>,
|
||||
scopes: &[String],
|
||||
oauth_client_id: Option<&str>,
|
||||
client_registration: McpOAuthClientRegistration,
|
||||
oauth_resource: Option<&str>,
|
||||
timeout_secs: Option<i64>,
|
||||
callback_port: Option<u16>,
|
||||
@@ -224,6 +232,7 @@ pub async fn perform_oauth_login_return_url(
|
||||
http_context,
|
||||
scopes,
|
||||
oauth_client_id,
|
||||
client_registration,
|
||||
oauth_resource,
|
||||
/*launch_browser*/ false,
|
||||
callback_port,
|
||||
@@ -492,6 +501,7 @@ impl OauthLoginFlow {
|
||||
http_context: OAuthHttpContext,
|
||||
scopes: &[String],
|
||||
oauth_client_id: Option<&str>,
|
||||
client_registration: McpOAuthClientRegistration,
|
||||
oauth_resource: Option<&str>,
|
||||
launch_browser: bool,
|
||||
callback_port: Option<u16>,
|
||||
@@ -541,14 +551,27 @@ impl OauthLoginFlow {
|
||||
));
|
||||
|
||||
let scope_refs: Vec<&str> = scopes.iter().map(String::as_str).collect();
|
||||
let oauth_state = start_authorization(
|
||||
server_url,
|
||||
oauth_http_client,
|
||||
&scope_refs,
|
||||
&redirect_uri,
|
||||
oauth_client_id,
|
||||
)
|
||||
.await?;
|
||||
let oauth_state = if let Some(oauth_client_id) =
|
||||
oauth_client_id.filter(|client_id| !client_id.trim().is_empty())
|
||||
{
|
||||
start_authorization(
|
||||
server_url,
|
||||
oauth_http_client,
|
||||
&scope_refs,
|
||||
&redirect_uri,
|
||||
oauth_client_id,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
start_client_registration(
|
||||
server_url,
|
||||
oauth_http_client,
|
||||
&scope_refs,
|
||||
&redirect_uri,
|
||||
client_registration,
|
||||
)
|
||||
.await?
|
||||
};
|
||||
let auth_url = append_query_param(
|
||||
&oauth_state.get_authorization_url().await?,
|
||||
"resource",
|
||||
@@ -670,25 +693,12 @@ async fn start_authorization(
|
||||
http_client: Arc<dyn OAuthHttpClient>,
|
||||
scopes: &[&str],
|
||||
redirect_uri: &str,
|
||||
oauth_client_id: Option<&str>,
|
||||
oauth_client_id: &str,
|
||||
) -> Result<OAuthState> {
|
||||
let mut auth_manager =
|
||||
AuthorizationManager::new_with_oauth_http_client(server_url, http_client).await?;
|
||||
auth_manager.set_allow_missing_issuer(true);
|
||||
|
||||
let Some(oauth_client_id) = oauth_client_id.filter(|client_id| !client_id.trim().is_empty())
|
||||
else {
|
||||
let mut oauth_state = OAuthState::Unauthorized(auth_manager);
|
||||
oauth_state
|
||||
.start_authorization(
|
||||
AuthorizationRequest::new(redirect_uri)
|
||||
.with_scopes(scopes.iter().copied())
|
||||
.with_client_name("Codex"),
|
||||
)
|
||||
.await?;
|
||||
return Ok(oauth_state);
|
||||
};
|
||||
|
||||
let metadata = auth_manager.resolve_metadata().await?.metadata;
|
||||
auth_manager.set_metadata(metadata);
|
||||
auth_manager.configure_client(
|
||||
@@ -721,6 +731,7 @@ fn append_query_param(url: &str, key: &str, value: Option<&str>) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
@@ -747,6 +758,7 @@ mod tests {
|
||||
use url::Url;
|
||||
|
||||
use super::CallbackOutcome;
|
||||
use super::McpOAuthClientRegistration;
|
||||
use super::OAuthHttpClientAdapter;
|
||||
use super::OAuthProviderError;
|
||||
use super::StreamableHttpRedirectMode;
|
||||
@@ -790,7 +802,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
async fn spawn_oauth_metadata_server() -> String {
|
||||
async fn spawn_oauth_metadata_server() -> (String, Arc<AtomicUsize>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind metadata listener");
|
||||
@@ -800,8 +812,11 @@ mod tests {
|
||||
"issuer": format!("{base_url}/mcp"),
|
||||
"authorization_endpoint": format!("{base_url}/oauth/authorize"),
|
||||
"token_endpoint": format!("{base_url}/oauth/token"),
|
||||
"scopes_supported": [""],
|
||||
"registration_endpoint": format!("{base_url}/oauth/register"),
|
||||
"scopes_supported": ["read", "offline_access"],
|
||||
});
|
||||
let registration_requests = Arc::new(AtomicUsize::new(0));
|
||||
let captured_registration_requests = Arc::clone(®istration_requests);
|
||||
let path_scoped_metadata = metadata.clone();
|
||||
let app = Router::new()
|
||||
.route(
|
||||
@@ -817,6 +832,16 @@ mod tests {
|
||||
let metadata = metadata.clone();
|
||||
async move { Json(metadata) }
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/oauth/register",
|
||||
post(move || {
|
||||
let registration_requests = Arc::clone(&captured_registration_requests);
|
||||
async move {
|
||||
registration_requests.fetch_add(1, Ordering::SeqCst);
|
||||
Json(json!({"client_id": "unexpected-dynamic-client"}))
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
tokio::spawn(async move {
|
||||
@@ -825,38 +850,50 @@ mod tests {
|
||||
.expect("serve oauth metadata");
|
||||
});
|
||||
|
||||
base_url
|
||||
(base_url, registration_requests)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_authorization_uses_configured_client_id() {
|
||||
let base_url = spawn_oauth_metadata_server().await;
|
||||
let oauth_state = start_authorization(
|
||||
&format!("{base_url}/mcp"),
|
||||
Arc::new(OAuthHttpClientAdapter::new(
|
||||
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
|
||||
OutboundProxyPolicy::ReqwestDefault,
|
||||
))),
|
||||
HeaderMap::new(),
|
||||
)),
|
||||
&[],
|
||||
"http://127.0.0.1/callback",
|
||||
Some("eci-prd-pub-codex-123"),
|
||||
)
|
||||
.await
|
||||
.expect("start oauth authorization");
|
||||
|
||||
let authorization_url = oauth_state
|
||||
.get_authorization_url()
|
||||
async fn configured_client_preserves_exact_scopes_and_redirect_without_registration() {
|
||||
for (scopes, expected_scope) in [(&[][..], None), (&["read"][..], Some("read"))] {
|
||||
let (base_url, registration_requests) = spawn_oauth_metadata_server().await;
|
||||
let redirect_uri = "http://127.0.0.1:43123/callback/configured-client";
|
||||
let oauth_state = start_authorization(
|
||||
&format!("{base_url}/mcp"),
|
||||
Arc::new(OAuthHttpClientAdapter::new(
|
||||
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
|
||||
OutboundProxyPolicy::ReqwestDefault,
|
||||
))),
|
||||
HeaderMap::new(),
|
||||
)),
|
||||
scopes,
|
||||
redirect_uri,
|
||||
"eci-prd-pub-codex-123",
|
||||
)
|
||||
.await
|
||||
.expect("read authorization url");
|
||||
let auth_url = Url::parse(&authorization_url).expect("authorization url should parse");
|
||||
let client_id = auth_url
|
||||
.query_pairs()
|
||||
.find(|(key, _)| key == "client_id")
|
||||
.map(|(_, value)| value.into_owned());
|
||||
.expect("start pre-registered OAuth authorization");
|
||||
|
||||
assert_eq!(client_id.as_deref(), Some("eci-prd-pub-codex-123"));
|
||||
let authorization_url = oauth_state
|
||||
.get_authorization_url()
|
||||
.await
|
||||
.expect("read authorization URL");
|
||||
let query = Url::parse(&authorization_url)
|
||||
.expect("authorization URL should parse")
|
||||
.query_pairs()
|
||||
.into_owned()
|
||||
.collect::<HashMap<String, String>>();
|
||||
|
||||
assert_eq!(
|
||||
query.get("client_id").map(String::as_str),
|
||||
Some("eci-prd-pub-codex-123")
|
||||
);
|
||||
assert_eq!(
|
||||
query.get("redirect_uri").map(String::as_str),
|
||||
Some(redirect_uri)
|
||||
);
|
||||
assert_eq!(query.get("scope").map(String::as_str), expected_scope);
|
||||
assert_eq!(registration_requests.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -925,7 +962,7 @@ mod tests {
|
||||
)),
|
||||
&[],
|
||||
"http://127.0.0.1/callback",
|
||||
Some("test-client"),
|
||||
"test-client",
|
||||
)
|
||||
.await
|
||||
.expect("start issuer-aware authorization");
|
||||
@@ -970,6 +1007,7 @@ mod tests {
|
||||
/*env_http_headers*/ None,
|
||||
&[],
|
||||
/*oauth_client_id*/ None,
|
||||
McpOAuthClientRegistration::Auto,
|
||||
/*oauth_resource*/ None,
|
||||
/*callback_port*/ None,
|
||||
/*callback_url*/ None,
|
||||
@@ -993,6 +1031,7 @@ mod tests {
|
||||
/*env_http_headers*/ None,
|
||||
&[],
|
||||
/*oauth_client_id*/ None,
|
||||
McpOAuthClientRegistration::Auto,
|
||||
/*oauth_resource*/ None,
|
||||
/*callback_port*/ None,
|
||||
/*callback_url*/ None,
|
||||
|
||||
Reference in new issue
Block a user