fix(rmcp): scope invalid_token recovery to OAuth

This commit is contained in:
Adam Perry
2026-06-05 05:22:59 +00:00
parent 14fd2db95b
commit 2cc6e66453
9 changed files with 241 additions and 71 deletions
@@ -40,8 +40,8 @@ use sse_stream::SseStream;
mod www_authenticate;
use self::www_authenticate::has_bearer_invalid_token_challenge;
use self::www_authenticate::insufficient_scope_challenge;
pub(crate) use self::www_authenticate::is_bearer_invalid_token_challenge;
const EVENT_STREAM_MIME_TYPE: &str = "text/event-stream";
const JSON_MIME_TYPE: &str = "application/json";
@@ -59,8 +59,6 @@ pub(crate) struct StreamableHttpClientAdapter {
pub(crate) enum StreamableHttpClientAdapterError {
#[error("streamable HTTP session expired with 404 Not Found")]
SessionExpired404,
#[error("MCP OAuth access token was rejected")]
OAuthInvalidToken,
#[error(transparent)]
HttpRequest(#[from] ExecServerError),
#[error("invalid HTTP header: {0}")]
@@ -161,13 +159,6 @@ impl StreamableHttpClient for StreamableHttpClientAdapter {
StreamableHttpClientAdapterError::SessionExpired404,
));
}
if response.status == StatusCode::UNAUTHORIZED.as_u16()
&& has_bearer_invalid_token_challenge(&response.headers)
{
return Err(StreamableHttpError::Client(
StreamableHttpClientAdapterError::OAuthInvalidToken,
));
}
if response.status == StatusCode::UNAUTHORIZED.as_u16()
&& let Some(header) =
response_header(&response.headers, reqwest::header::WWW_AUTHENTICATE)
@@ -84,13 +84,10 @@ pub(super) fn insufficient_scope_challenge(
})
}
/// Returns whether any `WWW-Authenticate` response header field value contains
/// a Bearer challenge with an `invalid_token` error.
pub(super) fn has_bearer_invalid_token_challenge(headers: &[HttpHeader]) -> bool {
headers
.iter()
.filter(|header| header.name.eq_ignore_ascii_case(WWW_AUTHENTICATE.as_str()))
.any(|header| parse_bearer_challenge(&header.value, "invalid_token").is_some())
/// Returns whether a `WWW-Authenticate` field value contains a Bearer
/// challenge with an `invalid_token` error.
pub(crate) fn is_bearer_invalid_token_challenge(header: &str) -> bool {
parse_bearer_challenge(header, "invalid_token").is_some()
}
/// Parses a Bearer `WWW-Authenticate` challenge with an `insufficient_scope`
@@ -3,8 +3,8 @@ use pretty_assertions::assert_eq;
use super::BearerInsufficientScope;
use super::InsufficientScopeChallenge;
use super::has_bearer_invalid_token_challenge;
use super::insufficient_scope_challenge;
use super::is_bearer_invalid_token_challenge;
use super::parse_bearer_insufficient_scope;
#[test]
@@ -126,21 +126,15 @@ fn selects_bearer_challenge_from_a_later_www_authenticate_field_value() {
#[test]
fn detects_only_bearer_invalid_token_challenges() {
let matching = vec![HttpHeader {
name: "WWW-Authenticate".to_string(),
value: r#"Basic realm="example", Bearer error="invalid_token""#.to_string(),
}];
assert!(has_bearer_invalid_token_challenge(&matching));
assert!(is_bearer_invalid_token_challenge(
r#"Basic realm="example", Bearer error="invalid_token""#
));
for value in [
r#"Bearer realm="example""#,
r#"Bearer error="insufficient_scope""#,
r#"Basic error="invalid_token""#,
] {
let headers = vec![HttpHeader {
name: "www-authenticate".to_string(),
value: value.to_string(),
}];
assert!(!has_bearer_invalid_token_challenge(&headers), "{value}");
assert!(!is_bearer_invalid_token_challenge(value), "{value}");
}
}
+1
View File
@@ -18,6 +18,7 @@ pub use auth_status::discover_streamable_http_oauth;
pub use auth_status::supports_oauth_login;
pub use codex_protocol::protocol::McpAuthStatus;
pub use in_process_transport::InProcessTransportFactory;
pub use oauth::OAUTH_REFRESH_REAUTHENTICATION_REQUIRED_ERROR;
pub use oauth::StoredOAuthTokens;
pub use oauth::WrappedOAuthTokenResponse;
pub use oauth::delete_oauth_tokens;
+21 -6
View File
@@ -19,6 +19,7 @@
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use anyhow::anyhow;
use codex_config::types::OAuthCredentialsStoreMode;
use oauth2::AccessToken;
use oauth2::RefreshToken;
@@ -45,6 +46,7 @@ use tracing::warn;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use rmcp::transport::auth::AuthError;
use rmcp::transport::auth::AuthorizationManager;
use tokio::sync::Mutex;
@@ -52,6 +54,9 @@ use codex_utils_home_dir::find_codex_home;
const KEYRING_SERVICE: &str = "Codex MCP Credentials";
const REFRESH_SKEW_MILLIS: u64 = 30_000;
const MISSING_REFRESH_TOKEN_ERROR: &str = "No refresh token available";
pub const OAUTH_REFRESH_REAUTHENTICATION_REQUIRED_ERROR: &str =
"OAuth refresh token was rejected; reauthentication required";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StoredOAuthTokens {
@@ -370,18 +375,28 @@ impl OAuthPersistor {
{
let manager = self.inner.authorization_manager.clone();
let guard = manager.lock().await;
guard.refresh_token().await.with_context(|| {
format!(
"failed to refresh OAuth tokens for server {}",
self.inner.server_name
)
})?;
if let Err(error) = guard.refresh_token().await {
return Err(refresh_error(error, &self.inner.server_name));
}
}
self.persist_if_needed().await
}
}
fn refresh_error(error: AuthError, server_name: &str) -> Error {
match error {
AuthError::TokenRefreshFailed(message)
if message == MISSING_REFRESH_TOKEN_ERROR || message.contains("invalid_grant") =>
{
anyhow!(OAUTH_REFRESH_REAUTHENTICATION_REQUIRED_ERROR)
}
error => Error::new(error).context(format!(
"failed to refresh OAuth tokens for server {server_name}"
)),
}
}
const FALLBACK_FILENAME: &str = ".credentials.json";
const MCP_SERVER_TYPE: &str = "http";
@@ -4,6 +4,7 @@ use rmcp::transport::DynamicTransportError;
use rmcp::transport::streamable_http_client::StreamableHttpError;
use crate::http_client_adapter::StreamableHttpClientAdapterError;
use crate::http_client_adapter::is_bearer_invalid_token_challenge;
#[derive(Debug, thiserror::Error)]
#[error("MCP OAuth access token was rejected; credentials refreshed, retry the request")]
@@ -27,7 +28,8 @@ pub(crate) fn rejected_transport(error: &DynamicTransportError) -> bool {
.is_some_and(|error| {
matches!(
error,
StreamableHttpError::Client(StreamableHttpClientAdapterError::OAuthInvalidToken)
StreamableHttpError::AuthRequired(auth)
if is_bearer_invalid_token_challenge(&auth.www_authenticate_header)
)
})
}
+10 -10
View File
@@ -9,7 +9,6 @@ use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_api::SharedAuthProvider;
@@ -419,13 +418,14 @@ impl RmcpClient {
)
.await
{
Err(error) if oauth_invalid_token::rejected_initialize_request(&error) => {
Err(error) => {
let Some(oauth_persistor) = startup_oauth_persistor else {
return Err(error);
};
oauth_persistor.force_refresh().await.with_context(
|| "failed to refresh MCP OAuth access token after invalid_token",
)?;
if !oauth_invalid_token::rejected_initialize_request(&error) {
return Err(error);
}
oauth_persistor.force_refresh().await?;
let retry_transport =
Self::create_pending_transport(&self.transport_recipe).await?;
Self::connect_pending_transport(
@@ -644,16 +644,16 @@ impl RmcpClient {
.await;
let result = match result {
Ok(result) => result,
Err(error) if Self::is_invalid_token_operation_error(&error) => {
Err(error) => {
let Some(oauth_persistor) = self.oauth_persistor().await else {
return Err(error);
};
oauth_persistor.force_refresh().await.with_context(
|| "failed to refresh MCP OAuth access token after invalid_token",
)?;
if !Self::is_invalid_token_operation_error(&error) {
return Err(error);
}
oauth_persistor.force_refresh().await?;
return Err(oauth_invalid_token::RetryRequired.into());
}
Err(error) => return Err(error),
};
self.persist_oauth_tokens().await;
Ok(result)
@@ -1,11 +1,13 @@
mod streamable_http_test_support;
use std::fs;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::Environment;
use codex_rmcp_client::OAUTH_REFRESH_REAUTHENTICATION_REQUIRED_ERROR;
use codex_rmcp_client::RmcpClient;
use codex_rmcp_client::StoredOAuthTokens;
use codex_rmcp_client::WrappedOAuthTokenResponse;
@@ -38,6 +40,7 @@ const EXPIRED_ACCESS_TOKEN: &str = "expired-access-token";
const REVOKED_ACCESS_TOKEN: &str = "revoked-access-token";
const REFRESH_TOKEN: &str = "valid-refresh-token";
const REFRESHED_ACCESS_TOKEN: &str = "refreshed-access-token";
const ROTATED_REFRESH_TOKEN: &str = "rotated-refresh-token";
const CHILD_SERVER_URL_ENV: &str = "MCP_TEST_OAUTH_STARTUP_SERVER_URL";
const CHILD_SCENARIO_ENV: &str = "MCP_TEST_OAUTH_STARTUP_SCENARIO";
const INVALID_TOKEN_CHALLENGE: &str = r#"Bearer error="invalid_token""#;
@@ -46,7 +49,10 @@ const RETRY_REQUIRED_ERROR: &str =
const SCENARIO_INITIALIZE_SUCCEEDS: &str = "initialize_succeeds";
const SCENARIO_INITIALIZE_FAILS: &str = "initialize_fails";
const SCENARIO_INITIALIZE_REAUTH_REQUIRED: &str = "initialize_reauth_required";
const SCENARIO_INITIALIZE_TIMES_OUT: &str = "initialize_times_out";
const SCENARIO_TOOL_CALL_FAILS: &str = "tool_call_fails";
const SCENARIO_TOOL_CALL_REAUTH_REQUIRED: &str = "tool_call_reauth_required";
const SCENARIO_TOOL_CALL_RECOVERS: &str = "tool_call_recovers";
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
@@ -97,7 +103,7 @@ async fn initialize_invalid_token_retry_uses_original_timeout() -> anyhow::Resul
mount_invalid_token_initialize(&server, REVOKED_ACCESS_TOKEN).await;
mount_refresh(
&server,
successful_refresh_response().set_delay(Duration::from_secs(1)),
successful_refresh_response(REFRESH_TOKEN).set_delay(Duration::from_secs(1)),
)
.await;
Mock::given(method("POST"))
@@ -141,30 +147,26 @@ async fn initialize_generic_401_does_not_refresh_or_retry() -> anyhow::Result<()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn initialized_notification_invalid_token_does_not_refresh_or_retry() -> anyhow::Result<()> {
async fn initialize_invalid_token_rejected_refresh_requires_reauthentication() -> anyhow::Result<()>
{
let server = MockServer::start().await;
mount_oauth_metadata(&server).await;
mount_unexpected_refresh(&server).await;
mount_invalid_token_initialize(&server, REVOKED_ACCESS_TOKEN).await;
Mock::given(method("POST"))
.and(path("/mcp"))
.and(header(
"authorization",
format!("Bearer {REVOKED_ACCESS_TOKEN}"),
))
.respond_with(|request: &Request| {
let body = request_body(request);
match body.get("method").and_then(Value::as_str) {
Some("initialize") => initialize_response(&body),
Some("notifications/initialized") => ResponseTemplate::new(401)
.insert_header("www-authenticate", INVALID_TOKEN_CHALLENGE),
method => unexpected_method(method),
}
})
.expect(2)
.and(path("/oauth/token"))
.and(body_string_contains("grant_type=refresh_token"))
.and(body_string_contains(format!(
"refresh_token={REFRESH_TOKEN}"
)))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
"error": "invalid_grant",
"error_description": "refresh token revoked",
})))
.expect(1)
.mount(&server)
.await;
run_scenario_child(&server, SCENARIO_INITIALIZE_FAILS).await?;
run_scenario_child(&server, SCENARIO_INITIALIZE_REAUTH_REQUIRED).await?;
server.verify().await;
Ok(())
}
@@ -174,7 +176,7 @@ async fn tool_call_invalid_token_refreshes_without_replay_and_next_call_succeeds
-> anyhow::Result<()> {
let server = MockServer::start().await;
mount_oauth_metadata(&server).await;
mount_successful_refresh(&server).await;
mount_successful_refresh_with_token(&server, ROTATED_REFRESH_TOKEN).await;
Mock::given(method("POST"))
.and(path("/mcp"))
.and(header(
@@ -215,7 +217,34 @@ async fn tool_call_invalid_token_refreshes_without_replay_and_next_call_succeeds
.mount(&server)
.await;
run_scenario_child(&server, SCENARIO_TOOL_CALL_RECOVERS).await?;
let codex_home = TempDir::new()?;
run_scenario_child_in_home(&server, SCENARIO_TOOL_CALL_RECOVERS, &codex_home).await?;
assert_persisted_refresh_token(&codex_home, ROTATED_REFRESH_TOKEN)?;
server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn tool_call_invalid_token_without_refresh_token_requires_reauthentication()
-> anyhow::Result<()> {
let server = MockServer::start().await;
mount_oauth_metadata(&server).await;
mount_unexpected_refresh(&server).await;
mount_tool_call_failure(&server, INVALID_TOKEN_CHALLENGE).await;
run_scenario_child(&server, SCENARIO_TOOL_CALL_REAUTH_REQUIRED).await?;
server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn tool_call_generic_401_does_not_refresh_or_replay() -> anyhow::Result<()> {
let server = MockServer::start().await;
mount_oauth_metadata(&server).await;
mount_unexpected_refresh(&server).await;
mount_tool_call_failure(&server, r#"Bearer realm="example""#).await;
run_scenario_child(&server, SCENARIO_TOOL_CALL_FAILS).await?;
server.verify().await;
Ok(())
}
@@ -236,7 +265,15 @@ async fn oauth_startup_child() -> anyhow::Result<()> {
async fn oauth_invalid_token_child() -> anyhow::Result<()> {
let server_url = std::env::var(CHILD_SERVER_URL_ENV)?;
let scenario = std::env::var(CHILD_SCENARIO_ENV)?;
save_test_oauth_tokens(&server_url, REVOKED_ACCESS_TOKEN, future_expiry())?;
if scenario == SCENARIO_TOOL_CALL_REAUTH_REQUIRED {
save_test_oauth_tokens_without_refresh_token(
&server_url,
REVOKED_ACCESS_TOKEN,
future_expiry(),
)?;
} else {
save_test_oauth_tokens(&server_url, REVOKED_ACCESS_TOKEN, future_expiry())?;
}
let client = new_oauth_client(&server_url).await?;
match scenario.as_str() {
@@ -244,6 +281,13 @@ async fn oauth_invalid_token_child() -> anyhow::Result<()> {
SCENARIO_INITIALIZE_FAILS => {
initialize_client(&client).await.unwrap_err();
}
SCENARIO_INITIALIZE_REAUTH_REQUIRED => {
let error = initialize_client(&client).await.unwrap_err();
assert_eq!(
error.to_string(),
OAUTH_REFRESH_REAUTHENTICATION_REQUIRED_ERROR
);
}
SCENARIO_INITIALIZE_TIMES_OUT => {
let error = initialize_client_with_timeout(&client, Duration::from_millis(500))
.await
@@ -253,6 +297,22 @@ async fn oauth_invalid_token_child() -> anyhow::Result<()> {
"timed out handshaking with MCP server after 500ms"
);
}
SCENARIO_TOOL_CALL_FAILS => {
initialize_client(&client).await?;
call_echo_tool(&client, "must not be replayed")
.await
.unwrap_err();
}
SCENARIO_TOOL_CALL_REAUTH_REQUIRED => {
initialize_client(&client).await?;
let error = call_echo_tool(&client, "must not be replayed")
.await
.unwrap_err();
assert_eq!(
error.to_string(),
OAUTH_REFRESH_REAUTHENTICATION_REQUIRED_ERROR
);
}
SCENARIO_TOOL_CALL_RECOVERS => {
initialize_client(&client).await?;
let error = call_echo_tool(&client, "must not be replayed")
@@ -270,6 +330,14 @@ async fn oauth_invalid_token_child() -> anyhow::Result<()> {
async fn run_scenario_child(server: &MockServer, scenario: &str) -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
run_scenario_child_in_home(server, scenario, &codex_home).await
}
async fn run_scenario_child_in_home(
server: &MockServer,
scenario: &str,
codex_home: &TempDir,
) -> anyhow::Result<()> {
let server_url = format!("{}/mcp", server.uri());
let status = Command::new(std::env::current_exe()?)
.args([
@@ -304,7 +372,11 @@ async fn mount_oauth_metadata(server: &MockServer) {
}
async fn mount_successful_refresh(server: &MockServer) {
mount_refresh(server, successful_refresh_response()).await;
mount_successful_refresh_with_token(server, REFRESH_TOKEN).await;
}
async fn mount_successful_refresh_with_token(server: &MockServer, refresh_token: &str) {
mount_refresh(server, successful_refresh_response(refresh_token)).await;
}
async fn mount_refresh(server: &MockServer, response: ResponseTemplate) {
@@ -320,12 +392,12 @@ async fn mount_refresh(server: &MockServer, response: ResponseTemplate) {
.await;
}
fn successful_refresh_response() -> ResponseTemplate {
fn successful_refresh_response(refresh_token: &str) -> ResponseTemplate {
ResponseTemplate::new(200).set_body_json(json!({
"access_token": REFRESHED_ACCESS_TOKEN,
"token_type": "Bearer",
"expires_in": 7200,
"refresh_token": REFRESH_TOKEN,
"refresh_token": refresh_token,
}))
}
@@ -350,6 +422,29 @@ async fn mount_invalid_token_initialize(server: &MockServer, access_token: &str)
.await;
}
async fn mount_tool_call_failure(server: &MockServer, challenge: &'static str) {
Mock::given(method("POST"))
.and(path("/mcp"))
.and(header(
"authorization",
format!("Bearer {REVOKED_ACCESS_TOKEN}"),
))
.respond_with(move |request: &Request| {
let body = request_body(request);
match body.get("method").and_then(Value::as_str) {
Some("initialize") => initialize_response(&body),
Some("notifications/initialized") => ResponseTemplate::new(202),
Some("tools/call") => {
ResponseTemplate::new(401).insert_header("www-authenticate", challenge)
}
method => unexpected_method(method),
}
})
.expect(3)
.mount(server)
.await;
}
async fn mount_successful_initialize(server: &MockServer, access_token: &str) {
Mock::given(method("POST"))
.and(path("/mcp"))
@@ -413,13 +508,40 @@ fn save_test_oauth_tokens(
server_url: &str,
access_token: &str,
expires_at: u64,
) -> anyhow::Result<()> {
save_test_oauth_tokens_with_refresh_token(
server_url,
access_token,
expires_at,
/*refresh_token*/ Some(REFRESH_TOKEN),
)
}
fn save_test_oauth_tokens_without_refresh_token(
server_url: &str,
access_token: &str,
expires_at: u64,
) -> anyhow::Result<()> {
save_test_oauth_tokens_with_refresh_token(
server_url,
access_token,
expires_at,
/*refresh_token*/ None,
)
}
fn save_test_oauth_tokens_with_refresh_token(
server_url: &str,
access_token: &str,
expires_at: u64,
refresh_token: Option<&str>,
) -> anyhow::Result<()> {
let mut response = OAuthTokenResponse::new(
AccessToken::new(access_token.to_string()),
BasicTokenType::Bearer,
VendorExtraTokenFields::default(),
);
response.set_refresh_token(Some(RefreshToken::new(REFRESH_TOKEN.to_string())));
response.set_refresh_token(refresh_token.map(|token| RefreshToken::new(token.to_string())));
response.set_expires_in(Some(&Duration::from_secs(7200)));
let tokens = StoredOAuthTokens {
server_name: SERVER_NAME.to_string(),
@@ -432,6 +554,28 @@ fn save_test_oauth_tokens(
Ok(())
}
fn assert_persisted_refresh_token(
codex_home: &TempDir,
expected_refresh_token: &str,
) -> anyhow::Result<()> {
let credentials: Value = serde_json::from_str(&fs::read_to_string(
codex_home.path().join(".credentials.json"),
)?)?;
let entries = credentials
.as_object()
.ok_or_else(|| anyhow::anyhow!("persisted OAuth credentials must be an object"))?;
assert_eq!(entries.len(), 1);
let entry = entries
.values()
.next()
.ok_or_else(|| anyhow::anyhow!("persisted OAuth credentials must contain one entry"))?;
assert_eq!(
entry.get("refresh_token"),
Some(&json!(expected_refresh_token))
);
Ok(())
}
async fn new_oauth_client(server_url: &str) -> anyhow::Result<RmcpClient> {
RmcpClient::new_streamable_http_client(
SERVER_NAME,
@@ -57,6 +57,32 @@ async fn streamable_http_401_does_not_trigger_recovery() -> anyhow::Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn static_bearer_invalid_token_retains_auth_required_semantics() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
arm_session_post_failure(
&base_url,
/*status*/ 401,
/*remaining*/ 1,
/*www_authenticate_headers*/ &[r#"Bearer error="invalid_token""#],
)
.await?;
let error = call_echo_tool(&client, "unauthorized").await.unwrap_err();
assert!(
error
.chain()
.any(|source| source.to_string().ends_with("Auth required")),
"static bearer invalid_token should remain AuthRequired: {error:#}"
);
let subsequent = call_echo_tool(&client, "subsequent").await?;
assert_eq!(subsequent, expected_echo_result("subsequent"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_403_scope_challenge_returns_insufficient_scope() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;