Centralize OAuth login and refresh handling with safer diagnostics (#46300)

## Why

Login and token refresh have separate OAuth request and error handling. Token endpoint errors can echo credentials, and JSON decoding errors can expose token values in diagnostics.

## What changed

- Extract authorization URL construction, callback validation, PKCE, token grants, and error handling into a shared `oauth` module in `codex-rs/login`.
- Route authorization-code exchange and ChatGPT refresh through `OAuthClient`, retaining form and JSON encoding respectively and caller-owned HTTP and credential recovery policies.
- Redact echoed request secrets from rejection details and request IDs, redact sensitive transport URL fields, and replace token decoding errors with a generic error. Preserve original error codes for refresh failure classification.
- Keep callback state validation ahead of codes and provider errors, with the existing onboarding suffix handled by the login server.

## Testing

Add coverage for PKCE binding, request encoding and headers, callback state rejection, credential redaction, oversized or unreadable error bodies, and preservation of stored and cached credentials after transient refresh failures.

GitOrigin-RevId: d0a9583b99e24f5aafb751acd1e7200e2261a0e4
This commit is contained in:
alexsong-oai authored and copyberry committed 2026-09-17 20:17:06 +00:00
1 parent 3e581ebca8
commit 8f73cdee45
19 files changed
+1219 -634

No files matched your search

+50 -45
View File
@@ -1021,7 +1021,8 @@ async fn refresh_token_does_not_retry_after_standard_invalid_grant_failure() ->
let ctx = RefreshTokenTestContext::new(&server).await?;
let initial_last_refresh = Utc::now() - Duration::days(1);
let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN);
// Redacting a credential that overlaps the error code must not change recovery policy.
let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, "invalid");
let initial_auth = AuthDotJson {
auth_mode: Some(AuthMode::Chatgpt),
openai_api_key: None,
@@ -1228,56 +1229,60 @@ async fn refresh_token_reloads_changed_auth_after_permanent_failure() -> Result<
#[serial_test::serial(auth_env)]
#[tokio::test]
async fn refresh_token_returns_transient_error_on_server_failure() -> Result<()> {
async fn refresh_token_preserves_credentials_on_server_or_decode_failure() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/oauth/token"))
.respond_with(ResponseTemplate::new(500).set_body_json(json!({
"error": "temporary-failure"
})))
.expect(1)
.mount(&server)
.await;
for (status, body) in [
(500, json!({"error": "temporary-failure"})),
(200, json!(INITIAL_REFRESH_TOKEN)),
] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/oauth/token"))
.respond_with(ResponseTemplate::new(status).set_body_json(body))
.expect(1)
.mount(&server)
.await;
let ctx = RefreshTokenTestContext::new(&server).await?;
let initial_last_refresh = Utc::now() - Duration::days(1);
let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN);
let initial_auth = AuthDotJson {
auth_mode: Some(AuthMode::Chatgpt),
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
ctx.write_auth(&initial_auth).await?;
let ctx = RefreshTokenTestContext::new(&server).await?;
let initial_last_refresh = Utc::now() - Duration::days(1);
let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN);
let initial_auth = AuthDotJson {
auth_mode: Some(AuthMode::Chatgpt),
openai_api_key: None,
tokens: Some(initial_tokens.clone()),
last_refresh: Some(initial_last_refresh),
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
ctx.write_auth(&initial_auth).await?;
let err = ctx
.auth_manager
.refresh_token_from_authority()
.await
.err()
.context("refresh should fail")?;
assert!(matches!(err, RefreshTokenError::Transient(_)));
assert_eq!(err.failed_reason(), None);
let err = ctx
.auth_manager
.refresh_token_from_authority()
.await
.err()
.context("refresh should fail")?;
assert!(matches!(err, RefreshTokenError::Transient(_)));
assert_eq!(err.failed_reason(), None);
assert!(!format!("{err} {err:?}").contains(INITIAL_REFRESH_TOKEN));
let stored = ctx.load_auth()?;
assert_eq!(stored, initial_auth);
let cached_auth = ctx
.auth_manager
.auth()
.await
.context("auth should remain cached")?;
let cached = cached_auth
.get_token_data()
.context("token data should remain cached")?;
assert_eq!(cached, initial_tokens);
let stored = ctx.load_auth()?;
assert_eq!(stored, initial_auth);
let cached_auth = ctx
.auth_manager
.auth()
.await
.context("auth should remain cached")?;
let cached = cached_auth
.get_token_data()
.context("token data should remain cached")?;
assert_eq!(cached, initial_tokens);
server.verify().await;
server.verify().await;
}
Ok(())
}