Notify opted-in stdio MCP servers of auth changes (#43428)

## What changed

Advertise the experimental `codex/auth-change` capability for stdio MCP connections with an auth manager. When the server opts in, send `notifications/codex/authChanged` after initialization and on subsequent auth changes, with credential and owner generation counters and no credentials.

Track owner changes separately from credential refreshes so consumers can detect login, logout, or user, workspace, and auth-mode changes even when notifications coalesce. Treat credential changes with incomplete owner identity as owner changes as well.

Tie the notification watcher to the managed client's lifetime, limit each send to five seconds, and close the connection if a subsequent notification fails.

## Testing

Add tests for credential refreshes versus owner changes, coalesced logout and account switches, capability opt-in, notification payloads, and watcher cleanup.

GitOrigin-RevId: 35a99f5252bd48ca60a71fbdd1f708a8158e812c
This commit is contained in:
jif authored and copyberry committed 2026-09-07 10:37:46 +00:00
1 parent 0b263a3331
commit 0df39752cb
12 files changed
+345 -1

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
//! Tracks credential changes separately from ownership changes, before notifications coalesce.
use super::CodexAuth;
/// Opaque revisions local to one auth manager. Consumers must reset on reconnect.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AuthChangeState {
/// Advances whenever cached credentials change.
pub generation: u64,
/// Advances on login, logout, or changes of user, workspace, or auth mode.
/// Credential changes with incomplete owner identity also advance this revision.
pub owner_generation: u64,
}
pub(super) fn same_owner(previous: Option<&CodexAuth>, current: Option<&CodexAuth>) -> bool {
let (Some(previous), Some(current)) = (previous, current) else {
return false;
};
if previous.api_auth_mode() != current.api_auth_mode() {
return false;
}
let (Some(user), Some(workspace)) = (previous.get_chatgpt_user_id(), previous.get_account_id())
else {
return false;
};
!user.trim().is_empty()
&& !workspace.trim().is_empty()
&& current.get_chatgpt_user_id().as_ref() == Some(&user)
&& current.get_account_id().as_ref() == Some(&workspace)
}
@@ -0,0 +1,76 @@
use super::*;
use base64::Engine;
use pretty_assertions::assert_eq;
use serde_json::json;
fn chatgpt_auth(user: &str, workspace: &str, token: &str) -> CodexAuth {
let claims = json!({
"jti": token,
"https://api.openai.com/auth": {"chatgpt_user_id": user},
});
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string());
CodexAuth::from_external_chatgpt_tokens(
&format!("header.{payload}.signature"),
workspace,
/*chatgpt_plan_type*/ None,
)
.unwrap()
}
#[test]
fn auth_owner_generation_distinguishes_refreshes_from_identity_changes() {
let manager = AuthManager::from_optional_auth_for_testing(/*auth*/ None);
let mut changes = manager.auth_change_state_receiver();
let mut legacy_changes = manager.auth_change_receiver();
let initial = chatgpt_auth("user-a", "workspace-a", "token-1");
for (auth, generation, owner_generation) in [
(Some(initial.clone()), 1, 1),
(Some(initial), 1, 1),
(Some(chatgpt_auth("user-a", "workspace-a", "token-2")), 2, 1),
(Some(chatgpt_auth("user-b", "workspace-a", "token-3")), 3, 2),
(Some(chatgpt_auth("user-b", "workspace-b", "token-4")), 4, 3),
(Some(chatgpt_auth("", "workspace-b", "token-5")), 5, 4),
(Some(chatgpt_auth("", "workspace-b", "token-6")), 6, 5),
(Some(CodexAuth::from_api_key("key-1")), 7, 6),
(Some(CodexAuth::from_api_key("key-2")), 8, 7),
] {
manager.set_cached_auth(auth);
assert_eq!(
*changes.borrow_and_update(),
AuthChangeState {
generation,
owner_generation,
},
);
assert_eq!(*legacy_changes.borrow_and_update(), generation);
}
}
#[tokio::test]
async fn auth_owner_generation_preserves_logout_and_switches_when_coalesced() {
let home = tempfile::tempdir().unwrap();
let initial = chatgpt_auth("user-a", "workspace-a", "token-1");
let manager =
AuthManager::from_auth_for_testing_with_home(initial.clone(), home.path().to_path_buf());
let mut changes = manager.auth_change_state_receiver();
manager.logout().await.unwrap();
manager.set_cached_auth(Some(initial.clone()));
assert_eq!(
*changes.borrow_and_update(),
AuthChangeState {
generation: 2,
owner_generation: 2,
},
);
manager.set_cached_auth(Some(chatgpt_auth("user-b", "workspace-a", "token-2")));
manager.set_cached_auth(Some(initial));
assert_eq!(
*changes.borrow_and_update(),
AuthChangeState {
generation: 4,
owner_generation: 4,
},
);
}
+25
View File
@@ -36,6 +36,8 @@ use super::agent_identity::record_needs_task_registration;
use super::agent_identity::register_managed_chatgpt_agent_identity;
use super::agent_identity::require_agent_identity_authapi_base_url;
use super::agent_identity::verified_record_from_jwt;
use super::change_state::AuthChangeState;
use super::change_state::same_owner;
use super::external_bearer::BearerTokenRefresher;
use super::revoke::revoke_auth_tokens;
use super::workload_identity::WorkloadIdentityExternalAuth;
@@ -2034,6 +2036,7 @@ pub struct AuthManager {
codex_home: PathBuf,
inner: RwLock<CachedAuth>,
auth_change_tx: watch::Sender<u64>,
auth_change_state_tx: watch::Sender<AuthChangeState>,
enable_codex_api_key_env: bool,
auth_credentials_store_mode: AuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
@@ -2170,6 +2173,7 @@ impl AuthManager {
permanent_refresh_failure: None,
}),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
enable_codex_api_key_env,
auth_credentials_store_mode,
keyring_backend_kind,
@@ -2204,6 +2208,7 @@ impl AuthManager {
codex_home: PathBuf::from("non-existent"),
inner: RwLock::new(cached),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
keyring_backend_kind: AuthKeyringBackendKind::default(),
@@ -2232,6 +2237,7 @@ impl AuthManager {
codex_home,
inner: RwLock::new(cached),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
keyring_backend_kind: AuthKeyringBackendKind::default(),
@@ -2264,6 +2270,7 @@ impl AuthManager {
codex_home: PathBuf::from("non-existent"),
inner: RwLock::new(cached),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
keyring_backend_kind: AuthKeyringBackendKind::default(),
@@ -2294,6 +2301,7 @@ impl AuthManager {
permanent_refresh_failure: None,
}),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
keyring_backend_kind: AuthKeyringBackendKind::default(),
@@ -2328,6 +2336,11 @@ impl AuthManager {
self.auth_change_tx.subscribe()
}
/// Subscribes to credential and owner revisions published together, including when changes coalesce.
pub fn auth_change_state_receiver(&self) -> watch::Receiver<AuthChangeState> {
self.auth_change_state_tx.subscribe()
}
pub fn refresh_failure_for_auth(&self, auth: &CodexAuth) -> Option<RefreshTokenFailedError> {
self.inner.read().ok().and_then(|cached| {
cached
@@ -2575,12 +2588,20 @@ impl AuthManager {
let changed = !AuthManager::auths_equal(previous, new_auth.as_ref());
let auth_changed_for_refresh =
!Self::auths_equal_for_refresh(previous, new_auth.as_ref());
let owner_changed =
auth_changed_for_refresh && !same_owner(previous, new_auth.as_ref());
if auth_changed_for_refresh {
guard.permanent_refresh_failure = None;
}
tracing::info!("Reloaded auth, changed: {changed}");
guard.auth = new_auth;
if auth_changed_for_refresh {
self.auth_change_state_tx.send_modify(|state| {
state.generation += 1;
if owner_changed {
state.owner_generation += 1;
}
});
self.auth_change_tx.send_modify(|revision| *revision += 1);
}
changed
@@ -3045,3 +3066,7 @@ fn auth_config_from(config: &impl AuthManagerConfig) -> AuthConfig {
#[cfg(test)]
#[path = "auth_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "change_state_tests.rs"]
mod change_state_tests;
+2
View File
@@ -3,6 +3,7 @@ mod agent_identity;
mod auth_headers;
mod bedrock_access_keys;
mod bedrock_api_key;
mod change_state;
pub mod default_client;
pub mod error;
mod personal_access_token;
@@ -19,6 +20,7 @@ pub use bedrock_access_keys::BedrockAccessKeysAuth;
pub use bedrock_access_keys::login_with_bedrock_access_keys;
pub use bedrock_api_key::BedrockApiKeyAuth;
pub use bedrock_api_key::login_with_bedrock_api_key;
pub use change_state::AuthChangeState;
pub use error::RefreshTokenFailedError;
pub use error::RefreshTokenFailedReason;
pub use manager::*;
+1
View File
@@ -27,6 +27,7 @@ pub use success_page::LoginSuccessPage;
pub use success_page::LoginSuccessPageBrand;
pub use auth::AgentIdentityAuthPolicy;
pub use auth::AuthChangeState;
pub use auth::AuthConfig;
pub use auth::AuthDotJson;
pub use auth::AuthHeaders;