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

## Why

MCP OAuth configuration supported a pre-registered client ID but could not supply a client secret for token exchange or refresh.

## What changed

- Add `oauth.client_secret` and `codex mcp add --oauth-client-secret`, requiring a nonempty secret and client ID. Persist the secret in server configuration and accept `clientSecret` in plugin configuration.
- Pass configured credentials through CLI, app-server, and plugin login flows and token refresh. Require a new login when a configured confidential client's ID differs from stored credentials.
- Redact secrets in debug output and keep them out of authorization URLs and persisted OAuth token records.
- Invalidate cached OAuth connections when the configured client ID or secret changes.

## Testing

Add coverage for configuration validation and round trips, CLI argument redaction and subsequent login, app-server login, connection invalidation, and refresh with `client_secret_basic` and `client_secret_post` in both refresh modes. Verify secret exclusion from token records and reject mismatched client IDs before contacting the provider.

GitOrigin-RevId: 85bb0e410e9e68e6cd68eb6359badfc7eac78147
This commit is contained in:
willwang-openai
2026-09-24 17:26:18 +00:00
committed by copyberry
parent b3ea9fa632
commit 83b56bc5ad
38 changed files with 912 additions and 127 deletions
+1
View File
@@ -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 }
+87 -53
View File
@@ -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 (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,
McpOAuthClientRegistration::Auto,
None,
)
}
AddMcpTransportArgs {
streamable_http:
Some(AddMcpStreamableHttpArgs {
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),
+62
View File
@@ -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"));
}
}
+4 -3
View File
@@ -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,
+34
View File
@@ -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()?;
+157 -36
View File
@@ -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"))