diff --git a/codex-rs/rmcp-client/src/oauth.rs b/codex-rs/rmcp-client/src/oauth.rs index c348460795..bf906b2564 100644 --- a/codex-rs/rmcp-client/src/oauth.rs +++ b/codex-rs/rmcp-client/src/oauth.rs @@ -35,6 +35,7 @@ use sha2::Digest; use sha2::Sha256; use std::collections::BTreeMap; use std::fs; +use std::fs::OpenOptions; use std::io::ErrorKind; use std::path::PathBuf; use std::sync::Arc; @@ -46,7 +47,11 @@ use tracing::warn; use codex_keyring_store::DefaultKeyringStore; use codex_keyring_store::KeyringStore; use rmcp::transport::auth::AuthorizationManager; +use rmcp::transport::auth::CredentialStore; +use rmcp::transport::auth::InMemoryCredentialStore; +use rmcp::transport::auth::StoredCredentials; use tokio::sync::Mutex; +use tokio::sync::Semaphore; use codex_utils_home_dir::find_codex_home; @@ -162,6 +167,15 @@ pub fn save_oauth_tokens( server_name: &str, tokens: &StoredOAuthTokens, store_mode: OAuthCredentialsStoreMode, +) -> Result<()> { + let _lock = acquire_oauth_server_lock(server_name, &tokens.url)?; + save_oauth_tokens_locked(server_name, tokens, store_mode) +} + +fn save_oauth_tokens_locked( + server_name: &str, + tokens: &StoredOAuthTokens, + store_mode: OAuthCredentialsStoreMode, ) -> Result<()> { let keyring_store = DefaultKeyringStore; match store_mode { @@ -266,6 +280,7 @@ struct OAuthPersistorInner { authorization_manager: Arc>, store_mode: OAuthCredentialsStoreMode, last_credentials: Mutex>, + update_lock: Semaphore, } impl OAuthPersistor { @@ -283,17 +298,23 @@ impl OAuthPersistor { authorization_manager, store_mode, last_credentials: Mutex::new(initial_credentials), + update_lock: Semaphore::new(1), }), } } /// Persists the latest stored credentials if they have changed. /// Deletes the credentials if they are no longer present. + pub(crate) async fn persist_if_needed(&self) -> Result<()> { + let _permit = self.inner.update_lock.acquire().await?; + self.persist_if_needed_locked().await + } + #[expect( clippy::await_holding_invalid_type, - reason = "AuthorizationManager async access must be serialized through its mutex" + reason = "AuthorizationManager async access and persisted credential comparison must be serialized" )] - pub(crate) async fn persist_if_needed(&self) -> Result<()> { + async fn persist_if_needed_locked(&self) -> Result<()> { let (client_id, maybe_credentials) = { let manager = self.inner.authorization_manager.clone(); let guard = manager.lock().await; @@ -302,7 +323,7 @@ impl OAuthPersistor { match maybe_credentials { Some(credentials) => { - let mut last_credentials = self.inner.last_credentials.lock().await; + let last_credentials = self.inner.last_credentials.lock().await.clone(); let new_token_response = WrappedOAuthTokenResponse(credentials.clone()); let same_token = last_credentials .as_ref() @@ -320,10 +341,31 @@ impl OAuthPersistor { token_response: new_token_response, expires_at, }; - if last_credentials.as_ref() != Some(&stored) { - save_oauth_tokens(&self.inner.server_name, &stored, self.inner.store_mode)?; - *last_credentials = Some(stored); + if last_credentials + .as_ref() + .is_some_and(|previous| same_persisted_generation(previous, &stored)) + { + return Ok(()); } + + let _server_lock = + acquire_oauth_server_lock_async(&self.inner.server_name, &self.inner.url) + .await?; + if let Some(persisted) = load_oauth_tokens( + &self.inner.server_name, + &self.inner.url, + self.inner.store_mode, + )? && !last_credentials + .as_ref() + .is_some_and(|previous| same_persisted_generation(previous, &persisted)) + { + self.replace_manager_credentials(&persisted).await?; + *self.inner.last_credentials.lock().await = Some(persisted); + return Ok(()); + } + + save_oauth_tokens_locked(&self.inner.server_name, &stored, self.inner.store_mode)?; + *self.inner.last_credentials.lock().await = Some(stored); } None => { let mut last_serialized = self.inner.last_credentials.lock().await; @@ -347,9 +389,12 @@ impl OAuthPersistor { #[expect( clippy::await_holding_invalid_type, - reason = "AuthorizationManager async access must be serialized through its mutex" + reason = "AuthorizationManager async access and persisted credential adoption must be serialized" )] pub(crate) async fn refresh_if_needed(&self) -> Result<()> { + let _permit = self.inner.update_lock.acquire().await?; + self.adopt_persisted_credentials_if_changed().await?; + let expires_at = { let guard = self.inner.last_credentials.lock().await; guard.as_ref().and_then(|tokens| tokens.expires_at) @@ -370,7 +415,109 @@ impl OAuthPersistor { })?; } - self.persist_if_needed().await + self.persist_if_needed_locked().await + } + + async fn adopt_persisted_credentials_if_changed(&self) -> Result<()> { + let _server_lock = + acquire_oauth_server_lock_async(&self.inner.server_name, &self.inner.url).await?; + let Some(persisted) = load_oauth_tokens( + &self.inner.server_name, + &self.inner.url, + self.inner.store_mode, + )? + else { + return Ok(()); + }; + + let last_credentials = self.inner.last_credentials.lock().await.clone(); + if last_credentials + .as_ref() + .is_some_and(|previous| same_persisted_generation(previous, &persisted)) + { + return Ok(()); + } + + self.replace_manager_credentials(&persisted).await?; + *self.inner.last_credentials.lock().await = Some(persisted); + Ok(()) + } + + async fn replace_manager_credentials(&self, tokens: &StoredOAuthTokens) -> Result<()> { + let token_response = tokens.token_response.0.clone(); + let store = InMemoryCredentialStore::new(); + store + .save(StoredCredentials::new( + tokens.client_id.clone(), + Some(token_response.clone()), + token_response + .scopes() + .map(|scopes| scopes.iter().map(|scope| scope.to_string()).collect()) + .unwrap_or_default(), + Some( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_else(|_| Duration::from_secs(0)) + .as_secs(), + ), + )) + .await?; + + let manager = self.inner.authorization_manager.clone(); + let mut guard = manager.lock().await; + guard.configure_client_id(&tokens.client_id)?; + guard.set_credential_store(store); + Ok(()) + } +} + +struct OAuthServerLock { + _file: fs::File, +} + +fn acquire_oauth_server_lock(server_name: &str, url: &str) -> Result { + let digest = sha_256_prefix(&Value::String(format!("{server_name}\n{url}")))?; + let path = find_codex_home()?.join(format!(".mcp-oauth-{digest}.lock")); + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&path) + .with_context(|| format!("failed to open OAuth credential lock at {}", path.display()))?; + file.lock() + .with_context(|| format!("failed to lock OAuth credentials at {}", path.display()))?; + Ok(OAuthServerLock { _file: file }) +} + +async fn acquire_oauth_server_lock_async(server_name: &str, url: &str) -> Result { + let server_name = server_name.to_string(); + let url = url.to_string(); + tokio::task::spawn_blocking(move || acquire_oauth_server_lock(&server_name, &url)) + .await + .context("OAuth credential lock task failed")? +} + +fn same_persisted_generation(left: &StoredOAuthTokens, right: &StoredOAuthTokens) -> bool { + if left.server_name != right.server_name + || left.url != right.url + || left.client_id != right.client_id + || left.expires_at != right.expires_at + { + return false; + } + + let normalize = |response: &WrappedOAuthTokenResponse| { + let mut value = serde_json::to_value(response).ok()?; + value.as_object_mut()?.remove("expires_in"); + Some(value) + }; + match ( + normalize(&left.token_response), + normalize(&right.token_response), + ) { + (Some(left), Some(right)) => left == right, + _ => false, } } 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 6309f2a8cb..cc7c43907d 100644 --- a/codex-rs/rmcp-client/tests/streamable_http_oauth_startup.rs +++ b/codex-rs/rmcp-client/tests/streamable_http_oauth_startup.rs @@ -1,8 +1,5 @@ mod streamable_http_test_support; -use std::sync::Arc; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; use std::time::Duration; use std::time::SystemTime; use std::time::UNIX_EPOCH; @@ -16,7 +13,6 @@ use codex_rmcp_client::save_oauth_tokens; use oauth2::AccessToken; use oauth2::RefreshToken; use oauth2::basic::BasicTokenType; -use pretty_assertions::assert_eq; use rmcp::transport::auth::OAuthTokenResponse; use rmcp::transport::auth::VendorExtraTokenFields; use serde_json::Value; @@ -46,7 +42,6 @@ const EXTERNAL_ACCESS_TOKEN: &str = "external-access-token"; const EXTERNAL_REFRESH_TOKEN: &str = "external-refresh-token"; const STALE_REFRESHED_ACCESS_TOKEN: &str = "stale-refreshed-access-token"; const STALE_ROTATED_REFRESH_TOKEN: &str = "stale-rotated-refresh-token"; -const REFRESH_SKEW: Duration = Duration::from_secs(30); #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn refreshes_expired_persisted_token_before_initialize() -> anyhow::Result<()> { @@ -169,7 +164,7 @@ async fn oauth_startup_child() -> anyhow::Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] -async fn running_client_keeps_and_can_persist_over_external_oauth_update() -> anyhow::Result<()> { +async fn running_client_adopts_external_oauth_update_before_next_operation() -> anyhow::Result<()> { let server = MockServer::start().await; Mock::given(method("GET")) .and(path("/.well-known/oauth-authorization-server/mcp")) @@ -181,77 +176,56 @@ async fn running_client_keeps_and_can_persist_over_external_oauth_update() -> an .expect(1) .mount(&server) .await; - Mock::given(method("POST")) - .and(path("/oauth/token")) - .and(body_string_contains("grant_type=refresh_token")) - .and(body_string_contains(format!( - "refresh_token={OLD_REFRESH_TOKEN}" - ))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "access_token": STALE_REFRESHED_ACCESS_TOKEN, - "token_type": "Bearer", - "expires_in": 7200, - "refresh_token": STALE_ROTATED_REFRESH_TOKEN, - }))) - .expect(1) - .mount(&server) - .await; - let tool_call_count = Arc::new(AtomicUsize::new(0)); Mock::given(method("POST")) .and(path("/mcp")) - .respond_with({ - let tool_call_count = Arc::clone(&tool_call_count); - move |request: &Request| { - let body: Value = request.body_json().expect("valid JSON-RPC request"); - let method = body.get("method").and_then(Value::as_str); - let authorization = request - .headers - .get("authorization") - .and_then(|value| value.to_str().ok()); - let expected_access_token = match method { - Some("tools/call") if tool_call_count.fetch_add(1, Ordering::SeqCst) == 1 => { - STALE_REFRESHED_ACCESS_TOKEN - } - _ => OLD_ACCESS_TOKEN, - }; - if authorization != Some(format!("Bearer {expected_access_token}").as_str()) { - return ResponseTemplate::new(401); - } + .respond_with(|request: &Request| { + let body: Value = request.body_json().expect("valid JSON-RPC request"); + let request_method = body.get("method").and_then(Value::as_str); + let expected_access_token = match request_method { + Some("tools/call") => EXTERNAL_ACCESS_TOKEN, + _ => OLD_ACCESS_TOKEN, + }; + let authorization = request + .headers + .get("authorization") + .and_then(|value| value.to_str().ok()); + if authorization != Some(format!("Bearer {expected_access_token}").as_str()) { + return ResponseTemplate::new(401); + } - match method { - Some("initialize") => ResponseTemplate::new(200).set_body_json(json!({ - "jsonrpc": "2.0", - "id": body.get("id").cloned().unwrap_or(Value::Null), - "result": { - "protocolVersion": body - .pointer("/params/protocolVersion") - .cloned() - .unwrap_or_else(|| json!("2025-06-18")), - "capabilities": { - "tools": {}, - }, - "serverInfo": { - "name": "oauth-external-update-test", - "version": "0.0.0-test", - }, + match request_method { + Some("initialize") => ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", + "id": body.get("id").cloned().unwrap_or(Value::Null), + "result": { + "protocolVersion": body + .pointer("/params/protocolVersion") + .cloned() + .unwrap_or_else(|| json!("2025-06-18")), + "capabilities": { + "tools": {}, }, - })), - Some("notifications/initialized") => ResponseTemplate::new(202), - Some("tools/call") => ResponseTemplate::new(200).set_body_json(json!({ - "jsonrpc": "2.0", - "id": body.get("id").cloned().unwrap_or(Value::Null), - "result": { - "content": [], - "isError": false, + "serverInfo": { + "name": "oauth-external-update-test", + "version": "0.0.0-test", }, - })), - method => ResponseTemplate::new(400) - .set_body_string(format!("unexpected JSON-RPC method: {method:?}")), - } + }, + })), + Some("notifications/initialized") => ResponseTemplate::new(202), + Some("tools/call") => ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", + "id": body.get("id").cloned().unwrap_or(Value::Null), + "result": { + "content": [], + "isError": false, + }, + })), + method => ResponseTemplate::new(400) + .set_body_string(format!("unexpected JSON-RPC method: {method:?}")), } }) - .expect(4) + .expect(3) .mount(&server) .await; @@ -272,25 +246,19 @@ async fn running_client_keeps_and_can_persist_over_external_oauth_update() -> an status.success(), "OAuth external update child failed: {status}" ); - assert_eq!(tool_call_count.load(Ordering::SeqCst), 2); server.verify().await; Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] -#[ignore = "spawned by running_client_keeps_and_can_persist_over_external_oauth_update"] +#[ignore = "spawned by running_client_adopts_external_oauth_update_before_next_operation"] async fn oauth_external_update_child() -> anyhow::Result<()> { let server_url = std::env::var(EXTERNAL_UPDATE_CHILD_SERVER_URL_ENV)?; - let old_expires_at = SystemTime::now() - .duration_since(UNIX_EPOCH)? - .checked_add(REFRESH_SKEW + Duration::from_secs(5)) - .expect("test expiry should fit") - .as_millis() as u64; save_test_tokens( &server_url, OLD_ACCESS_TOKEN, OLD_REFRESH_TOKEN, - old_expires_at, + future_expiry()?, )?; let client = RmcpClient::new_streamable_http_client( @@ -306,51 +274,182 @@ async fn oauth_external_update_child() -> anyhow::Result<()> { .await?; initialize_client(&client).await?; - let external_expires_at = SystemTime::now() - .duration_since(UNIX_EPOCH)? - .checked_add(Duration::from_secs(7200)) - .expect("test expiry should fit") - .as_millis() as u64; save_test_tokens( &server_url, EXTERNAL_ACCESS_TOKEN, EXTERNAL_REFRESH_TOKEN, - external_expires_at, + future_expiry()?, )?; client .call_tool( - "first-call-after-external-update".to_string(), + "call-after-external-update".to_string(), /*arguments*/ None, /*meta*/ None, Some(Duration::from_secs(5)), ) .await?; - let refresh_at = UNIX_EPOCH - + Duration::from_millis(old_expires_at) - .saturating_sub(REFRESH_SKEW) - .saturating_add(Duration::from_millis(250)); - if let Ok(wait) = refresh_at.duration_since(SystemTime::now()) { - tokio::time::sleep(wait).await; - } + assert_persisted_tokens(EXTERNAL_ACCESS_TOKEN, EXTERNAL_REFRESH_TOKEN)?; + Ok(()) +} +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn refresh_does_not_overwrite_external_oauth_update() -> anyhow::Result<()> { + let codex_home = TempDir::new()?; + let status = Command::new(std::env::current_exe()?) + .args([ + "oauth_external_update_during_refresh_child", + "--exact", + "--ignored", + "--nocapture", + ]) + .env("CODEX_HOME", codex_home.path()) + .status() + .await?; + assert!( + status.success(), + "OAuth external update during refresh child failed: {status}" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +#[ignore = "spawned by refresh_does_not_overwrite_external_oauth_update"] +async fn oauth_external_update_during_refresh_child() -> anyhow::Result<()> { + let server = MockServer::start().await; + let server_url = format!("{}/mcp", server.uri()); + 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": [""], + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/oauth/token")) + .and(body_string_contains("grant_type=refresh_token")) + .and(body_string_contains(format!( + "refresh_token={OLD_REFRESH_TOKEN}" + ))) + .respond_with({ + let server_url = server_url.clone(); + move |_request: &Request| { + save_test_tokens( + &server_url, + EXTERNAL_ACCESS_TOKEN, + EXTERNAL_REFRESH_TOKEN, + future_expiry().expect("future expiry"), + ) + .expect("save externally updated credentials"); + ResponseTemplate::new(200).set_body_json(json!({ + "access_token": STALE_REFRESHED_ACCESS_TOKEN, + "token_type": "Bearer", + "expires_in": 7200, + "refresh_token": STALE_ROTATED_REFRESH_TOKEN, + })) + } + }) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/mcp")) + .respond_with(|request: &Request| { + let body: Value = request.body_json().expect("valid JSON-RPC request"); + let request_method = body.get("method").and_then(Value::as_str); + let expected_access_token = match request_method { + Some("tools/call") => EXTERNAL_ACCESS_TOKEN, + _ => STALE_REFRESHED_ACCESS_TOKEN, + }; + let authorization = request + .headers + .get("authorization") + .and_then(|value| value.to_str().ok()); + if authorization != Some(format!("Bearer {expected_access_token}").as_str()) { + return ResponseTemplate::new(401); + } + + match request_method { + Some("initialize") => ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", + "id": body.get("id").cloned().unwrap_or(Value::Null), + "result": { + "protocolVersion": body + .pointer("/params/protocolVersion") + .cloned() + .unwrap_or_else(|| json!("2025-06-18")), + "capabilities": { + "tools": {}, + }, + "serverInfo": { + "name": "oauth-external-refresh-test", + "version": "0.0.0-test", + }, + }, + })), + Some("notifications/initialized") => ResponseTemplate::new(202), + Some("tools/call") => ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", + "id": body.get("id").cloned().unwrap_or(Value::Null), + "result": { + "content": [], + "isError": false, + }, + })), + method => ResponseTemplate::new(400) + .set_body_string(format!("unexpected JSON-RPC method: {method:?}")), + } + }) + .expect(3) + .mount(&server) + .await; + + save_test_tokens(&server_url, OLD_ACCESS_TOKEN, OLD_REFRESH_TOKEN, 0)?; + let client = RmcpClient::new_streamable_http_client( + SERVER_NAME, + &server_url, + /*bearer_token*/ None, + /*http_headers*/ None, + /*env_http_headers*/ None, + OAuthCredentialsStoreMode::File, + Environment::default_for_tests().get_http_client(), + /*auth_provider*/ None, + ) + .await?; + initialize_client(&client).await?; client .call_tool( - "second-call-after-stale-refresh".to_string(), + "call-after-refresh-race".to_string(), /*arguments*/ None, /*meta*/ None, Some(Duration::from_secs(5)), ) .await?; + assert_persisted_tokens(EXTERNAL_ACCESS_TOKEN, EXTERNAL_REFRESH_TOKEN)?; + server.verify().await; + Ok(()) +} + +fn future_expiry() -> anyhow::Result { + Ok(SystemTime::now() + .duration_since(UNIX_EPOCH)? + .saturating_add(Duration::from_secs(7200)) + .as_millis() as u64) +} + +fn assert_persisted_tokens(access_token: &str, refresh_token: &str) -> anyhow::Result<()> { let credentials = std::fs::read_to_string( std::path::Path::new(&std::env::var("CODEX_HOME")?).join(".credentials.json"), )?; - assert!(credentials.contains(STALE_REFRESHED_ACCESS_TOKEN)); - assert!(credentials.contains(STALE_ROTATED_REFRESH_TOKEN)); - assert!(!credentials.contains(EXTERNAL_ACCESS_TOKEN)); - assert!(!credentials.contains(EXTERNAL_REFRESH_TOKEN)); + assert!(credentials.contains(access_token)); + assert!(credentials.contains(refresh_token)); + assert!(!credentials.contains(STALE_REFRESHED_ACCESS_TOKEN)); + assert!(!credentials.contains(STALE_ROTATED_REFRESH_TOKEN)); Ok(()) }