Keep MCP OAuth refresh alive after caller cancellation

This commit is contained in:
Steven Lee
2026-06-25 17:38:14 +00:00
parent 61a6e45dab
commit fe7595b0ad
2 changed files with 301 additions and 13 deletions
+209
View File
@@ -710,11 +710,15 @@ mod tests {
use std::sync::MutexGuard;
use std::sync::OnceLock;
use std::sync::PoisonError;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use tempfile::tempdir;
use tokio::sync::Mutex as TokioMutex;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_string_contains;
use wiremock::matchers::method;
use wiremock::matchers::path;
@@ -1081,6 +1085,143 @@ mod tests {
Ok(())
}
#[tokio::test]
async fn provider_refresh_timeout_permits_a_later_serialized_retry() -> Result<()> {
let _env = TempCodexHome::new();
let server = MockServer::start().await;
mount_oauth_metadata(&server).await;
let request_count = Arc::new(AtomicUsize::new(/*v*/ 0));
let request_count_for_response = Arc::clone(&request_count);
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_string_contains("grant_type=refresh_token"))
.and(body_string_contains("refresh_token=refresh-token"))
.respond_with(move |_request: &wiremock::Request| {
let response = ResponseTemplate::new(200).set_body_json(json!({
"access_token": "retried-access-token",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "retried-refresh-token",
"scope": "scope-a scope-b",
}));
if request_count_for_response.fetch_add(1, Ordering::SeqCst) == 0 {
response.set_delay(Duration::from_millis(500))
} else {
response
}
})
.expect(2)
.mount(&server)
.await;
let store = MockKeyringStore::default();
let initial_tokens = expired_sample_tokens(&format!("{}/mcp", server.uri()));
super::save_oauth_tokens_with_keyring_store(
&store,
&initial_tokens.server_name,
&initial_tokens,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)?;
let manager = authorization_manager_for(&initial_tokens).await?;
let persistor = OAuthPersistor::new(
initial_tokens.server_name.clone(),
initial_tokens.url.clone(),
manager,
ResolvedOAuthCredentialStore::Keyring(AuthKeyringBackendKind::Direct),
Some(initial_tokens.clone()),
);
let first_error = persistor
.refresh_if_needed_with_keyring_store_and_timeout(&store, Duration::from_millis(100))
.await
.expect_err("the first provider request should reach its explicit timeout");
assert!(first_error.to_string().contains("timed out after 100ms"));
persistor
.refresh_if_needed_with_keyring_store_and_timeout(&store, Duration::from_secs(1))
.await?;
let stored = super::load_oauth_tokens_with_source_and_keyring_store(
&store,
&initial_tokens.server_name,
&initial_tokens.url,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)?
.expect("the later retry should persist the rotated credentials");
assert_eq!(access_token(&stored.tokens), "retried-access-token");
assert_eq!(
refresh_token(&stored.tokens),
Some("retried-refresh-token".to_string())
);
assert_eq!(request_count.load(Ordering::SeqCst), 2);
server.verify().await;
Ok(())
}
#[tokio::test]
async fn caller_cancellation_does_not_cancel_refresh_and_persistence() -> Result<()> {
let _env = TempCodexHome::new();
let server = MockServer::start().await;
mount_oauth_metadata(&server).await;
let refresh_started = mount_refresh_response_with_signal(
&server,
"refresh-token",
"cancel-safe-access-token",
"cancel-safe-refresh-token",
Duration::from_millis(300),
)
.await;
let store = MockKeyringStore::default();
let initial_tokens = expired_sample_tokens(&format!("{}/mcp", server.uri()));
super::save_oauth_tokens_with_keyring_store(
&store,
&initial_tokens.server_name,
&initial_tokens,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)?;
let manager = authorization_manager_for(&initial_tokens).await?;
let persistor = OAuthPersistor::new(
initial_tokens.server_name.clone(),
initial_tokens.url.clone(),
manager,
ResolvedOAuthCredentialStore::Keyring(AuthKeyringBackendKind::Direct),
Some(initial_tokens.clone()),
);
let caller = tokio::spawn({
let persistor = persistor.clone();
let store = store.clone();
async move { persistor.refresh_if_needed_with_keyring_store(&store).await }
});
wait_for_signal(refresh_started).await?;
caller.abort();
let caller_error = caller
.await
.expect_err("the caller task should observe cancellation");
assert!(caller_error.is_cancelled());
tokio::time::sleep(Duration::from_millis(500)).await;
let stored = super::load_oauth_tokens_with_source_and_keyring_store(
&store,
&initial_tokens.server_name,
&initial_tokens.url,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)?
.expect("the independently owned refresh should still persist credentials");
assert_eq!(access_token(&stored.tokens), "cancel-safe-access-token");
assert_eq!(
refresh_token(&stored.tokens),
Some("cancel-safe-refresh-token".to_string())
);
server.verify().await;
Ok(())
}
#[test]
fn save_oauth_tokens_with_secrets_backend_falls_back_to_file_when_keyring_fails() -> Result<()>
{
@@ -1384,6 +1525,62 @@ mod tests {
Ok(Arc::new(TokioMutex::new(manager)))
}
async fn mount_oauth_metadata(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"authorization_endpoint": format!("{}/oauth/authorize", server.uri()),
"token_endpoint": format!("{}/oauth/token", server.uri()),
"scopes_supported": ["scope-a", "scope-b"],
})))
.mount(server)
.await;
}
async fn mount_refresh_response_with_signal(
server: &MockServer,
request_refresh_token: &str,
response_access_token: &str,
response_refresh_token: &str,
response_delay: Duration,
) -> mpsc::Receiver<()> {
let (tx, rx) = mpsc::channel();
let response_access_token = response_access_token.to_string();
let response_refresh_token = response_refresh_token.to_string();
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_string_contains("grant_type=refresh_token"))
.and(body_string_contains(format!(
"refresh_token={request_refresh_token}"
)))
.respond_with(move |_request: &wiremock::Request| {
let _ = tx.send(());
let access_token = response_access_token.clone();
let refresh_token = response_refresh_token.clone();
ResponseTemplate::new(200)
.set_delay(response_delay)
.set_body_json(json!({
"access_token": access_token,
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": refresh_token,
"scope": "scope-a scope-b",
}))
})
.expect(1)
.mount(server)
.await;
rx
}
async fn wait_for_signal(rx: mpsc::Receiver<()>) -> Result<()> {
tokio::task::spawn_blocking(move || {
rx.recv_timeout(Duration::from_secs(5))
.context("timed out waiting for refresh request")
})
.await?
}
#[expect(
clippy::await_holding_invalid_type,
reason = "AuthorizationManager async access must be serialized through its mutex"
@@ -1403,6 +1600,18 @@ mod tests {
})
}
fn access_token(tokens: &StoredOAuthTokens) -> &str {
tokens.token_response.0.access_token().secret()
}
fn refresh_token(tokens: &StoredOAuthTokens) -> Option<String> {
tokens
.token_response
.0
.refresh_token()
.map(|token| token.secret().to_string())
}
fn expired_sample_tokens(url: &str) -> StoredOAuthTokens {
let mut tokens = sample_tokens();
tokens.url = url.to_string();
+92 -13
View File
@@ -2,6 +2,7 @@
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
@@ -17,6 +18,7 @@ use rmcp::transport::auth::InMemoryCredentialStore;
use rmcp::transport::auth::StoredCredentials;
use tokio::sync::Mutex;
use tokio::time::timeout;
use tracing::debug;
use tracing::warn;
use super::ResolvedOAuthCredentialStore;
@@ -177,10 +179,6 @@ impl OAuthPersistor {
.await
}
#[expect(
clippy::await_holding_invalid_type,
reason = "AuthorizationManager async access must be serialized through its mutex"
)]
pub(super) async fn refresh_if_needed_with_keyring_store_and_timeout<
K: KeyringStore + Clone + 'static,
>(
@@ -197,12 +195,62 @@ impl OAuthPersistor {
return Ok(());
}
self.run_owned_refresh_transaction(keyring_store.clone(), refresh_request_timeout)
.await
}
async fn run_owned_refresh_transaction<K: KeyringStore + Clone + 'static>(
&self,
keyring_store: K,
refresh_request_timeout: Duration,
) -> Result<()> {
let persistor = self.clone();
let server_name = self.inner.server_name.clone();
// Once the provider may consume a rotating refresh token, dropping the caller's future
// must not also drop refresh plus persistence. Dropping this JoinHandle detaches the task,
// which continues under the credential lock until its explicit lock/provider bounds.
//
// A provider timeout deliberately leaves the outcome unknown, releases the lock, and
// permits a later serialized retry. Some providers accept the previous token during a
// grace period; otherwise that retry surfaces reauthorization. We accept that residual
// token-family-revocation risk rather than holding the lock indefinitely.
tokio::spawn(async move {
persistor
.refresh_transaction(&keyring_store, refresh_request_timeout)
.await
})
.await
.with_context(|| format!("OAuth refresh task failed for server {server_name}"))?
}
#[expect(
clippy::await_holding_invalid_type,
reason = "AuthorizationManager async access must be serialized through its mutex"
)]
#[tracing::instrument(
level = "debug",
skip_all,
fields(server_name = %self.inner.server_name),
err
)]
async fn refresh_transaction<K: KeyringStore + Clone + 'static>(
&self,
keyring_store: &K,
refresh_request_timeout: Duration,
) -> Result<()> {
let transaction_started_at = Instant::now();
let lock_started_at = Instant::now();
debug!("waiting for the MCP OAuth credential transaction lock");
let snapshot = {
let guard = self.inner.last_credentials.lock().await;
guard.clone()
};
let key = compute_store_key(&self.inner.server_name, &self.inner.url)?;
let _lock = RefreshCredentialLock::acquire(&key).await?;
debug!(
lock_wait_ms = lock_started_at.elapsed().as_millis(),
"acquired the MCP OAuth credential transaction lock"
);
// The refresh transaction must stay on the store that supplied its snapshot. Falling back
// here could replay an older rotating refresh token from the other store. We assume store
// availability is stable for this client lifecycle and surface violations of that
@@ -253,26 +301,57 @@ impl OAuthPersistor {
{
let manager = self.inner.authorization_manager.clone();
let guard = manager.lock().await;
let provider_started_at = Instant::now();
debug!(
timeout_ms = refresh_request_timeout.as_millis(),
"requesting refreshed MCP OAuth credentials from the provider"
);
match timeout(refresh_request_timeout, guard.refresh_token()).await {
Ok(result) => {
result.with_context(|| {
Ok(Ok(_token_response)) => {
debug!(
provider_elapsed_ms = provider_started_at.elapsed().as_millis(),
"received refreshed MCP OAuth credentials from the provider"
);
}
Ok(Err(error)) => {
warn!(
provider_elapsed_ms = provider_started_at.elapsed().as_millis(),
error = %error,
"MCP OAuth provider refresh failed"
);
return Err(error).with_context(|| {
format!(
"failed to refresh OAuth tokens for server {}",
self.inner.server_name
)
})?;
});
}
Err(_) => {
warn!(
provider_elapsed_ms = provider_started_at.elapsed().as_millis(),
timeout_ms = refresh_request_timeout.as_millis(),
"MCP OAuth provider refresh timed out; the outcome is unknown and a later serialized retry is permitted"
);
anyhow::bail!(
"timed out after {refresh_request_timeout:?} refreshing OAuth tokens for server {}",
self.inner.server_name
);
}
Err(_) => anyhow::bail!(
"timed out after {refresh_request_timeout:?} refreshing OAuth tokens for server {}",
self.inner.server_name
),
}
}
// Once the provider returns a rotated token, persistence must finish before the credential
// lock is released. In particular, caller startup deadlines must not cancel this step.
self.persist_if_needed_with_keyring_store(keyring_store)
.await
let result = self
.persist_if_needed_with_keyring_store(keyring_store)
.await;
if result.is_ok() {
debug!(
transaction_elapsed_ms = transaction_started_at.elapsed().as_millis(),
"completed the MCP OAuth refresh transaction"
);
}
result
}
async fn adopt_credentials(&self, tokens: StoredOAuthTokens) -> Result<()> {