Track credential storage outcomes and redact sensitive errors (#49384)

## Why

Successful file fallback can hide a secure-store failure. Storage diagnostics need to distinguish that fallback from explicit file storage while keeping credential values out of error output.

## What changed

- Record credential load, save, delete, and fallback-file cleanup outcomes, including secure-store failures and fallback reasons.
- Preserve the initiating client's attribution across app-server requests, login tasks, sessions, turns, and blocking token persistence.
- Preserve storage error context and typed causes while redacting credential JSON data errors and payload-bearing keyring errors.
- Include sanitized fallback completion warnings in the default `codex login` file logs.

## Testing

Add coverage for storage policy and metric attribution, credential redaction, login diagnostics, concurrent app-server clients, device-code login, and token refresh during a turn.

GitOrigin-RevId: 6d5651c1718d184016fa77befa02aa528750b2ae
This commit is contained in:
Celia Chen
2026-09-29 22:24:09 +00:00
committed by copyberry
parent bd4204efc2
commit a44afa527c
24 changed files with 1465 additions and 353 deletions
+7 -1
View File
@@ -46,6 +46,8 @@ const API_KEY_LOGIN_DISABLED_MESSAGE: &str =
const ACCESS_TOKEN_LOGIN_DISABLED_MESSAGE: &str =
"Access token login is disabled. Use API key login instead.";
const LOGIN_SUCCESS_MESSAGE: &str = "Successfully logged in";
const DEFAULT_LOGIN_LOG_FILTER: &str =
"codex_cli=info,codex_core=info,codex_login=info,codex_otel::auth_storage=warn";
/// Installs a small file-backed tracing layer for direct `codex login` flows.
///
@@ -94,7 +96,7 @@ fn init_login_file_logging(config: &Config) -> Option<WorkerGuard> {
let (non_blocking, guard) = non_blocking(log_file);
let env_filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("codex_cli=info,codex_core=info,codex_login=info"));
.unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOGIN_LOG_FILTER));
let file_layer = tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_target(true)
@@ -619,6 +621,10 @@ fn safe_format_key(key: &str) -> String {
format!("{prefix}***{suffix}")
}
#[cfg(test)]
#[path = "login_storage_tests.rs"]
mod storage_tests;
#[cfg(test)]
mod tests {
use codex_config::types::AuthCredentialsStoreMode;
+87
View File
@@ -0,0 +1,87 @@
//! Verifies storage failures remain visible in direct login diagnostics.
use super::DEFAULT_LOGIN_LOG_FILTER;
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::login_with_api_key;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use tracing_subscriber::EnvFilter;
#[test]
fn login_default_filter_records_sanitized_storage_fallback() -> anyhow::Result<()> {
let home = tempdir()?;
// Fail before accessing the real keyring, then allow the plaintext fallback to succeed.
std::fs::write(home.path().join("secrets"), "not a directory")?;
let log_path = home.path().join("login.log");
let subscriber = tracing_subscriber::fmt()
.without_time()
.with_ansi(false)
.with_env_filter(EnvFilter::new(DEFAULT_LOGIN_LOG_FILTER))
.with_writer(std::fs::File::create(&log_path)?)
.finish();
tracing::subscriber::with_default(subscriber, || {
login_with_api_key(
home.path(),
"private-api-key",
AuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Secrets,
)
})?;
let logs = std::fs::read_to_string(log_path)?;
assert_eq!(logs.lines().count(), 2);
let failure = logs.lines().next().unwrap();
assert!(
failure.contains("failed to save auth to keyring, falling back to file storage"),
"{logs}"
);
assert!(failure.contains("failed to create secrets dir"), "{logs}");
assert!(
logs.contains("credential storage file fallback completed"),
"{logs}"
);
assert!(logs.contains("fallback_reason=\"secure_error\""), "{logs}");
assert!(logs.contains("outcome=\"success\""), "{logs}");
assert!(!logs.contains("private-api-key"));
let completion = logs.lines().last().unwrap();
assert!(!completion.contains(home.path().to_str().unwrap()));
let cause = std::fs::create_dir_all(home.path().join("secrets"))
.unwrap_err()
.to_string();
insta::assert_snapshot!(
logs.replace(
home.path().join("secrets").to_str().unwrap(),
"[SECRETS_PATH]"
)
.replace(&cause, "[OS_ERROR]")
);
Ok(())
}
#[test]
fn login_storage_error_displays_context_and_cause() -> anyhow::Result<()> {
let home = tempdir()?;
let secrets_path = home.path().join("secrets");
std::fs::write(&secrets_path, "not a directory")?;
let cause = std::fs::create_dir_all(&secrets_path)
.unwrap_err()
.to_string();
let error = login_with_api_key(
home.path(),
"private-api-key",
AuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Secrets,
)
.unwrap_err();
let message = error.to_string();
assert!(message.contains(&cause), "{message}");
assert!(!message.contains("private-api-key"));
// The temporary path and native filesystem error differ across platforms.
insta::assert_snapshot!(
message
.replace(secrets_path.to_str().unwrap(), "[SECRETS_PATH]")
.replace(&cause, "[OS_ERROR]")
);
Ok(())
}
@@ -0,0 +1,7 @@
---
source: cli/src/login_storage_tests.rs
assertion_line: 47
expression: "logs.replace(home.path().join(\"secrets\").to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
---
WARN codex_login::auth::storage: failed to save auth to keyring, falling back to file storage: failed to write OAuth tokens to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]
WARN codex_otel::auth_storage: credential storage file fallback completed credential_kind="codex" store_mode="auto" selected_store="secrets" actual_store="file" operation="save" secure_outcome="error" outcome="success" fallback_reason="secure_error" secure_error="other" storage_phase="policy" originator="none"
@@ -0,0 +1,6 @@
---
source: cli/src/login_storage_tests.rs
assertion_line: 58
expression: "message.replace(secrets_path.to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
---
failed to write OAuth tokens to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]