Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Support client secrets for pre-registered MCP OAuth clients (#47891)

willwang-openai83b56bc5ad94
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock
index dc457a186a..b96445cc78 100644
--- a/codex-rs/Cargo.lock
+++ b/codex-rs/Cargo.lock
@@ -2531,6 +2531,7 @@ dependencies = [
"codex-utils-path",
"codex-utils-path-uri",
"codex-utils-pty",
+ "codex-utils-redacted-string",
"codex-websocket-auth",
"codex-windows-sandbox",
"crossterm",
diff --git a/codex-rs/app-server/src/request_processors/mcp_processor.rs b/codex-rs/app-server/src/request_processors/mcp_processor.rs
index 7e20110f8d..5f2f773fe4 100644
--- a/codex-rs/app-server/src/request_processors/mcp_processor.rs
+++ b/codex-rs/app-server/src/request_processors/mcp_processor.rs
@@ -224,7 +224,7 @@ impl McpRequestProcessor {
http_headers,
env_http_headers,
&resolved_scopes.scopes,
- server.oauth_client_id(),
+ server.oauth.as_ref(),
client_registration,
server.oauth_resource.as_deref(),
timeout_secs,
diff --git a/codex-rs/app-server/src/request_processors/plugins.rs b/codex-rs/app-server/src/request_processors/plugins.rs
index 437dc38586..5b580f921f 100644
--- a/codex-rs/app-server/src/request_processors/plugins.rs
+++ b/codex-rs/app-server/src/request_processors/plugins.rs
@@ -1900,7 +1900,7 @@ impl PluginRequestProcessor {
let global_callback_url = config.mcp_oauth_callback_url.clone();
tokio::spawn(async move {
- let oauth_client_id = server.oauth_client_id();
+ let oauth_client_config = server.oauth.as_ref();
let first_attempt = perform_oauth_login_silent(
&oauth_credential_name,
&oauth_config.url,
@@ -1909,7 +1909,7 @@ impl PluginRequestProcessor {
oauth_config.http_headers.clone(),
oauth_config.env_http_headers.clone(),
&resolved_scopes.scopes,
- oauth_client_id,
+ oauth_client_config,
McpOAuthClientRegistration::Auto,
server.oauth_resource.as_deref(),
callback_port,
@@ -1930,7 +1930,7 @@ impl PluginRequestProcessor {
oauth_config.http_headers,
oauth_config.env_http_headers,
&[],
- oauth_client_id,
+ oauth_client_config,
McpOAuthClientRegistration::Auto,
server.oauth_resource.as_deref(),
callback_port,
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 c9f6a3f132..b9bf786e94 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
@@ -72,12 +72,13 @@ use wiremock::matchers::path;
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
-#[test_case(false, None, None, None, true; "legacy callback")]
+#[test_case(false, None, None, None, None, true; "legacy callback")]
#[test_case(
false,
Some("http://127.0.0.1/callback/registered"),
None,
None,
+ None,
true;
"ordinary configured callback falls back to default"
)]
@@ -86,6 +87,7 @@ const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
Some("http://127.0.0.1/callback/registered"),
Some("http://127.0.0.1/global/callback"),
None,
+ None,
true;
"ordinary configured callback falls back to global"
)]
@@ -94,6 +96,7 @@ const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
Some("http://127.0.0.1/callback/registered"),
Some("http://127.0.0.1/global/callback"),
Some("https://unexpected.example"),
+ None,
false;
"legacy callback fallback rejects mismatched issuer"
)]
@@ -102,6 +105,7 @@ const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
Some("http://127.0.0.1/callback"),
None,
Some("matching"),
+ None,
true;
"matching issuer"
)]
@@ -110,6 +114,7 @@ const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
Some("http://127.0.0.1/callback"),
None,
Some("https://unexpected.example"),
+ None,
false;
"mismatched issuer"
)]
@@ -118,15 +123,35 @@ const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
Some("http://127.0.0.1/callback"),
None,
None,
+ None,
false;
"missing issuer"
)]
+#[test_case(
+ false,
+ None,
+ None,
+ None,
+ Some("test-client-secret"),
+ true;
+ "client secret with legacy callback"
+)]
+#[test_case(
+ true,
+ Some("http://127.0.0.1/callback"),
+ None,
+ Some("matching"),
+ Some("test-client-secret"),
+ true;
+ "client secret with matching issuer"
+)]
#[tokio::test]
async fn oauth_login_validates_callback_issuer_and_uses_http_headers_helper(
issuer_supported: bool,
configured_callback: Option<&str>,
global_callback: Option<&str>,
callback_issuer: Option<&str>,
+ client_secret: Option<&'static str>,
expected_success: bool,
) -> Result<()> {
let oauth = MockServer::start().await;
@@ -139,12 +164,24 @@ async fn oauth_login_validates_callback_issuer_and_uses_http_headers_helper(
"authorization_endpoint": format!("{}/oauth/authorize", oauth.uri()),
"token_endpoint": format!("{}/oauth/token", oauth.uri()),
"authorization_response_iss_parameter_supported": issuer_supported,
+ "token_endpoint_auth_methods_supported": [if client_secret.is_some() {
+ "client_secret_post"
+ } else {
+ "none"
+ }],
})))
.mount(&oauth)
.await;
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(header("x-gateway", "gateway-token"))
+ .and(move |request: &wiremock::Request| {
+ let body: BTreeMap<_, _> = url::form_urlencoded::parse(&request.body)
+ .into_owned()
+ .collect();
+ body.get("client_secret").map(String::as_str) == client_secret
+ && body.get("client_id").map(String::as_str) == Some("test-client")
+ })
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": "oauth-token",
"token_type": "Bearer",
@@ -162,6 +199,9 @@ async fn oauth_login_validates_callback_issuer_and_uses_http_headers_helper(
let saved_callback = configured_callback
.map(|callback| format!("callback_url = \"{callback}\"\n"))
.unwrap_or_default();
+ let saved_client_secret = client_secret
+ .map(|secret| format!("client_secret = \"{secret}\"\n"))
+ .unwrap_or_default();
let global_callback_config = global_callback
.map(|callback| format!("mcp_oauth_callback_url = \"{callback}\"\n"))
.unwrap_or_default();
@@ -175,6 +215,7 @@ async fn oauth_login_validates_callback_issuer_and_uses_http_headers_helper(
http_headers_helper = {}\n\
[mcp_servers.gateway.oauth]\n\
client_id = \"test-client\"\n\
+ {saved_client_secret}\
{saved_callback}",
oauth.uri(),
toml::Value::String(helper_command.to_string()),
@@ -195,6 +236,7 @@ async fn oauth_login_validates_callback_issuer_and_uses_http_headers_helper(
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??;
let authorization_url = Url::parse(&response.authorization_url)?;
let query: BTreeMap<_, _> = authorization_url.query_pairs().into_owned().collect();
+ assert!(!query.contains_key("client_secret"));
let mut callback_url = Url::parse(&query["redirect_uri"])?;
let expected_callback = if issuer_supported {
configured_callback
@@ -242,6 +284,11 @@ async fn oauth_login_validates_callback_issuer_and_uses_http_headers_helper(
),
("gateway", None, expected_success, !expected_success)
);
+ if let Some(client_secret) = client_secret {
+ assert!(!response.authorization_url.contains(client_secret));
+ let credentials = std::fs::read_to_string(codex_home.path().join(".credentials.json"))?;
+ assert!(!credentials.contains(client_secret));
+ }
oauth.verify().await;
Ok(())
}
diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml
index 3a6ef4a716..4fed7668d3 100644
--- a/codex-rs/cli/Cargo.toml
+++ b/codex-rs/cli/Cargo.toml
@@ -75,6 +75,7 @@ codex-tui = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-path = { workspace = true }
codex-utils-path-uri = { workspace = true }
+codex-utils-redacted-string = { workspace = true }
codex-websocket-auth = { workspace = true }
crossterm = { workspace = true, features = ["event-stream"] }
futures = { workspace = true }
diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs
index 7c01fb96cb..cfc2f492b3 100644
--- a/codex-rs/cli/src/mcp_cmd.rs
+++ b/codex-rs/cli/src/mcp_cmd.rs
@@ -6,6 +6,7 @@ use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use clap::ArgGroup;
+use clap::builder::TypedValueParser;
use codex_config::types::AppToolApproval;
use codex_config::types::McpServerConfig;
use codex_config::types::McpServerOAuthConfig;
@@ -39,12 +40,17 @@ use codex_rmcp_client::delete_oauth_tokens;
use codex_rmcp_client::resolve_mcp_oauth_callback_url;
use codex_utils_cli::CliConfigOverrides;
use codex_utils_cli::format_env_display;
+use codex_utils_redacted_string::RedactedString;
use crate::cloud_config;
use crate::mcp_login::McpLoginMode;
use crate::mcp_login::perform_oauth_login_retry_without_scopes;
use crate::plugin_cmd::load_cli_auth_manager;
+#[cfg(test)]
+#[path = "mcp_cmd_tests.rs"]
+mod tests;
+
/// Subcommands:
/// - `list` — list configured servers (with `--json`)
/// - `get` — show a single server (with `--json`)
@@ -154,6 +160,15 @@ pub struct AddMcpStreamableHttpArgs {
#[arg(long = "oauth-client-id", value_name = "CLIENT_ID", requires = "url")]
pub oauth_client_id: Option<String>,
+ /// Optional OAuth client secret for the pre-registered client.
+ #[arg(
+ long = "oauth-client-secret",
+ value_name = "CLIENT_SECRET",
+ value_parser = clap::builder::StringValueParser::new().map(RedactedString::from),
+ requires_all = ["url", "oauth_client_id"]
+ )]
+ pub oauth_client_secret: Option<RedactedString>,
+
/// OAuth client-registration strategy for the immediate login only.
#[arg(
long = "oauth-client-registration",
@@ -293,60 +308,78 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re
let codex_home = find_codex_home().context("failed to resolve CODEX_HOME")?;
- let (transport, oauth_client_id, client_registration, oauth_resource) = match transport_args {
- AddMcpTransportArgs {
- stdio: Some(stdio), ..
- } => {
- let mut command_parts = stdio.command.into_iter();
- let command_bin = command_parts
- .next()
- .ok_or_else(|| anyhow!("command is required"))?;
- let command_args: Vec<String> = command_parts.collect();
-
- let env_map = if stdio.env.is_empty() {
- None
- } else {
- Some(stdio.env.into_iter().collect::<HashMap<_, _>>())
- };
- (
- McpServerTransportConfig::Stdio {
- command: command_bin,
- args: command_args,
- env: env_map,
- env_vars: Vec::new(),
- cwd: None,
- },
- None,
- McpOAuthClientRegistration::Auto,
- None,
- )
- }
- AddMcpTransportArgs {
- streamable_http:
- Some(AddMcpStreamableHttpArgs {
+ let (transport, oauth_client_id, oauth_client_secret, client_registration, oauth_resource) =
+ match transport_args {
+ AddMcpTransportArgs {
+ stdio: Some(stdio), ..
+ } => {
+ let mut command_parts = stdio.command.into_iter();
+ let command_bin = command_parts
+ .next()
+ .ok_or_else(|| anyhow!("command is required"))?;
+ let command_args: Vec<String> = command_parts.collect();
+
+ let env_map = if stdio.env.is_empty() {
+ None
+ } else {
+ Some(stdio.env.into_iter().collect::<HashMap<_, _>>())
+ };
+ (
+ McpServerTransportConfig::Stdio {
+ command: command_bin,
+ args: command_args,
+ env: env_map,
+ env_vars: Vec::new(),
+ cwd: None,
+ },
+ None,
+ None,
+ McpOAuthClientRegistration::Auto,
+ None,
+ )
+ }
+ AddMcpTransportArgs {
+ streamable_http:
+ Some(AddMcpStreamableHttpArgs {
+ url,
+ bearer_token_env_var,
+ oauth_client_id,
+ oauth_client_secret,
+ oauth_client_registration,
+ oauth_resource,
+ }),
+ ..
+ } => (
+ McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
- oauth_client_id,
- oauth_client_registration,
- oauth_resource,
- }),
- ..
- } => (
- McpServerTransportConfig::StreamableHttp {
- url,
- bearer_token_env_var,
- http_headers: None,
- env_http_headers: None,
- http_headers_helper: None,
- },
- oauth_client_id,
- oauth_client_registration
- .map(McpOAuthClientRegistration::from)
- .unwrap_or_default(),
- oauth_resource,
- ),
- AddMcpTransportArgs { .. } => bail!("exactly one of --command or --url must be provided"),
- };
+ http_headers: None,
+ env_http_headers: None,
+ http_headers_helper: None,
+ },
+ oauth_client_id,
+ oauth_client_secret,
+ oauth_client_registration
+ .map(McpOAuthClientRegistration::from)
+ .unwrap_or_default(),
+ oauth_resource,
+ ),
+ AddMcpTransportArgs { .. } => {
+ bail!("exactly one of --command or --url must be provided")
+ }
+ };
+
+ if let Some(secret) = &oauth_client_secret {
+ if secret.trim().is_empty() {
+ bail!("--oauth-client-secret must not be empty");
+ }
+ if oauth_client_id
+ .as_deref()
+ .is_none_or(|client_id| client_id.trim().is_empty())
+ {
+ bail!("--oauth-client-secret requires a nonempty --oauth-client-id");
+ }
+ }
// Discover once before saving so a new registered client keeps the exact
// callback its provider expects, including issuer-bound stable callbacks.
@@ -404,6 +437,7 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re
.clone()
.map(|client_id| McpServerOAuthConfig {
client_id: Some(client_id),
+ client_secret: oauth_client_secret,
callback_url: callback_url.clone(),
callback_port: None,
..Default::default()
@@ -444,7 +478,7 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re
oauth_config.http_headers,
oauth_config.env_http_headers,
&resolved_scopes,
- oauth_client_id.as_deref(),
+ servers[&name].oauth.as_ref(),
client_registration,
oauth_resource.as_deref(),
config.mcp_oauth_callback_port,
@@ -575,7 +609,7 @@ async fn run_login(config: &Config, login_args: LoginArgs) -> Result<()> {
http_headers,
env_http_headers,
&resolved_scopes,
- server.oauth_client_id(),
+ server.oauth.as_ref(),
client_registration,
server.oauth_resource.as_deref(),
server.oauth_callback_port(config.mcp_oauth_callback_port),
diff --git a/codex-rs/cli/src/mcp_cmd_tests.rs b/codex-rs/cli/src/mcp_cmd_tests.rs
new file mode 100644
index 0000000000..98ebe6a709
--- /dev/null
+++ b/codex-rs/cli/src/mcp_cmd_tests.rs
@@ -0,0 +1,62 @@
+//! Verifies MCP client-secret argument requirements and redacted CLI diagnostics.
+
+use clap::Parser;
+use pretty_assertions::assert_eq;
+
+use super::McpCli;
+use super::McpSubcommand;
+
+#[test]
+fn oauth_client_secret_is_redacted_in_parsed_command_debug() {
+ let cli = McpCli::try_parse_from([
+ "mcp",
+ "add",
+ "private",
+ "--url",
+ "https://example.com/mcp",
+ "--oauth-client-id",
+ "registered-client",
+ "--oauth-client-secret",
+ "cli-secret-marker",
+ ])
+ .expect("parse confidential client arguments");
+ let debug = format!("{cli:?}");
+ assert!(!debug.contains("cli-secret-marker"));
+ assert!(debug.contains("oauth_client_secret: Some(<redacted>)"));
+ let McpSubcommand::Add(add) = cli.subcommand else {
+ panic!("expected MCP add");
+ };
+ let http = add.transport_args.streamable_http.expect("HTTP arguments");
+ assert_eq!(
+ http.oauth_client_secret
+ .as_ref()
+ .map(|secret| secret.as_str()),
+ Some("cli-secret-marker")
+ );
+}
+
+#[test]
+fn oauth_client_secret_requires_url_and_client_id_without_disclosure() {
+ for args in [
+ vec!["--url", "https://example.com/mcp"],
+ vec!["--oauth-client-id", "registered-client"],
+ ] {
+ let error = McpCli::try_parse_from(
+ [
+ "mcp",
+ "add",
+ "private",
+ "--oauth-client-secret",
+ "cli-secret-marker",
+ ]
+ .into_iter()
+ .chain(args),
+ )
+ .expect_err("client secret requires both HTTP URL and client ID");
+ assert_eq!(
+ error.kind(),
+ clap::error::ErrorKind::MissingRequiredArgument
+ );
+ assert!(!error.to_string().contains("cli-secret-marker"));
+ }
+}
diff --git a/codex-rs/cli/src/mcp_login.rs b/codex-rs/cli/src/mcp_login.rs
index 912fa630b4..07fcc96c2f 100644
--- a/codex-rs/cli/src/mcp_login.rs
+++ b/codex-rs/cli/src/mcp_login.rs
@@ -14,6 +14,7 @@ use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
+use codex_config::McpServerOAuthConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::HttpClient;
@@ -49,7 +50,7 @@ pub(crate) async fn perform_oauth_login_retry_without_scopes(
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
resolved_scopes: &ResolvedMcpOAuthScopes,
- oauth_client_id: Option<&str>,
+ oauth_config: Option<&McpServerOAuthConfig>,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
callback_port: Option<u16>,
@@ -78,7 +79,7 @@ pub(crate) async fn perform_oauth_login_retry_without_scopes(
http_headers.clone(),
env_http_headers.clone(),
scopes,
- oauth_client_id,
+ oauth_config,
client_registration,
oauth_resource,
callback_port,
@@ -98,7 +99,7 @@ pub(crate) async fn perform_oauth_login_retry_without_scopes(
http_headers.clone(),
env_http_headers.clone(),
scopes,
- oauth_client_id,
+ oauth_config,
client_registration,
oauth_resource,
callback_port,
diff --git a/codex-rs/cli/tests/mcp_add_remove.rs b/codex-rs/cli/tests/mcp_add_remove.rs
index ca68faa061..80d0c11af8 100644
--- a/codex-rs/cli/tests/mcp_add_remove.rs
+++ b/codex-rs/cli/tests/mcp_add_remove.rs
@@ -347,6 +347,40 @@ async fn add_streamable_http_without_manual_token() -> Result<()> {
Ok(())
}
+#[tokio::test]
+async fn add_rejects_blank_client_credentials_before_saving() -> Result<()> {
+ let mut errors = Vec::new();
+ for (client_id, client_secret) in [("registered-client", " "), (" ", "cli-secret-marker")] {
+ let codex_home = TempDir::new()?;
+ let output = codex_command(codex_home.path())?
+ .args([
+ "mcp",
+ "add",
+ "private",
+ "--url",
+ "http://127.0.0.1:9/mcp",
+ "--oauth-client-id",
+ client_id,
+ "--oauth-client-secret",
+ client_secret,
+ ])
+ .assert()
+ .failure()
+ .get_output()
+ .clone();
+ let stderr = String::from_utf8(output.stderr)?;
+ assert!(!stderr.contains("cli-secret-marker"));
+ assert!(!String::from_utf8(output.stdout)?.contains("cli-secret-marker"));
+ assert!(load_global_mcp_servers(codex_home.path()).await?.is_empty());
+ errors.push(stderr.trim().to_string());
+ }
+ insta::assert_snapshot!(errors.join("\n"), @r"
+ Error: --oauth-client-secret must not be empty
+ Error: --oauth-client-secret requires a nonempty --oauth-client-id
+ ");
+ Ok(())
+}
+
#[tokio::test]
async fn add_streamable_http_with_custom_env_var() -> Result<()> {
let codex_home = TempDir::new()?;
diff --git a/codex-rs/cli/tests/mcp_login.rs b/codex-rs/cli/tests/mcp_login.rs
index 784b761b3f..4684e134ed 100644
--- a/codex-rs/cli/tests/mcp_login.rs
+++ b/codex-rs/cli/tests/mcp_login.rs
@@ -8,6 +8,7 @@ use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
+use codex_core::config::load_global_mcp_servers;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
@@ -37,46 +38,66 @@ struct Fixture {
}
impl Fixture {
- async fn new() -> Result<Self> {
+ async fn new(client_secret: Option<&'static str>) -> Result<Self> {
let server = MockServer::start().await;
let home = TempDir::new()?;
let issuer = format!("{}/mcp", server.uri());
+ let saved_client_secret = client_secret
+ .map(|secret| format!("client_secret = \"{secret}\"\n"))
+ .unwrap_or_default();
std::fs::write(
home.path().join("config.toml"),
format!(
"mcp_oauth_credentials_store = \"file\"\n\
[mcp_servers.manual]\nurl = \"{issuer}\"\nscopes = [\"mcp.read\"]\n\
- [mcp_servers.manual.oauth]\nclient_id = \"registered-client\"\n"
+ [mcp_servers.manual.oauth]\nclient_id = \"registered-client\"\n\
+ {saved_client_secret}"
),
)?;
+ let fixture = Self {
+ server,
+ home,
+ issuer,
+ };
+ fixture.mount_oauth(client_secret).await;
+ Ok(fixture)
+ }
+
+ async fn mount_oauth(&self, client_secret: Option<&'static str>) {
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "issuer": issuer,
- "authorization_endpoint": format!("{}/authorize", server.uri()),
- "token_endpoint": format!("{}/token", server.uri()),
+ "issuer": self.issuer,
+ "authorization_endpoint": format!("{}/authorize", self.server.uri()),
+ "token_endpoint": format!("{}/token", self.server.uri()),
"response_types_supported": ["code"],
"code_challenge_methods_supported": ["S256"],
"scopes_supported": ["mcp.read"],
"authorization_response_iss_parameter_supported": true,
+ "token_endpoint_auth_methods_supported": [if client_secret.is_some() {
+ "client_secret_post"
+ } else {
+ "none"
+ }],
})))
- .mount(&server)
+ .mount(&self.server)
.await;
Mock::given(method("POST"))
.and(path("/token"))
+ .and(move |request: &wiremock::Request| {
+ let body: BTreeMap<_, _> = url::form_urlencoded::parse(&request.body)
+ .into_owned()
+ .collect();
+ body.get("client_secret").map(String::as_str) == client_secret
+ })
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": "mock-access-token",
"token_type": "Bearer",
"refresh_token": "mock-refresh-token",
"scope": "mcp.read",
})))
- .mount(&server)
+ .mount(&self.server)
.await;
- Ok(Self {
- server,
- home,
- issuer,
- })
}
async fn start(&self) -> Result<Login> {
@@ -93,7 +114,20 @@ impl Fixture {
.spawn()?;
let mut stdout = BufReader::new(child.stdout.take().context("missing stdout")?);
let mut transcript = String::new();
- let authorization_url = read_authorization_url(&mut stdout, &mut transcript).await?;
+ let authorization_url = match read_authorization_url(&mut stdout, &mut transcript).await {
+ Ok(authorization_url) => authorization_url,
+ Err(error) => {
+ let mut stderr = String::new();
+ if let Some(stderr_pipe) = child.stderr.take() {
+ let _ = timeout(
+ Duration::from_secs(1),
+ stderr_pipe.take(/*limit*/ 4096).read_to_string(&mut stderr),
+ )
+ .await;
+ }
+ return Err(error.context(format!("MCP login stderr: {stderr}")));
+ }
+ };
Ok(Login {
child,
stdout,
@@ -158,7 +192,85 @@ impl Login {
#[tokio::test]
async fn no_browser_exchanges_pasted_callback_and_saves_credentials() -> Result<()> {
- let fixture = Fixture::new().await?;
+ let fixture = Fixture::new(/*client_secret*/ None).await?;
+ assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
+ fixture, /*client_secret*/ None,
+ )
+ .await
+}
+
+#[tokio::test]
+async fn no_browser_exchanges_pasted_callback_with_client_secret() -> Result<()> {
+ let fixture = Fixture::new(Some("headless-client-secret")).await?;
+ assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
+ fixture,
+ Some("headless-client-secret"),
+ )
+ .await
+}
+
+#[tokio::test]
+async fn add_persists_client_secret_for_subsequent_login_without_disclosure() -> Result<()> {
+ const CLIENT_SECRET: &str = "cli-client-secret";
+ let fixture = Fixture::new(Some(CLIENT_SECRET)).await?;
+ std::fs::write(
+ fixture.home.path().join("config.toml"),
+ "mcp_oauth_credentials_store = \"file\"\n",
+ )?;
+ // Stop automatic login before browser launch, then retry with valid metadata.
+ Mock::given(method("GET"))
+ .and(path("/.well-known/oauth-authorization-server/mcp"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "issuer": fixture.issuer,
+ "authorization_endpoint": "not-a-valid-authorization-url",
+ "token_endpoint": format!("{}/token", fixture.server.uri()),
+ "authorization_response_iss_parameter_supported": true,
+ })))
+ .with_priority(/*priority*/ 1)
+ .mount(&fixture.server)
+ .await;
+ let output = timeout(
+ TEST_TIMEOUT,
+ Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
+ .kill_on_drop(true)
+ .current_dir(fixture.home.path())
+ .env("CODEX_HOME", fixture.home.path())
+ .env("NO_PROXY", "127.0.0.1,localhost")
+ .env("no_proxy", "127.0.0.1,localhost")
+ .args([
+ "mcp",
+ "add",
+ "manual",
+ "--url",
+ &fixture.issuer,
+ "--oauth-client-id",
+ "registered-client",
+ "--oauth-client-secret",
+ CLIENT_SECRET,
+ ])
+ .output(),
+ )
+ .await??;
+ assert!(!output.status.success());
+ let stdout = String::from_utf8(output.stdout)?;
+ let stderr = String::from_utf8(output.stderr)?;
+ assert!(stdout.contains("Detected OAuth support. Starting OAuth flow"));
+ assert!(!stdout.contains(CLIENT_SECRET));
+ assert!(!stderr.contains(CLIENT_SECRET));
+ let servers = load_global_mcp_servers(fixture.home.path()).await?;
+ assert_eq!(servers["manual"].oauth_client_secret(), Some(CLIENT_SECRET));
+ // Reset removes the priority override without relying on wiremock's scoped indices.
+ fixture.server.reset().await;
+ fixture.mount_oauth(Some(CLIENT_SECRET)).await;
+
+ assert_no_browser_exchanges_pasted_callback_and_saves_credentials(fixture, Some(CLIENT_SECRET))
+ .await
+}
+
+async fn assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
+ fixture: Fixture,
+ client_secret: Option<&'static str>,
+) -> Result<()> {
let mut login = fixture.start().await?;
let authorization_url = login.authorization_url.to_string();
let params: BTreeMap<_, _> = login.authorization_url.query_pairs().into_owned().collect();
@@ -176,15 +288,23 @@ async fn no_browser_exchanges_pasted_callback_and_saves_credentials() -> Result<
"{}",
String::from_utf8_lossy(&output.stderr)
);
- insta::assert_snapshot!(String::from_utf8(output.stdout)?.replace(&authorization_url, "[AUTHORIZATION_URL]"), @r"
- Authorize the MCP server by opening this URL in your browser:
- [AUTHORIZATION_URL]
+ let stdout = String::from_utf8(output.stdout)?;
+ let stderr = String::from_utf8(output.stderr)?;
+ if let Some(client_secret) = client_secret {
+ assert!(!stdout.contains(client_secret));
+ assert!(!stderr.contains(client_secret));
+ }
+ insta::allow_duplicates! {
+ insta::assert_snapshot!(stdout.replace(&authorization_url, "[AUTHORIZATION_URL]"), @r"
+ Authorize the MCP server by opening this URL in your browser:
+ [AUTHORIZATION_URL]
- After signing in, copy the full URL from your browser's address bar.
- If the callback page cannot load, paste that URL here anyway.
- Successfully logged in to MCP server 'manual'.
- ");
- assert!(String::from_utf8(output.stderr)?.contains("Callback URL (input hidden): "));
+ After signing in, copy the full URL from your browser's address bar.
+ If the callback page cannot load, paste that URL here anyway.
+ Successfully logged in to MCP server 'manual'.
+ ");
+ }
+ assert!(stderr.contains("Callback URL (input hidden): "));
let requests = fixture
.server
.received_requests()
@@ -204,16 +324,17 @@ async fn no_browser_exchanges_pasted_callback_and_saves_credentials() -> Result<
assert!((43..=128).contains(&verifier.len()));
assert_eq!(params["code_challenge_method"], "S256");
assert!(!params["code_challenge"].is_empty());
- assert_eq!(
- exchange,
- BTreeMap::from([
- ("client_id".to_string(), "registered-client".to_string()),
- ("code".to_string(), "mock-code".to_string()),
- ("grant_type".to_string(), "authorization_code".to_string()),
- ("redirect_uri".to_string(), params["redirect_uri"].clone()),
- ("resource".to_string(), fixture.issuer.clone()),
- ])
- );
+ let mut expected_exchange = BTreeMap::from([
+ ("client_id".to_string(), "registered-client".to_string()),
+ ("code".to_string(), "mock-code".to_string()),
+ ("grant_type".to_string(), "authorization_code".to_string()),
+ ("redirect_uri".to_string(), params["redirect_uri"].clone()),
+ ("resource".to_string(), fixture.issuer.clone()),
+ ]);
+ if let Some(client_secret) = client_secret {
+ expected_exchange.insert("client_secret".to_string(), client_secret.to_string());
+ }
+ assert_eq!(exchange, expected_exchange);
let credentials: BTreeMap<String, Value> = serde_json::from_slice(&std::fs::read(
fixture.home.path().join(".credentials.json"),
)?)?;
@@ -236,7 +357,7 @@ async fn no_browser_rejects_invalid_callbacks_without_exchanging_tokens() -> Res
("iss", Some("https://secret-issuer-marker.example")),
("eof", None),
] {
- let fixture = Fixture::new().await?;
+ let fixture = Fixture::new(/*client_secret*/ None).await?;
let mut login = fixture.start().await?;
let mut callback = login.callback(&fixture.issuer)?;
let mut pairs: BTreeMap<_, _> = callback.query_pairs().into_owned().collect();
@@ -285,7 +406,7 @@ async fn no_browser_rejects_invalid_callbacks_without_exchanging_tokens() -> Res
#[tokio::test]
async fn no_browser_accepts_http_callback_while_terminal_input_remains_open() -> Result<()> {
- let fixture = Fixture::new().await?;
+ let fixture = Fixture::new(/*client_secret*/ None).await?;
let mut login = fixture.start().await?;
let callback = login.callback(&fixture.issuer)?;
let stdin = login.child.stdin.take().context("missing stdin")?;
@@ -317,7 +438,7 @@ async fn no_browser_accepts_http_callback_while_terminal_input_remains_open() ->
#[tokio::test]
async fn no_browser_retries_rejected_discovered_scopes_with_pasteback() -> Result<()> {
- let fixture = Fixture::new().await?;
+ let fixture = Fixture::new(/*client_secret*/ None).await?;
let config_path = fixture.home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(config_path, config.replace("scopes = [\"mcp.read\"]\n", ""))?;
@@ -383,7 +504,7 @@ async fn no_browser_retries_rejected_discovered_scopes_with_pasteback() -> Resul
#[tokio::test]
async fn no_browser_sigint_cancels_token_exchange_after_pasted_or_http_callback() -> Result<()> {
for callback_delivery in ["paste", "http"] {
- let fixture = Fixture::new().await?;
+ let fixture = Fixture::new(/*client_secret*/ None).await?;
let request_started = std::sync::Arc::new(tokio::sync::Notify::new());
let notify = std::sync::Arc::clone(&request_started);
Mock::given(method("POST"))
diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs
index 3d8875caf3..2fb322548f 100644
--- a/codex-rs/codex-mcp/src/connection_manager_tests.rs
+++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs
@@ -5736,6 +5736,79 @@ async fn reconciliation_retries_non_oauth_authentication_failures() {
assert!(!previous.shares_test_connection_with(&reconciled, "docs"));
}
+#[test]
+fn connection_identity_tracks_only_oauth_credentials_when_oauth_is_active() {
+ let runtime_context = reusable_server_runtime_context();
+ for authorization in [None, Some("Bearer configured-token")] {
+ let identity = |oauth: serde_json::Value| {
+ let config: McpServerConfig = serde_json::from_value(serde_json::json!({
+ "url": "http://127.0.0.1:1",
+ "http_headers": authorization.map(|value| HashMap::from([
+ ("Authorization", value)
+ ])),
+ "oauth": oauth
+ }))
+ .expect("valid OAuth configuration");
+ let debug = format!("{config:?}");
+ assert!(!debug.contains("old-secret"));
+ assert!(!debug.contains("new-secret"));
+ McpServerConnectionIdentity::new(
+ "docs",
+ &EffectiveMcpServer::configured(config),
+ /*host_plugin_root*/ None,
+ OAuthCredentialsStoreMode::File,
+ AuthKeyringBackendKind::Direct,
+ McpOAuthRefreshMode::Legacy,
+ &Ok(None),
+ &runtime_context,
+ /*runtime_auth_provider*/ None,
+ /*auth*/ None,
+ /*codex_apps_cache_identity*/ None,
+ ElicitationCapability::default(),
+ ClientMcpExtensions::default(),
+ /*previous_identity*/ None,
+ )
+ };
+ let original_config = serde_json::json!({
+ "client_id": "client",
+ "client_secret": "old-secret",
+ "callback_url": "http://127.0.0.1:12799/callback/original",
+ "callback_port": 12799,
+ });
+ let original = identity(original_config.clone());
+ assert!(original.has_same_connection_config(&identity(original_config.clone())));
+ for (field, value) in [
+ ("client_secret", serde_json::json!("new-secret")),
+ ("client_id", serde_json::json!("new-client")),
+ ] {
+ let mut changed = original_config.clone();
+ changed[field] = value;
+ assert_eq!(
+ original.has_same_connection_config(&identity(changed)),
+ authorization.is_some(),
+ );
+ }
+ for (field, value) in [
+ (
+ "callback_url",
+ serde_json::json!("http://127.0.0.1:12799/callback/changed"),
+ ),
+ ("callback_port", serde_json::json!(12800)),
+ ] {
+ let mut changed = original_config.clone();
+ changed[field] = value.clone();
+ assert!(original.has_same_connection_config(&identity(changed)));
+
+ let mut callback_only = serde_json::json!({});
+ callback_only[field] = value;
+ assert!(
+ identity(serde_json::Value::Null)
+ .has_same_connection_config(&identity(callback_only))
+ );
+ }
+ }
+}
+
#[test]
fn connection_identity_uses_effective_authorization_headers() {
let runtime_context = reusable_server_runtime_context();
diff --git a/codex-rs/codex-mcp/src/plugin_config.rs b/codex-rs/codex-mcp/src/plugin_config.rs
index f55ebf977d..9a14022a8d 100644
--- a/codex-rs/codex-mcp/src/plugin_config.rs
+++ b/codex-rs/codex-mcp/src/plugin_config.rs
@@ -280,6 +280,12 @@ fn normalize_plugin_mcp_server_value(
oauth.entry("client_id".to_string()).or_insert(client_id);
}
+ if let Some(client_secret) = oauth.remove("clientSecret") {
+ oauth
+ .entry("client_secret".to_string())
+ .or_insert(client_secret);
+ }
+
if !oauth.is_empty() {
object.insert("oauth".to_string(), JsonValue::Object(oauth));
}
diff --git a/codex-rs/codex-mcp/src/plugin_config_tests.rs b/codex-rs/codex-mcp/src/plugin_config_tests.rs
index b6836e55c6..7d4c166f85 100644
--- a/codex-rs/codex-mcp/src/plugin_config_tests.rs
+++ b/codex-rs/codex-mcp/src/plugin_config_tests.rs
@@ -582,6 +582,7 @@ fn declared_placement_preserves_local_plugin_normalization() {
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: Some("client-id".to_string()),
+ client_secret: Some("plugin-client-secret".into()),
callback_url: Some("http://127.0.0.1/callback/registered".to_string()),
callback_port: Some(9876),
..Default::default()
@@ -613,7 +614,7 @@ fn declared_placement_preserves_local_plugin_normalization() {
"hosted": {
"type": "http",
"url": "https://example.com/mcp",
- "oauth": {"clientId": "client-id", "callbackUrl": "http://127.0.0.1/callback/registered", "callbackPort": 9876}
+ "oauth": {"clientId": "client-id", "clientSecret": "plugin-client-secret", "callbackUrl": "http://127.0.0.1/callback/registered", "callbackPort": 9876}
},
"helper": {"type":"http","url":"https://example.com/mcp","http_headers_helper":"./auth.sh"}
}"#,
diff --git a/codex-rs/codex-mcp/src/rmcp_client.rs b/codex-rs/codex-mcp/src/rmcp_client.rs
index d185c6f578..2844a61979 100644
--- a/codex-rs/codex-mcp/src/rmcp_client.rs
+++ b/codex-rs/codex-mcp/src/rmcp_client.rs
@@ -1287,6 +1287,7 @@ pub(crate) async fn make_rmcp_client(
resolved_bearer_token,
http_headers,
env_http_headers,
+ server.config().oauth.clone(),
store_mode,
keyring_backend_kind,
http_client,
diff --git a/codex-rs/codex-mcp/src/server.rs b/codex-rs/codex-mcp/src/server.rs
index a7ad0583c5..d052418957 100644
--- a/codex-rs/codex-mcp/src/server.rs
+++ b/codex-rs/codex-mcp/src/server.rs
@@ -8,6 +8,7 @@ use codex_api::SharedAuthProvider;
use codex_config::AppToolApproval;
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
+use codex_config::McpServerOAuthConfig;
use codex_config::McpServerTransportConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
@@ -112,6 +113,7 @@ pub(crate) struct McpServerConnectionIdentity {
host_plugin_root: Option<PathUri>,
oauth_store: Option<(OAuthCredentialsStoreMode, AuthKeyringBackendKind)>,
oauth_refresh_mode: Option<McpOAuthRefreshMode>,
+ oauth_config: Option<McpServerOAuthConfig>,
oauth_credentials: Result<Option<StoredOAuthCredentialSnapshot>, String>,
pub(crate) oauth_store_was_contended: bool,
resolved_environment: Result<Option<Arc<Environment>>, String>,
@@ -234,6 +236,7 @@ impl McpServerConnectionIdentity {
.is_some()
.then_some((store_mode, keyring_backend_kind)),
oauth_refresh_mode: stored_oauth_url.is_some().then_some(oauth_refresh_mode),
+ oauth_config: stored_oauth_url.and(config.oauth.clone()),
oauth_credentials,
oauth_store_was_contended,
resolved_environment: resolved_environment.clone(),
@@ -269,6 +272,11 @@ impl McpServerConnectionIdentity {
&& self.host_plugin_root == other.host_plugin_root
&& self.oauth_store == other.oauth_store
&& self.oauth_refresh_mode == other.oauth_refresh_mode
+ // Callback settings only affect a future login, not the live connection.
+ && self.oauth_config.as_ref().and_then(|oauth| oauth.client_id.as_ref())
+ == other.oauth_config.as_ref().and_then(|oauth| oauth.client_id.as_ref())
+ && self.oauth_config.as_ref().and_then(|oauth| oauth.client_secret.as_ref())
+ == other.oauth_config.as_ref().and_then(|oauth| oauth.client_secret.as_ref())
&& same_resolved_environment(&self.resolved_environment, &other.resolved_environment)
&& self.local_stdio_fallback_cwd == other.local_stdio_fallback_cwd
&& self.referenced_environment_variables == other.referenced_environment_variables
diff --git a/codex-rs/config/src/mcp_ema.rs b/codex-rs/config/src/mcp_ema.rs
index 8360f22ebc..bee6d43f5d 100644
--- a/codex-rs/config/src/mcp_ema.rs
+++ b/codex-rs/config/src/mcp_ema.rs
@@ -175,6 +175,9 @@ impl McpServerConfig {
if !self.is_local_environment() {
return Err("ema_auth requires a host-owned MCP connection");
}
+ if self.oauth_client_secret().is_some() {
+ return Err("ema_auth cannot be combined with oauth.client_secret");
+ }
let McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
http_headers,
diff --git a/codex-rs/config/src/mcp_ema_tests.rs b/codex-rs/config/src/mcp_ema_tests.rs
index 5211497725..585f62ba37 100644
--- a/codex-rs/config/src/mcp_ema_tests.rs
+++ b/codex-rs/config/src/mcp_ema_tests.rs
@@ -295,6 +295,7 @@ fn ema_rejects_alternate_credentials_and_executor_custody() {
"http_headers.Accept='application/json'",
"env_http_headers.X-Key='TOKEN'",
"http_headers_helper='get-headers'",
+ "oauth={client_id='client', client_secret='secret'}",
"environment_id='remote'",
] {
let server: McpServerConfig = toml::from_str(&format!(
diff --git a/codex-rs/config/src/mcp_types.rs b/codex-rs/config/src/mcp_types.rs
index 6cc30861de..a1135c6af1 100644
--- a/codex-rs/config/src/mcp_types.rs
+++ b/codex-rs/config/src/mcp_types.rs
@@ -10,6 +10,7 @@ use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_protocol::config_types::ToolExposureSurface;
use codex_utils_path_uri::LegacyAppPathString;
+use codex_utils_redacted_string::RedactedString;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Deserializer;
@@ -164,6 +165,10 @@ pub struct McpServerOAuthConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
+ /// OAuth client secret used for token exchange with a pre-registered client.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub client_secret: Option<RedactedString>,
+
/// Registered callback URL associated with this OAuth client.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub callback_url: Option<String>,
@@ -317,6 +322,13 @@ impl McpServerConfig {
.and_then(|oauth| oauth.client_id.as_deref())
}
+ pub fn oauth_client_secret(&self) -> Option<&str> {
+ self.oauth
+ .as_ref()
+ .and_then(|oauth| oauth.client_secret.as_ref())
+ .map(|secret| secret.as_str())
+ }
+
pub fn oauth_callback_port(&self, global_callback_port: Option<u16>) -> Option<u16> {
let callback_port = self.oauth.as_ref().and_then(|oauth| oauth.callback_port);
if let Some(callback_port) = callback_port {
@@ -512,6 +524,20 @@ impl TryFrom<RawMcpServerConfig> for McpServerConfig {
let environment_id =
environment_id.unwrap_or_else(|| DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string());
let auth = auth.unwrap_or_default();
+ if let Some(oauth) = &oauth
+ && let Some(client_secret) = &oauth.client_secret
+ {
+ if client_secret.trim().is_empty() {
+ return Err("oauth.client_secret must not be empty".to_string());
+ }
+ if oauth
+ .client_id
+ .as_deref()
+ .is_none_or(|client_id| client_id.trim().is_empty())
+ {
+ return Err("oauth.client_secret requires oauth.client_id".to_string());
+ }
+ }
if !matches!(auth, McpServerAuth::EmaAuth)
&& oauth
.as_ref()
diff --git a/codex-rs/config/src/mcp_types_tests.rs b/codex-rs/config/src/mcp_types_tests.rs
index 2ccb848b19..613e4fdcdb 100644
--- a/codex-rs/config/src/mcp_types_tests.rs
+++ b/codex-rs/config/src/mcp_types_tests.rs
@@ -381,6 +381,84 @@ fn deserialize_streamable_http_server_config_with_oauth_client_id() {
);
}
+#[test]
+fn oauth_client_secret_round_trips_without_debug_disclosure() {
+ let cfg: McpServerConfig = toml::from_str(
+ r#"
+ url = "https://example.com/mcp"
+
+ [oauth]
+ client_id = "confidential-client"
+ client_secret = "test-client-secret"
+ "#,
+ )
+ .expect("should deserialize an OAuth client secret");
+ assert_eq!(
+ cfg.oauth,
+ Some(McpServerOAuthConfig {
+ client_id: Some("confidential-client".to_string()),
+ client_secret: Some("test-client-secret".into()),
+ ..Default::default()
+ })
+ );
+ assert_eq!(cfg.oauth_client_secret(), Some("test-client-secret"));
+
+ let serialized = serde_json::to_value(&cfg).expect("serialize server as JSON");
+ assert_eq!(
+ serialized["oauth"],
+ serde_json::json!({
+ "client_id": "confidential-client",
+ "client_secret": "test-client-secret"
+ })
+ );
+ assert_eq!(
+ serde_json::from_value::<McpServerConfig>(serialized).expect("deserialize JSON"),
+ cfg
+ );
+ assert_eq!(
+ toml::from_str::<McpServerConfig>(&toml::to_string(&cfg).expect("serialize TOML"))
+ .expect("deserialize TOML"),
+ cfg
+ );
+
+ let debug = format!("{cfg:?}");
+ assert!(!debug.contains("test-client-secret"));
+ assert!(debug.contains("client_secret: Some(<redacted>)"));
+}
+
+#[test]
+fn oauth_client_secret_requires_nonempty_secret_and_client_id() {
+ for (oauth, expected) in [
+ (
+ serde_json::json!({"client_id": "client", "client_secret": ""}),
+ "oauth.client_secret must not be empty",
+ ),
+ (
+ serde_json::json!({"client_id": "client", "client_secret": " \t"}),
+ "oauth.client_secret must not be empty",
+ ),
+ (
+ serde_json::json!({"client_secret": "test-client-secret"}),
+ "oauth.client_secret requires oauth.client_id",
+ ),
+ (
+ serde_json::json!({"client_id": "", "client_secret": "test-client-secret"}),
+ "oauth.client_secret requires oauth.client_id",
+ ),
+ (
+ serde_json::json!({"client_id": " \t", "client_secret": "test-client-secret"}),
+ "oauth.client_secret requires oauth.client_id",
+ ),
+ ] {
+ let err = serde_json::from_value::<McpServerConfig>(serde_json::json!({
+ "url": "https://example.com/mcp",
+ "oauth": oauth
+ }))
+ .expect_err("should reject invalid OAuth client credentials");
+ assert_eq!(err.to_string(), expected);
+ }
+}
+
#[test]
fn oauth_callback_port_prefers_server_port_over_global_port() {
let cfg: McpServerConfig = toml::from_str(
diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json
index 76e227be9a..95af497bdc 100644
--- a/codex-rs/core/config.schema.json
+++ b/codex-rs/core/config.schema.json
@@ -2361,6 +2361,10 @@
"client_id": {
"description": "Explicit OAuth client identifier to present during authorization and token exchange.",
"type": "string"
+ },
+ "client_secret": {
+ "description": "OAuth client secret used for token exchange with a pre-registered client.",
+ "type": "string"
}
},
"type": "object"
diff --git a/codex-rs/core/src/config/edit/document_helpers.rs b/codex-rs/core/src/config/edit/document_helpers.rs
index 0c804412db..79b5e1ab99 100644
--- a/codex-rs/core/src/config/edit/document_helpers.rs
+++ b/codex-rs/core/src/config/edit/document_helpers.rs
@@ -158,6 +158,9 @@ fn serialize_mcp_server_table(config: &McpServerConfig) -> anyhow::Result<TomlTa
{
oauth_table["client_id"] = value(client_id.clone());
}
+ if let Some(client_secret) = &oauth.client_secret {
+ oauth_table["client_secret"] = value(client_secret.as_str());
+ }
if let Some(callback_url) = &oauth.callback_url {
oauth_table["callback_url"] = value(callback_url.clone());
}
diff --git a/codex-rs/core/src/config/edit_tests.rs b/codex-rs/core/src/config/edit_tests.rs
index a22c7951b1..24a7658e1f 100644
--- a/codex-rs/core/src/config/edit_tests.rs
+++ b/codex-rs/core/src/config/edit_tests.rs
@@ -1124,6 +1124,7 @@ fn blocking_replace_mcp_servers_round_trips() {
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: Some("eci-prd-pub-codex-123".to_string()),
+ client_secret: Some("test-client-secret".into()),
callback_url: Some("http://127.0.0.1/callback/example".to_string()),
callback_port: Some(9876),
..Default::default()
@@ -1165,6 +1166,7 @@ Z-Header = \"z\"
[mcp_servers.http.oauth]
client_id = \"eci-prd-pub-codex-123\"
+client_secret = \"test-client-secret\"
callback_url = \"http://127.0.0.1/callback/example\"
callback_port = 9876
diff --git a/codex-rs/core/src/mcp_skill_dependencies.rs b/codex-rs/core/src/mcp_skill_dependencies.rs
index 12b0608652..8b080bc483 100644
--- a/codex-rs/core/src/mcp_skill_dependencies.rs
+++ b/codex-rs/core/src/mcp_skill_dependencies.rs
@@ -189,7 +189,7 @@ async fn maybe_install_mcp_dependencies(
server_config.scopes.clone(),
oauth_config.discovered_scopes.clone(),
);
- let oauth_client_id = server_config.oauth_client_id();
+ let oauth_client_config = server_config.oauth.as_ref();
let oauth_credential_name = server_config.oauth_credential_name(&name);
let callback_port = server_config.oauth_callback_port(config.mcp_oauth_callback_port);
let first_attempt = perform_oauth_login(
@@ -200,7 +200,7 @@ async fn maybe_install_mcp_dependencies(
oauth_config.http_headers.clone(),
oauth_config.env_http_headers.clone(),
&resolved_scopes.scopes,
- oauth_client_id,
+ oauth_client_config,
McpOAuthClientRegistration::Auto,
server_config.oauth_resource.as_deref(),
callback_port,
@@ -220,7 +220,7 @@ async fn maybe_install_mcp_dependencies(
oauth_config.http_headers,
oauth_config.env_http_headers,
&[],
- oauth_client_id,
+ oauth_client_config,
McpOAuthClientRegistration::Auto,
server_config.oauth_resource.as_deref(),
callback_port,
diff --git a/codex-rs/rmcp-client/src/enterprise_oauth_login.rs b/codex-rs/rmcp-client/src/enterprise_oauth_login.rs
index 6c805fd460..92bf031e76 100644
--- a/codex-rs/rmcp-client/src/enterprise_oauth_login.rs
+++ b/codex-rs/rmcp-client/src/enterprise_oauth_login.rs
@@ -216,7 +216,10 @@ pub async fn perform_enterprise_oauth_login_return_url(
redirect_mode: request.redirect_mode,
},
&["openid".to_string(), "offline_access".to_string()],
- Some(request.client_id),
+ Some(&codex_config::McpServerOAuthConfig {
+ client_id: Some(request.client_id.to_string()),
+ ..Default::default()
+ }),
OAuthLoginPurpose::EnterpriseIdp,
McpOAuthClientRegistration::Auto,
/*oauth_resource*/ None,
diff --git a/codex-rs/rmcp-client/src/lib.rs b/codex-rs/rmcp-client/src/lib.rs
index ab270cc95f..3a4a2b0f1c 100644
--- a/codex-rs/rmcp-client/src/lib.rs
+++ b/codex-rs/rmcp-client/src/lib.rs
@@ -16,6 +16,7 @@ mod local_stdio_transport;
mod logging_client_handler;
mod oauth;
mod oauth_callback;
+mod oauth_client_credentials;
mod oauth_client_registration;
mod oauth_http_client;
mod oauth_refresh_mode;
diff --git a/codex-rs/rmcp-client/src/oauth.rs b/codex-rs/rmcp-client/src/oauth.rs
index 5ec028225a..c4fa7a1f95 100644
--- a/codex-rs/rmcp-client/src/oauth.rs
+++ b/codex-rs/rmcp-client/src/oauth.rs
@@ -68,6 +68,7 @@ use self::store_lock::OAuthStore;
use self::store_lock::OAuthStoreLock;
use self::store_lock::OAuthStoreLockFailure;
+use codex_config::McpServerOAuthConfig;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use rmcp::transport::auth::AuthorizationManager;
@@ -717,6 +718,7 @@ struct OAuthPersistorInner {
url: String,
authorization_manager: Arc<Mutex<AuthorizationManager>>,
credential_store: ResolvedOAuthCredentialStore,
+ oauth_config: Option<McpServerOAuthConfig>,
last_credentials: Mutex<Option<StoredOAuthTokens>>,
}
@@ -727,6 +729,7 @@ impl OAuthPersistor {
authorization_manager: Arc<Mutex<AuthorizationManager>>,
credential_store: ResolvedOAuthCredentialStore,
initial_credentials: Option<StoredOAuthTokens>,
+ oauth_config: Option<McpServerOAuthConfig>,
) -> Self {
Self {
inner: Arc::new(OAuthPersistorInner {
@@ -735,6 +738,7 @@ impl OAuthPersistor {
authorization_manager,
credential_store,
last_credentials: Mutex::new(initial_credentials),
+ oauth_config,
}),
}
}
diff --git a/codex-rs/rmcp-client/src/oauth/credential_store.rs b/codex-rs/rmcp-client/src/oauth/credential_store.rs
index 0429efde42..2d79fe403b 100644
--- a/codex-rs/rmcp-client/src/oauth/credential_store.rs
+++ b/codex-rs/rmcp-client/src/oauth/credential_store.rs
@@ -18,6 +18,7 @@ use std::sync::Weak;
use anyhow::Context;
use anyhow::Result;
+use codex_config::McpServerOAuthConfig;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use futures::future::BoxFuture;
@@ -31,6 +32,7 @@ use rmcp::transport::auth::StoredCredentials;
use tokio::sync::Mutex;
use tracing::warn;
+use crate::oauth_client_credentials::OAuthClientCredentials;
use crate::oauth_http_client::PROACTIVE_REFRESH_TIMEOUT;
use super::RefreshCredentialLock;
@@ -56,6 +58,7 @@ struct OAuthCredentialStoreInner<K> {
issuer: Option<String>,
store: ResolvedOAuthCredentialStore,
keyring: K,
+ oauth_config: Option<McpServerOAuthConfig>,
last_credentials: Mutex<Option<StoredOAuthTokens>>,
refresh_guard: Mutex<Weak<RefreshCredentialLock>>,
}
@@ -65,6 +68,7 @@ impl<K: KeyringStore + Clone + 'static> OAuthCredentialStore<K> {
tokens: StoredOAuthTokens,
store: ResolvedOAuthCredentialStore,
keyring: K,
+ oauth_config: Option<McpServerOAuthConfig>,
) -> Self {
Self {
inner: Arc::new(OAuthCredentialStoreInner {
@@ -74,6 +78,7 @@ impl<K: KeyringStore + Clone + 'static> OAuthCredentialStore<K> {
issuer: tokens.bound_issuer().map(str::to_owned),
store,
keyring,
+ oauth_config,
last_credentials: Mutex::new(Some(tokens)),
refresh_guard: Mutex::new(Weak::new()),
}),
@@ -97,6 +102,11 @@ impl<K: KeyringStore + Clone + 'static> OAuthCredentialStore<K> {
validate_refresh_token_issuer(&metadata, &tokens)?;
manager.set_metadata(metadata);
manager.configure_client_id(&tokens.client_id)?;
+ OAuthClientCredentials::resolve(self.inner.oauth_config.as_ref())?.configure_for_refresh(
+ manager,
+ &self.inner.url,
+ &tokens.client_id,
+ )?;
// Reuse the guard for RMCP's exchange and save after the locked freshness check.
manager.set_credential_store(Self {
inner: Arc::clone(&self.inner),
diff --git a/codex-rs/rmcp-client/src/oauth/refresh_transaction.rs b/codex-rs/rmcp-client/src/oauth/refresh_transaction.rs
index e4804dd57c..e5341ca73b 100644
--- a/codex-rs/rmcp-client/src/oauth/refresh_transaction.rs
+++ b/codex-rs/rmcp-client/src/oauth/refresh_transaction.rs
@@ -7,6 +7,7 @@ use std::time::UNIX_EPOCH;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
+use codex_config::McpServerOAuthConfig;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use oauth2::TokenResponse;
@@ -20,6 +21,8 @@ use tokio::time::timeout;
use tracing::debug;
use tracing::warn;
+use crate::oauth_client_credentials::OAuthClientCredentials;
+
use super::OAuthPersistor;
use super::OAuthPersistorInner;
use super::StoredOAuthTokens;
@@ -152,7 +155,8 @@ impl OAuthPersistor {
});
}
}
- install_tokens_in_manager(&mut guard, &latest).await?;
+ install_tokens_in_manager(&mut guard, &latest, self.inner.oauth_config.as_ref())
+ .await?;
*self.inner.last_credentials.lock().await = Some(latest);
return Ok(());
}
@@ -178,7 +182,7 @@ impl OAuthPersistor {
.metadata;
validate_refresh_token_issuer(&metadata, &latest)?;
guard.set_metadata(metadata);
- install_tokens_in_manager(&mut guard, &latest)
+ install_tokens_in_manager(&mut guard, &latest, self.inner.oauth_config.as_ref())
.await
.context("failed to stage OAuth credentials for refresh")?;
// The owned task prevents caller deadlines from canceling after possible token rotation;
@@ -251,7 +255,7 @@ impl OAuthPersistor {
error = %error,
"failed to persist refreshed MCP OAuth credentials; returning the error and restoring the previous in-process credentials"
);
- install_tokens_in_manager(&mut guard, &latest)
+ install_tokens_in_manager(&mut guard, &latest, self.inner.oauth_config.as_ref())
.await
.context(
"failed to restore previous OAuth credentials after refresh persistence failed",
@@ -262,7 +266,7 @@ impl OAuthPersistor {
// This layer retains RMCP's legacy persistence hook. Install the same merged response
// (including carried-forward refresh token/scopes) so that hook cannot overwrite durable
// credentials with the provider's partial response.
- install_tokens_in_manager(&mut guard, &refreshed)
+ install_tokens_in_manager(&mut guard, &refreshed, self.inner.oauth_config.as_ref())
.await
.context(
"refreshed OAuth tokens were persisted but could not be installed in the authorization manager",
@@ -315,7 +319,8 @@ impl OAuthPersistor {
);
}
debug!("adopting new MCP OAuth credentials after a failed refresh");
- install_tokens_in_manager(manager, &replacement).await?;
+ install_tokens_in_manager(manager, &replacement, self.inner.oauth_config.as_ref())
+ .await?;
*self.inner.last_credentials.lock().await = Some(replacement);
return Ok(());
}
@@ -335,7 +340,10 @@ fn token_has_expired(expires_at: Option<u64>) -> bool {
pub(crate) async fn install_tokens_in_manager(
authorization_manager: &mut AuthorizationManager,
tokens: &StoredOAuthTokens,
+ oauth_config: Option<&McpServerOAuthConfig>,
) -> Result<()> {
+ let credentials = OAuthClientCredentials::resolve(oauth_config)?;
+ credentials.validate_stored_client_id(&tokens.client_id)?;
let store = InMemoryCredentialStore::new();
let token_response = tokens.token_response.0.clone();
let granted_scopes = token_response
@@ -366,6 +374,7 @@ pub(crate) async fn install_tokens_in_manager(
.initialize_from_store()
.await
.context("failed to adopt refreshed OAuth tokens")?;
+ credentials.configure_for_refresh(authorization_manager, &tokens.url, &tokens.client_id)?;
Ok(())
}
diff --git a/codex-rs/rmcp-client/src/oauth/tests/credential_store_tests.rs b/codex-rs/rmcp-client/src/oauth/tests/credential_store_tests.rs
index d8b4e3bdb1..86882fc464 100644
--- a/codex-rs/rmcp-client/src/oauth/tests/credential_store_tests.rs
+++ b/codex-rs/rmcp-client/src/oauth/tests/credential_store_tests.rs
@@ -38,6 +38,7 @@ async fn mutations_require_and_retain_the_transaction_guard() -> Result<()> {
initial.clone(),
ResolvedOAuthCredentialStore::File,
MockKeyringStore::default(),
+ /*oauth_config*/ None,
);
let guard = store.acquire_transaction_guard().await?;
let credentials = store.load().await?.unwrap();
@@ -104,7 +105,12 @@ async fn save_publishes_only_persisted_credentials() -> Result<()> {
.0
.set_access_token(AccessToken::new("fallback-token".into()));
save_oauth_tokens_to_file(&fallback)?;
- let store = OAuthCredentialStore::new(initial.clone(), authority, keyring.clone());
+ let store = OAuthCredentialStore::new(
+ initial.clone(),
+ authority,
+ keyring.clone(),
+ /*oauth_config*/ None,
+ );
let _guard = store.acquire_transaction_guard().await?;
let mut credentials = store.load().await?.expect("stored credentials");
let token_response = credentials
@@ -163,6 +169,7 @@ async fn pinned_read_failure_does_not_adopt_fallback_credentials() -> Result<()>
initial.clone(),
ResolvedOAuthCredentialStore::Keyring(AuthKeyringBackendKind::Direct),
keyring,
+ /*oauth_config*/ None,
);
let cached = store.load().await?.expect("cached credentials");
assert_eq!(
@@ -189,6 +196,7 @@ async fn replacement_or_removal_does_not_acknowledge_a_new_runtime_snapshot() ->
initial.clone(),
ResolvedOAuthCredentialStore::File,
MockKeyringStore::default(),
+ /*oauth_config*/ None,
);
let original_snapshot = store.stored_credentials().await;
for (client_id, issuer) in [
@@ -232,6 +240,7 @@ async fn storage_roundtrip_preserves_absolute_and_unknown_expiry() -> Result<()>
initial.clone(),
ResolvedOAuthCredentialStore::File,
MockKeyringStore::default(),
+ /*oauth_config*/ None,
);
let future_received_at = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let future_deadline = (future_received_at + 120) * 1000;
diff --git a/codex-rs/rmcp-client/src/oauth/tests/persistor_tests.rs b/codex-rs/rmcp-client/src/oauth/tests/persistor_tests.rs
index 057fb7c6fd..2951504e59 100644
--- a/codex-rs/rmcp-client/src/oauth/tests/persistor_tests.rs
+++ b/codex-rs/rmcp-client/src/oauth/tests/persistor_tests.rs
@@ -181,6 +181,7 @@ async fn coordinated_401_refresh_rereads_and_persists_before_retry() -> Result<(
initial.clone(),
ResolvedOAuthCredentialStore::File,
DefaultKeyringStore,
+ /*oauth_config*/ None,
));
let client = AuthClient::new(
StreamableHttpClientAdapter::new(
@@ -397,6 +398,7 @@ async fn resolved_keyring_read_error_preserves_in_memory_credentials() -> Result
Arc::clone(&manager),
ResolvedOAuthCredentialStore::Keyring(AuthKeyringBackendKind::Direct),
Some(initial.clone()),
+ /*oauth_config*/ None,
);
let error = persistor
@@ -875,6 +877,7 @@ async fn coordinated_manager_for(
tokens.clone(),
ResolvedOAuthCredentialStore::File,
DefaultKeyringStore,
+ /*oauth_config*/ None,
);
manager.set_credential_store(store.clone());
Ok((Arc::new(TokioMutex::new(manager)), store))
@@ -887,6 +890,7 @@ async fn persistor_for(tokens: &StoredOAuthTokens) -> Result<OAuthPersistor> {
Arc::new(TokioMutex::new(authorization_manager_for(tokens).await?)),
ResolvedOAuthCredentialStore::File,
Some(tokens.clone()),
+ /*oauth_config*/ None,
))
}
diff --git a/codex-rs/rmcp-client/src/oauth_callback_input.rs b/codex-rs/rmcp-client/src/oauth_callback_input.rs
index 5358764137..46037eea0c 100644
--- a/codex-rs/rmcp-client/src/oauth_callback_input.rs
+++ b/codex-rs/rmcp-client/src/oauth_callback_input.rs
@@ -14,6 +14,7 @@ use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
+use codex_config::McpServerOAuthConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::HttpClient;
@@ -35,7 +36,7 @@ pub async fn perform_oauth_login_with_callback_input<F>(
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
scopes: &[String],
- oauth_client_id: Option<&str>,
+ oauth_config: Option<&McpServerOAuthConfig>,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
callback_port: Option<u16>,
@@ -59,7 +60,7 @@ where
redirect_mode: StreamableHttpRedirectMode::Legacy,
},
scopes,
- oauth_client_id,
+ oauth_config,
OAuthLoginPurpose::Mcp,
client_registration,
oauth_resource,
diff --git a/codex-rs/rmcp-client/src/oauth_client_credentials.rs b/codex-rs/rmcp-client/src/oauth_client_credentials.rs
new file mode 100644
index 0000000000..8b11ba8b37
--- /dev/null
+++ b/codex-rs/rmcp-client/src/oauth_client_credentials.rs
@@ -0,0 +1,68 @@
+//! Applies configured OAuth client secrets to login and refresh without persisting them.
+//! A confidential client must never reuse tokens issued to a different client ID.
+
+use anyhow::Context;
+use anyhow::Result;
+use anyhow::bail;
+use codex_config::McpServerOAuthConfig;
+use oauth2::ClientSecret;
+use rmcp::transport::AuthorizationManager;
+use rmcp::transport::auth::AuthError;
+use rmcp::transport::auth::OAuthClientConfig;
+
+#[derive(Debug, Default)]
+pub(crate) struct OAuthClientCredentials {
+ pub(crate) client_id: Option<String>,
+ pub(crate) client_secret: Option<ClientSecret>,
+}
+
+impl OAuthClientCredentials {
+ pub(crate) fn resolve(config: Option<&McpServerOAuthConfig>) -> Result<Self> {
+ let client_id = config
+ .and_then(|config| config.client_id.clone())
+ .filter(|id| !id.trim().is_empty());
+ let client_secret = config
+ .and_then(|config| config.client_secret.as_ref())
+ .map(|secret| ClientSecret::new(secret.to_string()));
+ if client_secret.is_some() && client_id.is_none() {
+ bail!("MCP OAuth client_secret requires a nonempty client_id");
+ }
+ if client_secret
+ .as_ref()
+ .is_some_and(|secret| secret.secret().trim().is_empty())
+ {
+ bail!("MCP OAuth client_secret must not be empty");
+ }
+ Ok(Self {
+ client_id,
+ client_secret,
+ })
+ }
+
+ pub(crate) fn validate_stored_client_id(&self, stored_client_id: &str) -> Result<()> {
+ if self.client_secret.is_some() && self.client_id.as_deref() != Some(stored_client_id) {
+ return Err(AuthError::AuthorizationRequired).context(
+ "Configured MCP OAuth client ID differs from stored credentials; log in again",
+ );
+ }
+ Ok(())
+ }
+
+ pub(crate) fn configure_for_refresh(
+ &self,
+ manager: &mut AuthorizationManager,
+ server_url: &str,
+ stored_client_id: &str,
+ ) -> Result<()> {
+ self.validate_stored_client_id(stored_client_id)?;
+ if let Some(secret) = &self.client_secret {
+ // Preserve the manager's application type, as configure_client_id does.
+ // Refresh does not send the redirect URI.
+ let mut config = OAuthClientConfig::new(stored_client_id, server_url)
+ .with_client_secret(secret.secret());
+ config.application_type = None;
+ manager.configure_client(config)?;
+ }
+ Ok(())
+ }
+}
diff --git a/codex-rs/rmcp-client/src/oauth_http_client_security_tests.rs b/codex-rs/rmcp-client/src/oauth_http_client_security_tests.rs
index d4b8a64444..6ce9f0a34e 100644
--- a/codex-rs/rmcp-client/src/oauth_http_client_security_tests.rs
+++ b/codex-rs/rmcp-client/src/oauth_http_client_security_tests.rs
@@ -388,6 +388,12 @@ async fn oauth_registration_redirects_never_forward_resource_only_headers() -> R
async fn same_origin_redirects_preserve_timeout_and_response_body_limits() -> Result<()> {
for oversized_redirect_body in [false, true] {
let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/warmup"))
+ .respond_with(ResponseTemplate::new(204))
+ .expect(1)
+ .mount(&server)
+ .await;
let resource_url = format!("{}/mcp", server.uri());
let redirect = ResponseTemplate::new(307).insert_header("location", "/register/");
let redirect = if oversized_redirect_body {
@@ -423,6 +429,17 @@ async fn same_origin_redirects_preserve_timeout_and_response_body_limits() -> Re
)?,
&resource_url,
);
+ // Measure redirect handling after lazy native HTTP client initialization.
+ adapter
+ .execute_request(
+ oauth2::http::Request::builder()
+ .uri(format!("{}/warmup", server.uri()))
+ .body(Vec::new())?,
+ OAuthHttpRedirectPolicy::Stop,
+ /*timeout*/ None,
+ )
+ .await
+ .expect("HTTP client warmup should succeed");
let error = adapter
.execute_request(
oauth2::http::Request::builder()
diff --git a/codex-rs/rmcp-client/src/perform_oauth_login.rs b/codex-rs/rmcp-client/src/perform_oauth_login.rs
index a1b094a041..ce7839cb8a 100644
--- a/codex-rs/rmcp-client/src/perform_oauth_login.rs
+++ b/codex-rs/rmcp-client/src/perform_oauth_login.rs
@@ -8,6 +8,7 @@ use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
+use codex_config::McpServerOAuthConfig;
use codex_exec_server::HttpClient;
use rmcp::transport::AuthorizationManager;
use rmcp::transport::AuthorizationSession;
@@ -36,6 +37,7 @@ use crate::oauth_callback::callback_id_from_server_url;
use crate::oauth_callback::callback_mode;
use crate::oauth_callback::resolve_mcp_oauth_callback_url;
use crate::oauth_callback::validate_callback_redirect;
+use crate::oauth_client_credentials::OAuthClientCredentials;
use crate::oauth_client_registration::McpOAuthClientRegistration;
use crate::oauth_client_registration::PreparedOAuthLogin;
use crate::oauth_client_registration::start_authorization as start_client_registration;
@@ -111,7 +113,7 @@ pub async fn perform_oauth_login(
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
scopes: &[String],
- oauth_client_id: Option<&str>,
+ oauth_config: Option<&McpServerOAuthConfig>,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
callback_port: Option<u16>,
@@ -127,7 +129,7 @@ pub async fn perform_oauth_login(
http_headers,
env_http_headers,
scopes,
- oauth_client_id,
+ oauth_config,
client_registration,
oauth_resource,
callback_port,
@@ -149,7 +151,7 @@ pub async fn perform_oauth_login_silent(
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
scopes: &[String],
- oauth_client_id: Option<&str>,
+ oauth_config: Option<&McpServerOAuthConfig>,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
callback_port: Option<u16>,
@@ -166,7 +168,7 @@ pub async fn perform_oauth_login_silent(
http_headers,
env_http_headers,
scopes,
- oauth_client_id,
+ oauth_config,
client_registration,
oauth_resource,
callback_port,
@@ -188,7 +190,7 @@ async fn perform_oauth_login_with_browser_output(
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
scopes: &[String],
- oauth_client_id: Option<&str>,
+ oauth_config: Option<&McpServerOAuthConfig>,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
callback_port: Option<u16>,
@@ -211,7 +213,7 @@ async fn perform_oauth_login_with_browser_output(
keyring_backend_kind,
http_context,
scopes,
- oauth_client_id,
+ oauth_config,
OAuthLoginPurpose::Mcp,
client_registration,
oauth_resource,
@@ -235,7 +237,7 @@ pub async fn perform_oauth_login_return_url(
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
scopes: &[String],
- oauth_client_id: Option<&str>,
+ oauth_config: Option<&McpServerOAuthConfig>,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
timeout_secs: Option<i64>,
@@ -258,7 +260,7 @@ pub async fn perform_oauth_login_return_url(
keyring_backend_kind,
http_context,
scopes,
- oauth_client_id,
+ oauth_config,
OAuthLoginPurpose::Mcp,
client_registration,
oauth_resource,
@@ -538,7 +540,7 @@ impl OauthLoginFlow {
keyring_backend_kind: AuthKeyringBackendKind,
http_context: OAuthHttpContext,
scopes: &[String],
- oauth_client_id: Option<&str>,
+ oauth_config: Option<&McpServerOAuthConfig>,
purpose: OAuthLoginPurpose,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
@@ -550,6 +552,8 @@ impl OauthLoginFlow {
) -> Result<Self> {
const DEFAULT_OAUTH_TIMEOUT_SECS: i64 = 300;
+ let credentials = OAuthClientCredentials::resolve(oauth_config)?;
+ let oauth_client_id = credentials.client_id.as_deref();
let callback_port = resolve_callback_port(callback_port)?;
let is_enterprise_idp = matches!(purpose, OAuthLoginPurpose::EnterpriseIdp);
let (enterprise_bind_ip, callback_port) = if is_enterprise_idp {
@@ -564,7 +568,6 @@ impl OauthLoginFlow {
(None, callback_port)
};
let callback_id = callback_id_from_server_url(server_url)?;
- let oauth_client_id = oauth_client_id.filter(|client_id| !client_id.trim().is_empty());
let configured_callback = if oauth_client_id.is_some() {
callback_url
.map(|callback_url| {
@@ -682,6 +685,7 @@ impl OauthLoginFlow {
&redirect_uri,
&callback_id,
oauth_client_id,
+ credentials.client_secret.as_ref(),
purpose,
)
.await?
@@ -839,6 +843,7 @@ async fn resolve_authorization_manager(
Ok((auth_manager, metadata))
}
+#[allow(clippy::too_many_arguments)]
async fn start_authorization(
mut auth_manager: AuthorizationManager,
metadata: AuthorizationMetadata,
@@ -846,14 +851,18 @@ async fn start_authorization(
redirect_uri: &str,
callback_id: &str,
oauth_client_id: &str,
+ client_secret: Option<&oauth2::ClientSecret>,
purpose: OAuthLoginPurpose,
) -> Result<PreparedOAuthLogin> {
let strict_enterprise_idp = matches!(purpose, OAuthLoginPurpose::EnterpriseIdp);
let authorization_server_issuer = metadata.issuer.clone();
validate_callback_redirect(redirect_uri, callback_id, callback_mode(&metadata)?)?;
auth_manager.set_metadata(metadata);
- let client_config = OAuthClientConfig::new(oauth_client_id, redirect_uri)
+ let mut client_config = OAuthClientConfig::new(oauth_client_id, redirect_uri)
.with_scopes(scopes.iter().map(|scope| (*scope).to_string()).collect());
+ if let Some(secret) = client_secret {
+ client_config = client_config.with_client_secret(secret.secret());
+ }
auth_manager.configure_client(client_config)?;
let auth_url = auth_manager.get_authorization_url(scopes).await?;
let auth_url = if strict_enterprise_idp {
@@ -904,6 +913,7 @@ mod tests {
use axum::Router;
use axum::routing::get;
use axum::routing::post;
+ use codex_config::McpServerOAuthConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::ExecServerError;
@@ -1081,7 +1091,10 @@ mod tests {
redirect_mode: StreamableHttpRedirectMode::Legacy,
},
&[],
- Some("test-client"),
+ Some(&McpServerOAuthConfig {
+ client_id: Some("test-client".to_string()),
+ ..Default::default()
+ }),
OAuthLoginPurpose::Mcp,
McpOAuthClientRegistration::Auto,
/*oauth_resource*/ None,
@@ -1145,6 +1158,7 @@ mod tests {
redirect_uri,
"configured-client",
"eci-prd-pub-codex-123",
+ /*client_secret*/ None,
OAuthLoginPurpose::Mcp,
)
.await
@@ -1254,6 +1268,7 @@ mod tests {
redirect_uri,
"test-callback",
"test-client",
+ /*client_secret*/ None,
OAuthLoginPurpose::Mcp,
)
.await
@@ -1311,7 +1326,7 @@ mod tests {
/*http_headers*/ None,
/*env_http_headers*/ None,
&[],
- /*oauth_client_id*/ None,
+ /*oauth_config*/ None,
McpOAuthClientRegistration::Auto,
/*oauth_resource*/ None,
/*callback_port*/ None,
@@ -1336,7 +1351,7 @@ mod tests {
/*http_headers*/ None,
/*env_http_headers*/ None,
&[],
- /*oauth_client_id*/ None,
+ /*oauth_config*/ None,
McpOAuthClientRegistration::Auto,
/*oauth_resource*/ None,
/*callback_port*/ None,
diff --git a/codex-rs/rmcp-client/src/rmcp_client.rs b/codex-rs/rmcp-client/src/rmcp_client.rs
index 408d1b53ff..b8817d2eba 100644
--- a/codex-rs/rmcp-client/src/rmcp_client.rs
+++ b/codex-rs/rmcp-client/src/rmcp_client.rs
@@ -16,6 +16,7 @@ use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_api::SharedAuthProvider;
+use codex_config::McpServerOAuthConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::McpServerEnvVar;
use codex_exec_server::HttpClient;
@@ -88,6 +89,7 @@ use crate::oauth::StoredOAuthTokens;
use crate::oauth::install_tokens_in_manager;
use crate::oauth::resolve_oauth_tokens_from_store_policy;
use crate::oauth::validate_refresh_token_issuer;
+use crate::oauth_client_credentials::OAuthClientCredentials;
use crate::oauth_http_client::OAuthHttpClientAdapter;
use crate::oauth_refresh_mode::McpOAuthRefreshMode;
use crate::protocol_mode::McpProtocolMode;
@@ -162,6 +164,7 @@ enum TransportRecipe {
bearer_token: Option<StreamableHttpBearerToken>,
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
+ oauth_config: Option<Arc<McpServerOAuthConfig>>,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
pinned_credential_store: Arc<OnceLock<ResolvedOAuthCredentialStore>>,
@@ -567,6 +570,7 @@ impl RmcpClient {
bearer_token.map(StreamableHttpBearerToken::Resolved),
http_headers,
env_http_headers,
+ /*oauth_config*/ None,
store_mode,
keyring_backend_kind,
http_client,
@@ -585,6 +589,7 @@ impl RmcpClient {
bearer_token: Option<StreamableHttpBearerToken>,
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
+ oauth_config: Option<McpServerOAuthConfig>,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
http_client: Arc<dyn HttpClient>,
@@ -599,6 +604,7 @@ impl RmcpClient {
bearer_token,
http_headers,
env_http_headers,
+ oauth_config: oauth_config.map(Arc::new),
store_mode,
keyring_backend_kind,
pinned_credential_store: Arc::new(OnceLock::new()),
@@ -1103,6 +1109,7 @@ impl RmcpClient {
bearer_token,
http_headers,
env_http_headers,
+ oauth_config,
store_mode,
keyring_backend_kind,
pinned_credential_store,
@@ -1134,6 +1141,7 @@ impl RmcpClient {
&& auth_provider.is_none()
&& !default_headers.contains_key(AUTHORIZATION)
{
+ OAuthClientCredentials::resolve(oauth_config.as_deref())?;
let oauth_server_name = server_name.clone();
let oauth_url = url.clone();
let oauth_store_mode = *store_mode;
@@ -1198,6 +1206,7 @@ impl RmcpClient {
*redirect_mode,
*oauth_refresh_mode,
Arc::clone(initialize_deadline),
+ oauth_config.as_deref(),
)
.await
{
@@ -1596,7 +1605,10 @@ async fn create_oauth_transport_and_runtime(
redirect_mode: StreamableHttpRedirectMode,
oauth_refresh_mode: McpOAuthRefreshMode,
initialize_deadline: Arc<StdMutex<Option<Instant>>>,
+ oauth_config: Option<&McpServerOAuthConfig>,
) -> Result<PendingTransport> {
+ OAuthClientCredentials::resolve(oauth_config)?
+ .validate_stored_client_id(&initial_tokens.client_id)?;
let oauth_http_client = Arc::new(OAuthHttpClientAdapter::new_with_redirect_mode(
http_client.clone(),
default_headers.clone(),
@@ -1625,13 +1637,14 @@ async fn create_oauth_transport_and_runtime(
runtime_tokens.token_response.0.set_refresh_token(None);
runtime_tokens.issuer = None;
}
- install_tokens_in_manager(&mut manager, &runtime_tokens).await?;
+ install_tokens_in_manager(&mut manager, &runtime_tokens, oauth_config).await?;
let coordinated_store = match oauth_refresh_mode {
McpOAuthRefreshMode::Coordinated if !use_stored_access_token_only => {
let store = OAuthCredentialStore::new(
initial_tokens.clone(),
credential_store,
DefaultKeyringStore,
+ oauth_config.cloned(),
);
manager.set_credential_store(store.clone());
Some(store)
@@ -1675,6 +1688,7 @@ async fn create_oauth_transport_and_runtime(
auth_manager,
credential_store,
Some(initial_tokens),
+ oauth_config.cloned(),
)),
};
diff --git a/codex-rs/rmcp-client/tests/mcp_2026_oauth_discovery.rs b/codex-rs/rmcp-client/tests/mcp_2026_oauth_discovery.rs
index a26dc7fbee..2419821d97 100644
--- a/codex-rs/rmcp-client/tests/mcp_2026_oauth_discovery.rs
+++ b/codex-rs/rmcp-client/tests/mcp_2026_oauth_discovery.rs
@@ -643,6 +643,11 @@ async fn interactive_oauth_rejects_untrusted_authorization_metadata() -> anyhow:
.await;
for oauth_client_id in [None, Some("preregistered-client")] {
+ let oauth_config =
+ oauth_client_id.map(|client_id| codex_config::McpServerOAuthConfig {
+ client_id: Some(client_id.to_string()),
+ ..Default::default()
+ });
let error = perform_oauth_login_return_url(
"untrusted-oauth-metadata",
&resource_url,
@@ -651,7 +656,7 @@ async fn interactive_oauth_rejects_untrusted_authorization_metadata() -> anyhow:
/*http_headers*/ None,
/*env_http_headers*/ None,
/*scopes*/ &[],
- oauth_client_id,
+ oauth_config.as_ref(),
McpOAuthClientRegistration::Dcr,
/*oauth_resource*/ None,
Some(/*timeout_secs*/ 5),
diff --git a/codex-rs/rmcp-client/tests/streamable_http_oauth_startup.rs b/codex-rs/rmcp-client/tests/streamable_http_oauth_startup.rs
index 374e3232c2..57604d3bad 100644
--- a/codex-rs/rmcp-client/tests/streamable_http_oauth_startup.rs
+++ b/codex-rs/rmcp-client/tests/streamable_http_oauth_startup.rs
@@ -8,6 +8,8 @@ use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
+use base64::Engine;
+use codex_config::McpServerOAuthConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::Environment;
@@ -55,6 +57,8 @@ const RESOURCE_API_KEY: &str = "resource-api-key-secret";
const RESOURCE_USER_AGENT: &str = "resource-only-user-agent";
const MCP_USER_AGENT: &str = concat!("codex-mcp-client/", env!("CARGO_PKG_VERSION"));
const CHILD_SERVER_URL_ENV: &str = "MCP_TEST_OAUTH_STARTUP_SERVER_URL";
+const CLIENT_SECRET: &str = "configured-client-secret";
+const CHILD_CONFIDENTIAL_CLIENT_ID_ENV: &str = "MCP_TEST_OAUTH_CONFIDENTIAL_CLIENT_ID";
const CHILD_REFRESH_MODE_ENV: &str = "MCP_TEST_OAUTH_REFRESH_MODE";
const CHILD_HELPER_COMMAND_ENV: &str = "MCP_TEST_OAUTH_STARTUP_HELPER_COMMAND";
const CHILD_RESOURCE_API_KEY_ENV: &str = "MCP_TEST_OAUTH_STARTUP_RESOURCE_API_KEY";
@@ -68,6 +72,8 @@ const REFRESHABLE_SERVER_URL: &str = "https://refreshable.example/mcp";
#[derive(Clone, Copy)]
enum OAuthStartupScenario {
DirectAuthorizationMetadata,
+ ClientSecretBasic,
+ ClientSecretPost,
OidcMetadataAfter503,
GatewayHeadersHelper,
SameOriginGatewayHeadersHelper,
@@ -256,6 +262,47 @@ async fn refreshes_expired_persisted_token_before_initialize() -> anyhow::Result
.await
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+async fn refreshes_confidential_client_without_persisting_secret() -> anyhow::Result<()> {
+ for scenario in [
+ OAuthStartupScenario::ClientSecretBasic,
+ OAuthStartupScenario::ClientSecretPost,
+ ] {
+ for refresh_mode in [
+ McpOAuthRefreshMode::Legacy,
+ McpOAuthRefreshMode::Coordinated,
+ ] {
+ assert_expired_token_refresh(scenario, refresh_mode).await?;
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+async fn rejects_confidential_client_id_mismatch_before_contacting_provider() -> anyhow::Result<()>
+{
+ let server = MockServer::start().await;
+ let codex_home = TempDir::new()?;
+ let status = Command::new(std::env::current_exe()?)
+ .args(["oauth_startup_child", "--exact", "--ignored", "--nocapture"])
+ .env("CODEX_HOME", codex_home.path())
+ .env(CHILD_SERVER_URL_ENV, format!("{}/mcp", server.uri()))
+ .env(CHILD_STORED_ISSUER_ENV, server.uri())
+ .env(CHILD_RESOURCE_API_KEY_ENV, RESOURCE_API_KEY)
+ .env(CHILD_CONFIDENTIAL_CLIENT_ID_ENV, "different-client-id")
+ .status()
+ .await?;
+ assert!(status.success(), "OAuth startup child failed: {status}");
+ assert!(
+ server
+ .received_requests()
+ .await
+ .unwrap_or_default()
+ .is_empty()
+ );
+ Ok(())
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn refreshes_expired_persisted_token_after_oidc_fallback() -> anyhow::Result<()> {
for refresh_mode in [
@@ -313,6 +360,8 @@ async fn assert_expired_token_refresh(
let resource_url = format!("{}/mcp", server.uri());
let (server_url, mcp_path, authorization_metadata_path) = match scenario {
OAuthStartupScenario::DirectAuthorizationMetadata
+ | OAuthStartupScenario::ClientSecretBasic
+ | OAuthStartupScenario::ClientSecretPost
| OAuthStartupScenario::GatewayHeadersHelper
| OAuthStartupScenario::SameOriginGatewayHeadersHelper => (
resource_url.clone(),
@@ -371,6 +420,18 @@ async fn assert_expired_token_refresh(
if matches!(scenario, OAuthStartupScenario::ProtectedResourceMetadata) {
authorization_metadata["issuer"] = json!(server.uri());
}
+ let client_auth_method = match scenario {
+ OAuthStartupScenario::ClientSecretBasic => Some("client_secret_basic"),
+ OAuthStartupScenario::ClientSecretPost => Some("client_secret_post"),
+ OAuthStartupScenario::DirectAuthorizationMetadata
+ | OAuthStartupScenario::OidcMetadataAfter503
+ | OAuthStartupScenario::GatewayHeadersHelper
+ | OAuthStartupScenario::SameOriginGatewayHeadersHelper
+ | OAuthStartupScenario::ProtectedResourceMetadata => None,
+ };
+ if let Some(method) = client_auth_method {
+ authorization_metadata["token_endpoint_auth_methods_supported"] = json!([method]);
+ }
let authorization_server_issuer = authorization_metadata["issuer"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("authorization metadata should include issuer"))?
@@ -407,6 +468,30 @@ async fn assert_expired_token_refresh(
.any(|(name, value)| name == "resource" && value == expected_resource)
}
})
+ .and(move |request: &Request| match client_auth_method {
+ Some("client_secret_basic") => {
+ let encoded = base64::engine::general_purpose::STANDARD
+ .encode(format!("test-client-id:{CLIENT_SECRET}"));
+ request
+ .headers
+ .get("authorization")
+ .is_some_and(|value| value.as_bytes() == format!("Basic {encoded}").as_bytes())
+ && !request
+ .body
+ .windows(CLIENT_SECRET.len())
+ .any(|value| value == CLIENT_SECRET.as_bytes())
+ }
+ Some("client_secret_post") => {
+ let form: HashMap<_, _> = url::form_urlencoded::parse(&request.body).collect();
+ form.get("client_id")
+ .is_some_and(|value| value == "test-client-id")
+ && form
+ .get("client_secret")
+ .is_some_and(|value| value == CLIENT_SECRET)
+ && !request.headers.contains_key("authorization")
+ }
+ _ => true,
+ })
.respond_with(move |request: &Request| {
if same_origin_gateway
&& request
@@ -499,6 +584,9 @@ async fn assert_expired_token_refresh(
},
)
.env("MCP_TEST_AMBIENT_SECRET", "must-not-reach-helper");
+ if client_auth_method.is_some() {
+ command.env(CHILD_CONFIDENTIAL_CLIENT_ID_ENV, "test-client-id");
+ }
if with_headers_helper {
command.env(
CHILD_HELPER_COMMAND_ENV,
@@ -511,6 +599,10 @@ async fn assert_expired_token_refresh(
}
let status = command.status().await?;
assert!(status.success(), "OAuth startup child failed: {status}");
+ let persisted_credentials =
+ std::fs::read_to_string(codex_home.path().join(".credentials.json"))?;
+ assert!(!persisted_credentials.contains(CLIENT_SECRET));
+ assert!(!persisted_credentials.contains("client_secret"));
if with_headers_helper {
assert_eq!(
std::fs::read_to_string(helper_invocations)?,
@@ -991,6 +1083,16 @@ async fn oauth_startup_child() -> anyhow::Result<()> {
std::env::current_dir()?,
)?;
}
+ let oauth_config = std::env::var(CHILD_CONFIDENTIAL_CLIENT_ID_ENV)
+ .ok()
+ .map(|client_id| McpServerOAuthConfig {
+ client_id: Some(client_id),
+ client_secret: Some(CLIENT_SECRET.into()),
+ ..Default::default()
+ });
+ let mismatched_client = oauth_config
+ .as_ref()
+ .is_some_and(|config| config.client_id.as_deref() != Some(tokens.client_id.as_str()));
let client = RmcpClient::new_streamable_http_client_with_protocol_mode_and_redirect_mode(
SERVER_NAME,
&server_url,
@@ -1003,6 +1105,7 @@ async fn oauth_startup_child() -> anyhow::Result<()> {
"X-Api-Key".to_string(),
CHILD_RESOURCE_API_KEY_ENV.to_string(),
)])),
+ oauth_config,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
http_client,
@@ -1011,7 +1114,21 @@ async fn oauth_startup_child() -> anyhow::Result<()> {
StreamableHttpRedirectMode::Legacy,
refresh_mode,
)
- .await?;
+ .await;
+
+ if mismatched_client {
+ let error = client
+ .err()
+ .expect("a different client ID must be rejected");
+ assert!(is_authentication_required_error(&error));
+ assert!(
+ error
+ .to_string()
+ .contains("differs from stored credentials")
+ );
+ return Ok(());
+ }
+ let client = client?;
if refresh_mode == McpOAuthRefreshMode::Coordinated {
initialize_client_with_timeout(&client, Duration::from_secs(/*secs*/ 1)).await?;
diff --git a/codex-rs/rmcp-client/tests/streamable_http_oauth_store_pinning.rs b/codex-rs/rmcp-client/tests/streamable_http_oauth_store_pinning.rs
index 1656774650..abbd237692 100644
--- a/codex-rs/rmcp-client/tests/streamable_http_oauth_store_pinning.rs
+++ b/codex-rs/rmcp-client/tests/streamable_http_oauth_store_pinning.rs
@@ -197,6 +197,7 @@ async fn transport_provided_bearer_token_avoids_placeholder_headers_and_redirect
Some(StreamableHttpBearerToken::ProvidedByHttpClient),
/*http_headers*/ None,
/*env_http_headers*/ None,
+ /*oauth_config*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
Arc::new(http_client.clone()),