Persist agent identity in auth state

This commit is contained in:
adrian
2026-04-13 14:47:03 -07:00
parent a3cf34c4e2
commit 5589186a8e
13 changed files with 262 additions and 123 deletions
@@ -96,6 +96,7 @@ fn remote_control_auth_dot_json(account_id: Option<&str>) -> AuthDotJson {
account_id: account_id.map(str::to_string),
}),
last_refresh: Some(chrono::Utc::now()),
agent_identity: None,
}
}
@@ -971,6 +971,7 @@ mod tests {
account_id: Some("account_id".to_string()),
}),
last_refresh: Some(Utc::now()),
agent_identity: None,
}
}
@@ -163,6 +163,7 @@ pub fn write_chatgpt_auth(
openai_api_key: None,
tokens: Some(tokens),
last_refresh,
agent_identity: None,
};
save_auth(codex_home, &auth, cli_auth_credentials_store_mode).context("write auth.json")
@@ -117,6 +117,7 @@ async fn list_apps_returns_empty_with_api_key_auth() -> Result<()> {
openai_api_key: Some("test-api-key".to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
},
AuthCredentialsStoreMode::File,
)?;
+81 -115
View File
@@ -9,14 +9,11 @@ use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use chrono::SecondsFormat;
use chrono::Utc;
use codex_features::Feature;
use codex_login::AgentIdentityAuthRecord;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::default_client::create_client;
use codex_protocol::protocol::SessionSource;
use codex_secrets::SecretName;
use codex_secrets::SecretScope;
use codex_secrets::SecretsBackendKind;
use codex_secrets::SecretsManager;
use ed25519_dalek::SigningKey;
use ed25519_dalek::VerifyingKey;
use ed25519_dalek::pkcs8::DecodePrivateKey;
@@ -32,14 +29,12 @@ use tracing::warn;
use crate::config::Config;
const AGENT_IDENTITY_SECRET_NAME: &str = "AGENT_IDENTITY";
const AGENT_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(15);
const AGENT_IDENTITY_BISCUIT_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Clone)]
pub(crate) struct AgentIdentityManager {
auth_manager: Arc<AuthManager>,
secrets_manager: SecretsManager,
chatgpt_base_url: String,
feature_enabled: bool,
abom: AgentBillOfMaterials,
@@ -108,10 +103,6 @@ impl AgentIdentityManager {
) -> Self {
Self {
auth_manager,
secrets_manager: SecretsManager::new(
config.codex_home.to_path_buf(),
SecretsBackendKind::Local,
),
chatgpt_base_url: config.chatgpt_base_url.clone(),
feature_enabled: config.features.enabled(Feature::UseAgentIdentity),
abom: build_abom(session_source),
@@ -142,7 +133,7 @@ impl AgentIdentityManager {
let _guard = self.ensure_lock.lock().await;
if let Some(stored_identity) = self.load_stored_identity(&binding)? {
if let Some(stored_identity) = self.load_stored_identity(&auth, &binding)? {
info!(
agent_runtime_id = %stored_identity.agent_runtime_id,
binding_id = %binding.binding_id,
@@ -152,7 +143,7 @@ impl AgentIdentityManager {
}
let stored_identity = self.register_agent_identity(&binding).await?;
self.store_identity(&binding, &stored_identity)?;
self.store_identity(&auth, &stored_identity)?;
Ok(Some(stored_identity))
}
@@ -252,33 +243,33 @@ impl AgentIdentityManager {
fn load_stored_identity(
&self,
auth: &CodexAuth,
binding: &AgentIdentityBinding,
) -> Result<Option<StoredAgentIdentity>> {
let scope = secret_scope(binding)?;
let name = agent_identity_secret_name()?;
let Some(value) = self.secrets_manager.get(&scope, &name)? else {
let Some(record) = auth.get_agent_identity(&binding.chatgpt_account_id) else {
return Ok(None);
};
let stored_identity = match serde_json::from_str::<StoredAgentIdentity>(&value) {
Ok(stored_identity) => stored_identity,
Err(error) => {
warn!(
binding_id = %binding.binding_id,
error = %error,
"stored agent identity could not be deserialized; deleting cached value"
);
self.delete_identity(&scope, &name)?;
return Ok(None);
}
};
let stored_identity =
match StoredAgentIdentity::from_auth_record(binding, record, self.abom.clone()) {
Ok(stored_identity) => stored_identity,
Err(error) => {
warn!(
binding_id = %binding.binding_id,
error = %error,
"stored agent identity is invalid; deleting cached value"
);
auth.remove_agent_identity()?;
return Ok(None);
}
};
if !stored_identity.matches_binding(binding) {
warn!(
binding_id = %binding.binding_id,
"stored agent identity binding no longer matches current auth; deleting cached value"
);
self.delete_identity(&scope, &name)?;
auth.remove_agent_identity()?;
return Ok(None);
}
@@ -289,7 +280,7 @@ impl AgentIdentityManager {
error = %error,
"stored agent identity key material is invalid; deleting cached value"
);
self.delete_identity(&scope, &name)?;
auth.remove_agent_identity()?;
return Ok(None);
}
@@ -298,18 +289,10 @@ impl AgentIdentityManager {
fn store_identity(
&self,
binding: &AgentIdentityBinding,
auth: &CodexAuth,
stored_identity: &StoredAgentIdentity,
) -> Result<()> {
let scope = secret_scope(binding)?;
let name = agent_identity_secret_name()?;
let value = serde_json::to_string(stored_identity)
.context("failed to serialize stored agent identity")?;
self.secrets_manager.set(&scope, &name, &value)
}
fn delete_identity(&self, scope: &SecretScope, name: &SecretName) -> Result<()> {
self.secrets_manager.delete(scope, name)?;
auth.set_agent_identity(stored_identity.to_auth_record())?;
Ok(())
}
@@ -319,11 +302,9 @@ impl AgentIdentityManager {
feature_enabled: bool,
chatgpt_base_url: String,
session_source: SessionSource,
secrets_manager: SecretsManager,
) -> Self {
Self {
auth_manager,
secrets_manager,
chatgpt_base_url,
feature_enabled,
abom: build_abom(session_source),
@@ -333,6 +314,40 @@ impl AgentIdentityManager {
}
impl StoredAgentIdentity {
fn from_auth_record(
binding: &AgentIdentityBinding,
record: AgentIdentityAuthRecord,
abom: AgentBillOfMaterials,
) -> Result<Self> {
if record.workspace_id != binding.chatgpt_account_id {
anyhow::bail!(
"stored agent identity workspace {:?} does not match current workspace {:?}",
record.workspace_id,
binding.chatgpt_account_id
);
}
let signing_key = signing_key_from_private_key_pkcs8_base64(&record.agent_private_key)?;
Ok(Self {
binding_id: binding.binding_id.clone(),
chatgpt_account_id: binding.chatgpt_account_id.clone(),
chatgpt_user_id: binding.chatgpt_user_id.clone(),
agent_runtime_id: record.agent_runtime_id,
private_key_pkcs8_base64: record.agent_private_key,
public_key_ssh: encode_ssh_ed25519_public_key(&signing_key.verifying_key()),
registered_at: record.registered_at,
abom,
})
}
fn to_auth_record(&self) -> AgentIdentityAuthRecord {
AgentIdentityAuthRecord {
workspace_id: self.chatgpt_account_id.clone(),
agent_runtime_id: self.agent_runtime_id.clone(),
agent_private_key: self.private_key_pkcs8_base64.clone(),
registered_at: self.registered_at.clone(),
}
}
fn matches_binding(&self, binding: &AgentIdentityBinding) -> bool {
self.binding_id == binding.binding_id
&& self.chatgpt_account_id == binding.chatgpt_account_id
@@ -353,11 +368,7 @@ impl StoredAgentIdentity {
}
pub(crate) fn signing_key(&self) -> Result<SigningKey> {
let private_key = BASE64_STANDARD
.decode(&self.private_key_pkcs8_base64)
.context("stored agent identity private key is not valid base64")?;
SigningKey::from_pkcs8_der(&private_key)
.context("stored agent identity private key is not valid PKCS#8")
signing_key_from_private_key_pkcs8_base64(&self.private_key_pkcs8_base64)
}
}
@@ -432,21 +443,19 @@ fn append_ssh_string(buf: &mut Vec<u8>, value: &[u8]) {
buf.extend_from_slice(value);
}
fn agent_identity_secret_name() -> Result<SecretName> {
SecretName::new(AGENT_IDENTITY_SECRET_NAME)
.context("agent identity secret name constant must be valid")
}
fn secret_scope(binding: &AgentIdentityBinding) -> Result<SecretScope> {
SecretScope::environment(binding.binding_id.clone())
.context("agent identity binding must be a valid secrets scope")
}
fn agent_registration_url(chatgpt_base_url: &str) -> String {
let trimmed = chatgpt_base_url.trim_end_matches('/');
format!("{trimmed}/v1/agent/register")
}
fn signing_key_from_private_key_pkcs8_base64(private_key_pkcs8_base64: &str) -> Result<SigningKey> {
let private_key = BASE64_STANDARD
.decode(private_key_pkcs8_base64)
.context("stored agent identity private key is not valid base64")?;
SigningKey::from_pkcs8_der(&private_key)
.context("stored agent identity private key is not valid PKCS#8")
}
fn agent_identity_biscuit_url(chatgpt_base_url: &str) -> String {
let trimmed = chatgpt_base_url.trim_end_matches('/');
format!("{trimmed}/authenticate_app_v2")
@@ -469,7 +478,6 @@ mod tests {
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_app_server_protocol::AuthMode as ApiAuthMode;
use codex_keyring_store::tests::MockKeyringStore;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthDotJson;
use codex_login::save_auth;
@@ -485,13 +493,6 @@ mod tests {
#[tokio::test]
async fn ensure_registered_identity_skips_when_feature_is_disabled() {
let tempdir = tempfile::tempdir().expect("tempdir");
let keyring_store = Arc::new(MockKeyringStore::default());
let secrets_manager = SecretsManager::new_with_keyring_store(
tempdir.path().to_path_buf(),
SecretsBackendKind::Local,
keyring_store,
);
let auth_manager =
AuthManager::from_auth_for_testing(make_chatgpt_auth("account-123", Some("user-123")));
let manager = AgentIdentityManager::new_for_tests(
@@ -499,7 +500,6 @@ mod tests {
/*feature_enabled*/ false,
"https://chatgpt.com/backend-api/".to_string(),
SessionSource::Cli,
secrets_manager,
);
assert_eq!(manager.ensure_registered_identity().await.unwrap(), None);
@@ -507,20 +507,12 @@ mod tests {
#[tokio::test]
async fn ensure_registered_identity_skips_for_api_key_auth() {
let tempdir = tempfile::tempdir().expect("tempdir");
let keyring_store = Arc::new(MockKeyringStore::default());
let secrets_manager = SecretsManager::new_with_keyring_store(
tempdir.path().to_path_buf(),
SecretsBackendKind::Local,
keyring_store,
);
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-key"));
let manager = AgentIdentityManager::new_for_tests(
auth_manager,
/*feature_enabled*/ true,
"https://chatgpt.com/backend-api/".to_string(),
SessionSource::Cli,
secrets_manager,
);
assert_eq!(manager.ensure_registered_identity().await.unwrap(), None);
@@ -541,13 +533,6 @@ mod tests {
.mount(&server)
.await;
let tempdir = tempfile::tempdir().expect("tempdir");
let keyring_store = Arc::new(MockKeyringStore::default());
let secrets_manager = SecretsManager::new_with_keyring_store(
tempdir.path().to_path_buf(),
SecretsBackendKind::Local,
keyring_store,
);
let auth_manager =
AuthManager::from_auth_for_testing(make_chatgpt_auth("account-123", Some("user-123")));
let manager = AgentIdentityManager::new_for_tests(
@@ -555,7 +540,6 @@ mod tests {
/*feature_enabled*/ true,
chatgpt_base_url,
SessionSource::Cli,
secrets_manager,
);
let first = manager
@@ -591,33 +575,24 @@ mod tests {
.mount(&server)
.await;
let tempdir = tempfile::tempdir().expect("tempdir");
let keyring_store = Arc::new(MockKeyringStore::default());
let secrets_manager = SecretsManager::new_with_keyring_store(
tempdir.path().to_path_buf(),
SecretsBackendKind::Local,
keyring_store.clone(),
);
let auth_manager =
AuthManager::from_auth_for_testing(make_chatgpt_auth("account-123", Some("user-123")));
let auth = make_chatgpt_auth("account-123", Some("user-123"));
let auth_manager = AuthManager::from_auth_for_testing(auth.clone());
let manager = AgentIdentityManager::new_for_tests(
auth_manager,
/*feature_enabled*/ true,
chatgpt_base_url,
SessionSource::Cli,
secrets_manager.clone(),
);
let binding = AgentIdentityBinding::from_auth(
&make_chatgpt_auth("account-123", Some("user-123")),
/*forced_workspace_id*/ None,
)
.expect("binding");
let scope = secret_scope(&binding).expect("scope");
let name = agent_identity_secret_name().expect("secret name");
secrets_manager
.set(&scope, &name, "{\"not\":\"valid\"}")
.expect("seed invalid secret");
let binding =
AgentIdentityBinding::from_auth(&auth, /*forced_workspace_id*/ None).expect("binding");
auth.set_agent_identity(AgentIdentityAuthRecord {
workspace_id: "account-123".to_string(),
agent_runtime_id: "agent_invalid".to_string(),
agent_private_key: "not-valid-base64".to_string(),
registered_at: "2026-01-01T00:00:00Z".to_string(),
})
.expect("seed invalid identity");
let stored = manager
.ensure_registered_identity()
@@ -626,12 +601,10 @@ mod tests {
.expect("identity should be registered");
assert_eq!(stored.agent_runtime_id, "agent_456");
let persisted = secrets_manager
.get(&scope, &name)
.expect("read secret")
.expect("secret");
let parsed: StoredAgentIdentity = serde_json::from_str(&persisted).expect("json");
assert_eq!(parsed.agent_runtime_id, "agent_456");
let persisted = auth
.get_agent_identity(&binding.chatgpt_account_id)
.expect("stored identity");
assert_eq!(persisted.agent_runtime_id, "agent_456");
}
#[tokio::test]
@@ -649,13 +622,6 @@ mod tests {
.mount(&server)
.await;
let tempdir = tempfile::tempdir().expect("tempdir");
let keyring_store = Arc::new(MockKeyringStore::default());
let secrets_manager = SecretsManager::new_with_keyring_store(
tempdir.path().to_path_buf(),
SecretsBackendKind::Local,
keyring_store,
);
let auth_manager =
AuthManager::from_auth_for_testing(make_chatgpt_auth("account-123", Some("user-123")));
let manager = AgentIdentityManager::new_for_tests(
@@ -663,7 +629,6 @@ mod tests {
/*feature_enabled*/ true,
chatgpt_base_url,
SessionSource::Cli,
secrets_manager,
);
let stored = manager
@@ -727,6 +692,7 @@ mod tests {
account_id: Some(account_id.to_string()),
}),
last_refresh: Some(Utc::now()),
agent_identity: None,
};
save_auth(tempdir.path(), &auth_json, AuthCredentialsStoreMode::File).expect("save auth");
CodexAuth::from_auth_storage(tempdir.path(), AuthCredentialsStoreMode::File)
+46
View File
@@ -137,6 +137,7 @@ async fn pro_account_with_no_api_key_uses_chatgpt_auth() {
account_id: None,
}),
last_refresh: Some(last_refresh),
agent_identity: None,
},
auth_dot_json
);
@@ -174,6 +175,7 @@ fn logout_removes_auth_file() -> Result<(), std::io::Error> {
openai_api_key: Some("sk-test-key".to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
};
super::save_auth(dir.path(), &auth_dot_json, AuthCredentialsStoreMode::File)?;
let auth_file = get_auth_file(dir.path());
@@ -183,6 +185,48 @@ fn logout_removes_auth_file() -> Result<(), std::io::Error> {
Ok(())
}
#[test]
fn chatgpt_auth_persists_agent_identity_for_workspace() {
let codex_home = tempdir().unwrap();
write_auth_file(
AuthFileParams {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: Some("account-123".to_string()),
},
codex_home.path(),
)
.expect("failed to write auth file");
let auth = super::load_auth(
codex_home.path(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
)
.expect("load auth")
.expect("auth available");
let record = AgentIdentityAuthRecord {
workspace_id: "account-123".to_string(),
agent_runtime_id: "agent_123".to_string(),
agent_private_key: "pkcs8-base64".to_string(),
registered_at: "2026-04-13T12:00:00Z".to_string(),
};
auth.set_agent_identity(record.clone())
.expect("set agent identity");
assert_eq!(auth.get_agent_identity("account-123"), Some(record.clone()));
assert_eq!(auth.get_agent_identity("other-account"), None);
let storage = FileAuthStorage::new(codex_home.path().to_path_buf());
let persisted = storage
.load()
.expect("load auth")
.expect("auth should exist");
assert_eq!(persisted.agent_identity, Some(record));
assert!(auth.remove_agent_identity().expect("remove agent identity"));
assert_eq!(auth.get_agent_identity("account-123"), None);
}
#[test]
fn unauthorized_recovery_reports_mode_and_step_names() {
let dir = tempdir().unwrap();
@@ -493,6 +537,7 @@ async fn auth_manager_notifies_when_auth_state_changes() {
openai_api_key: Some("sk-test-key".to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
},
AuthCredentialsStoreMode::File,
)
@@ -514,6 +559,7 @@ async fn auth_manager_notifies_when_auth_state_changes() {
openai_api_key: Some("sk-updated-key".to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
},
AuthCredentialsStoreMode::File,
)
+64 -8
View File
@@ -21,6 +21,7 @@ use codex_protocol::config_types::ForcedLoginMethod;
use codex_protocol::config_types::ModelProviderAuthInfo;
use super::external_bearer::BearerTokenRefresher;
pub use crate::auth::storage::AgentIdentityAuthRecord;
pub use crate::auth::storage::AuthDotJson;
use crate::auth::storage::AuthStorageBackend;
use crate::auth::storage::create_auth_storage;
@@ -61,6 +62,7 @@ pub struct ChatgptAuth {
#[derive(Debug, Clone)]
pub struct ChatgptAuthTokens {
state: ChatgptAuthState,
storage: Arc<dyn AuthStorageBackend>,
}
#[derive(Debug, Clone)]
@@ -205,14 +207,13 @@ impl CodexAuth {
client,
};
let storage = create_auth_storage(codex_home.to_path_buf(), storage_mode);
match auth_mode {
ApiAuthMode::Chatgpt => {
let storage = create_auth_storage(codex_home.to_path_buf(), storage_mode);
Ok(Self::Chatgpt(ChatgptAuth { state, storage }))
}
ApiAuthMode::ChatgptAuthTokens => {
Ok(Self::ChatgptAuthTokens(ChatgptAuthTokens { state }))
}
ApiAuthMode::Chatgpt => Ok(Self::Chatgpt(ChatgptAuth { state, storage })),
ApiAuthMode::ChatgptAuthTokens => Ok(Self::ChatgptAuthTokens(ChatgptAuthTokens {
state,
storage,
})),
ApiAuthMode::ApiKey => unreachable!("api key mode is handled above"),
}
}
@@ -352,6 +353,52 @@ impl CodexAuth {
self.get_current_auth_json().and_then(|t| t.tokens)
}
pub fn get_agent_identity(&self, workspace_id: &str) -> Option<AgentIdentityAuthRecord> {
self.get_current_auth_json()
.and_then(|auth| auth.agent_identity)
.filter(|identity| identity.workspace_id == workspace_id)
}
pub fn set_agent_identity(&self, record: AgentIdentityAuthRecord) -> std::io::Result<()> {
let (state, storage) = match self {
Self::Chatgpt(auth) => (&auth.state, &auth.storage),
Self::ChatgptAuthTokens(auth) => (&auth.state, &auth.storage),
Self::ApiKey(_) => return Ok(()),
};
let mut guard = state
.auth_dot_json
.lock()
.map_err(|_| std::io::Error::other("failed to lock auth state"))?;
let mut auth = guard
.clone()
.ok_or_else(|| std::io::Error::other("auth data is not available"))?;
auth.agent_identity = Some(record);
storage.save(&auth)?;
*guard = Some(auth);
Ok(())
}
pub fn remove_agent_identity(&self) -> std::io::Result<bool> {
let (state, storage) = match self {
Self::Chatgpt(auth) => (&auth.state, &auth.storage),
Self::ChatgptAuthTokens(auth) => (&auth.state, &auth.storage),
Self::ApiKey(_) => return Ok(false),
};
let mut guard = state
.auth_dot_json
.lock()
.map_err(|_| std::io::Error::other("failed to lock auth state"))?;
let Some(mut auth) = guard.clone() else {
return Ok(false);
};
let removed = auth.agent_identity.take().is_some();
if removed {
storage.save(&auth)?;
*guard = Some(auth);
}
Ok(removed)
}
/// Consider this private to integration tests.
pub fn create_dummy_chatgpt_auth_for_testing() -> Self {
let auth_dot_json = AuthDotJson {
@@ -364,6 +411,7 @@ impl CodexAuth {
account_id: Some("account_id".to_string()),
}),
last_refresh: Some(Utc::now()),
agent_identity: None,
};
let client = create_client();
@@ -439,6 +487,7 @@ pub fn login_with_api_key(
openai_api_key: Some(api_key.to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
};
save_auth(codex_home, &auth_dot_json, auth_credentials_store_mode)
}
@@ -812,6 +861,7 @@ impl AuthDotJson {
openai_api_key: None,
tokens: Some(tokens),
last_refresh: Some(Utc::now()),
agent_identity: None,
})
}
@@ -1657,8 +1707,14 @@ impl AuthManager {
),
)));
}
let auth_dot_json =
let mut auth_dot_json =
AuthDotJson::from_external_tokens(&refreshed).map_err(RefreshTokenError::Transient)?;
if let Some(previous_auth) = self
.auth_cached()
.and_then(|auth| auth.get_current_auth_json())
{
auth_dot_json.agent_identity = previous_auth.agent_identity;
}
save_auth(
&self.codex_home,
&auth_dot_json,
+11
View File
@@ -39,6 +39,17 @@ pub struct AuthDotJson {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_refresh: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent_identity: Option<AgentIdentityAuthRecord>,
}
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct AgentIdentityAuthRecord {
pub workspace_id: String,
pub agent_runtime_id: String,
pub agent_private_key: String,
pub registered_at: String,
}
pub(super) fn get_auth_file(codex_home: &Path) -> PathBuf {
+30
View File
@@ -18,6 +18,7 @@ async fn file_storage_load_returns_auth_dot_json() -> anyhow::Result<()> {
openai_api_key: Some("test-key".to_string()),
tokens: None,
last_refresh: Some(Utc::now()),
agent_identity: None,
};
storage
@@ -38,6 +39,7 @@ async fn file_storage_save_persists_auth_dot_json() -> anyhow::Result<()> {
openai_api_key: Some("test-key".to_string()),
tokens: None,
last_refresh: Some(Utc::now()),
agent_identity: None,
};
let file = get_auth_file(codex_home.path());
@@ -52,6 +54,29 @@ async fn file_storage_save_persists_auth_dot_json() -> anyhow::Result<()> {
Ok(())
}
#[tokio::test]
async fn file_storage_persists_agent_identity() -> anyhow::Result<()> {
let codex_home = tempdir()?;
let storage = FileAuthStorage::new(codex_home.path().to_path_buf());
let auth_dot_json = AuthDotJson {
auth_mode: Some(AuthMode::Chatgpt),
openai_api_key: None,
tokens: None,
last_refresh: Some(Utc::now()),
agent_identity: Some(AgentIdentityAuthRecord {
workspace_id: "account-123".to_string(),
agent_runtime_id: "agent_123".to_string(),
agent_private_key: "pkcs8-base64".to_string(),
registered_at: "2026-04-13T12:00:00Z".to_string(),
}),
};
storage.save(&auth_dot_json)?;
assert_eq!(storage.load()?, Some(auth_dot_json));
Ok(())
}
#[test]
fn file_storage_delete_removes_auth_file() -> anyhow::Result<()> {
let dir = tempdir()?;
@@ -60,6 +85,7 @@ fn file_storage_delete_removes_auth_file() -> anyhow::Result<()> {
openai_api_key: Some("sk-test-key".to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
};
let storage = create_auth_storage(dir.path().to_path_buf(), AuthCredentialsStoreMode::File);
storage.save(&auth_dot_json)?;
@@ -83,6 +109,7 @@ fn ephemeral_storage_save_load_delete_is_in_memory_only() -> anyhow::Result<()>
openai_api_key: Some("sk-ephemeral".to_string()),
tokens: None,
last_refresh: Some(Utc::now()),
agent_identity: None,
};
storage.save(&auth_dot_json)?;
@@ -181,6 +208,7 @@ fn auth_with_prefix(prefix: &str) -> AuthDotJson {
account_id: Some(format!("{prefix}-account-id")),
}),
last_refresh: None,
agent_identity: None,
}
}
@@ -197,6 +225,7 @@ fn keyring_auth_storage_load_returns_deserialized_auth() -> anyhow::Result<()> {
openai_api_key: Some("sk-test".to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
};
seed_keyring_with_auth(
&mock_keyring,
@@ -239,6 +268,7 @@ fn keyring_auth_storage_save_persists_and_removes_fallback_file() -> anyhow::Res
account_id: Some("account".to_string()),
}),
last_refresh: Some(Utc::now()),
agent_identity: None,
};
storage.save(&auth)?;
+1
View File
@@ -20,6 +20,7 @@ pub use server::ShutdownHandle;
pub use server::run_login_server;
pub use api_bridge::auth_provider_from_auth;
pub use auth::AgentIdentityAuthRecord;
pub use auth::AuthConfig;
pub use auth::AuthDotJson;
pub use auth::AuthManager;
+1
View File
@@ -781,6 +781,7 @@ pub(crate) async fn persist_tokens_async(
openai_api_key: api_key,
tokens: Some(tokens),
last_refresh: Some(Utc::now()),
agent_identity: None,
};
save_auth(&codex_home, &auth, auth_credentials_store_mode)
})
@@ -54,6 +54,7 @@ async fn refresh_token_succeeds_updates_storage() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -117,6 +118,7 @@ async fn refresh_token_refreshes_when_auth_is_unchanged() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -171,6 +173,7 @@ async fn refresh_token_skips_refresh_when_auth_changed() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -180,6 +183,7 @@ async fn refresh_token_skips_refresh_when_auth_changed() -> Result<()> {
openai_api_key: None,
tokens: Some(disk_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
save_auth(
ctx.codex_home.path(),
@@ -234,6 +238,7 @@ async fn refresh_token_errors_on_account_mismatch() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -244,6 +249,7 @@ async fn refresh_token_errors_on_account_mismatch() -> Result<()> {
openai_api_key: None,
tokens: Some(disk_tokens),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
save_auth(
ctx.codex_home.path(),
@@ -302,6 +308,7 @@ async fn returns_fresh_tokens_as_is() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(stale_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -349,6 +356,7 @@ async fn refreshes_token_when_access_token_is_expired() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(fresh_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -398,6 +406,7 @@ async fn auth_reloads_disk_auth_when_cached_auth_is_stale() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens),
last_refresh: Some(stale_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -408,6 +417,7 @@ async fn auth_reloads_disk_auth_when_cached_auth_is_stale() -> Result<()> {
openai_api_key: None,
tokens: Some(disk_tokens.clone()),
last_refresh: Some(fresh_refresh),
agent_identity: None,
};
save_auth(
ctx.codex_home.path(),
@@ -459,6 +469,7 @@ async fn auth_reloads_disk_auth_without_calling_expired_refresh_token() -> Resul
openai_api_key: None,
tokens: Some(initial_tokens),
last_refresh: Some(stale_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -469,6 +480,7 @@ async fn auth_reloads_disk_auth_without_calling_expired_refresh_token() -> Resul
openai_api_key: None,
tokens: Some(disk_tokens.clone()),
last_refresh: Some(fresh_refresh),
agent_identity: None,
};
save_auth(
ctx.codex_home.path(),
@@ -518,6 +530,7 @@ async fn refresh_token_returns_permanent_error_for_expired_refresh_token() -> Re
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -570,6 +583,7 @@ async fn refresh_token_does_not_retry_after_permanent_failure() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -636,6 +650,7 @@ async fn refresh_token_reloads_changed_auth_after_permanent_failure() -> Result<
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -657,6 +672,7 @@ async fn refresh_token_reloads_changed_auth_after_permanent_failure() -> Result<
openai_api_key: None,
tokens: Some(disk_tokens.clone()),
last_refresh: Some(fresh_refresh),
agent_identity: None,
};
save_auth(
ctx.codex_home.path(),
@@ -715,6 +731,7 @@ async fn refresh_token_returns_transient_error_on_server_failure() -> Result<()>
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -767,6 +784,7 @@ async fn unauthorized_recovery_reloads_then_refreshes_tokens() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -776,6 +794,7 @@ async fn unauthorized_recovery_reloads_then_refreshes_tokens() -> Result<()> {
openai_api_key: None,
tokens: Some(disk_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
save_auth(
ctx.codex_home.path(),
@@ -859,6 +878,7 @@ async fn unauthorized_recovery_errors_on_account_mismatch() -> Result<()> {
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
ctx.write_auth(&initial_auth)?;
@@ -869,6 +889,7 @@ async fn unauthorized_recovery_errors_on_account_mismatch() -> Result<()> {
openai_api_key: None,
tokens: Some(disk_tokens),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
};
save_auth(
ctx.codex_home.path(),
@@ -926,6 +947,7 @@ async fn unauthorized_recovery_requires_chatgpt_auth() -> Result<()> {
openai_api_key: Some("sk-test".to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
};
ctx.write_auth(&auth)?;
+2
View File
@@ -108,6 +108,7 @@ mod tests {
account_id: Some("workspace-1".to_string()),
}),
last_refresh: Some(Utc::now()),
agent_identity: None,
};
save_auth(codex_home, &auth, AuthCredentialsStoreMode::File)
.expect("chatgpt auth should save");
@@ -154,6 +155,7 @@ mod tests {
openai_api_key: Some("sk-test".to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
},
AuthCredentialsStoreMode::File,
)