Files
codex-proxy-rs/backend/crates/providers/openai/tests/credential/refresh.rs
T
ZyyandCodex 3e747cb233 fix(providers): use global identity for background operations
Apply global client profiles to OAuth, token refresh and account background operations across OpenAI, xAI and Antigravity. Preserve Client Key overrides for model requests.

Co-authored-by: Codex <noreply@openai.com>
2026-11-25 21:02:04 +08:00

1071 lines
36 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 验证 OpenAI 令牌刷新、凭据状态与失败反馈的持久化
use std::num::NonZeroU32;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use chrono::{DateTime, TimeZone as _, Utc};
use futures::future::BoxFuture;
use gateway_core::account::{
AccountErrorReason, AccountStateChange, AccountStatus, CredentialState, ProviderAccountId,
ProviderAccountStore, QuotaAccessChange, QuotaEvidence, QuotaState, QuotaWriteOutcome,
};
use gateway_core::policy::ClientApiKeyId;
use gateway_core::provider_ports::{
ProviderCredentialState, ProviderCredentialStatePort, ProviderLeaseAcquisition,
ProviderLeasePort, ProviderLeaseRequest, ProviderRefreshPolicy, ProviderRuntimePolicyPort,
ProviderSchedulingState, ProviderStoreError,
};
use gateway_core::routing::ProviderKind;
use provider_openai::credential::token_client::{
OpenAiTokenClient, RefreshFailure, TokenClientConfig, TokenPair, TokenRefresher,
};
use provider_openai::credential::{
CodexCredentialCodec, CodexCredentialRefreshOutcome, CodexCredentialRefreshService,
ImportCodexOAuthCredential,
};
use secrecy::{ExposeSecret as _, SecretString};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
use crate::support::{MemoryAccountStore, profile, secret};
struct SingleUseRefresher {
calls: AtomicUsize,
response: Mutex<Option<TokenPair>>,
}
impl SingleUseRefresher {
fn new() -> Arc<Self> {
Arc::new(Self {
calls: AtomicUsize::new(0),
response: Mutex::new(Some(TokenPair {
access_token: Some("refreshed-access-token".to_owned()),
refresh_token: None,
id_token: None,
})),
})
}
fn calls(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
fn with_id_token(id_token: &str) -> Arc<Self> {
Arc::new(Self {
calls: AtomicUsize::new(0),
response: Mutex::new(Some(TokenPair {
access_token: Some("refreshed-access-token".to_owned()),
refresh_token: None,
id_token: Some(id_token.to_owned()),
})),
})
}
fn with_access_token(access_token: String) -> Arc<Self> {
Arc::new(Self {
calls: AtomicUsize::new(0),
response: Mutex::new(Some(TokenPair {
access_token: Some(access_token),
refresh_token: None,
id_token: None,
})),
})
}
fn without_rotated_tokens() -> Arc<Self> {
Arc::new(Self {
calls: AtomicUsize::new(0),
response: Mutex::new(Some(TokenPair {
access_token: None,
refresh_token: None,
id_token: None,
})),
})
}
}
#[async_trait]
impl TokenRefresher for SingleUseRefresher {
async fn refresh(&self, _: &str) -> Result<TokenPair, RefreshFailure> {
self.calls.fetch_add(1, Ordering::SeqCst);
self.response
.lock()
.expect("refresh response lock")
.take()
.ok_or_else(|| RefreshFailure::Transport {
redacted: false,
source: None,
message: Some("test refresh response is exhausted".to_owned()),
upstream: None,
})
}
}
struct FailingRefresher {
failure: RefreshFailure,
}
#[async_trait]
impl TokenRefresher for FailingRefresher {
async fn refresh(&self, _: &str) -> Result<TokenPair, RefreshFailure> {
Err(self.failure.clone())
}
}
struct RefreshLeases;
impl ProviderLeasePort for RefreshLeases {
fn load_state<'a>(
&'a self,
_: &'a ClientApiKeyId,
_: &'a ProviderKind,
_: &'a [ProviderAccountId],
_pool: gateway_core::provider_ports::ProviderConcurrencyPool,
) -> BoxFuture<'a, Result<ProviderSchedulingState, ProviderStoreError>> {
Box::pin(async { panic!("scheduled credential refresh does not load scheduling state") })
}
fn try_acquire(
&self,
request: ProviderLeaseRequest,
) -> BoxFuture<'_, Result<ProviderLeaseAcquisition, ProviderStoreError>> {
Box::pin(async move {
match request {
ProviderLeaseRequest::RefreshCapacity(_) | ProviderLeaseRequest::Refresh(_) => {
Ok(ProviderLeaseAcquisition::Acquired(Box::new(())))
}
ProviderLeaseRequest::Scheduling(_) => {
panic!("scheduled credential refresh must not acquire a scheduling lease")
}
}
})
}
}
struct RefreshCredentialState;
impl ProviderCredentialStatePort for RefreshCredentialState {
fn replace(&self, _: ProviderCredentialState) -> BoxFuture<'_, Result<(), ProviderStoreError>> {
Box::pin(async { Ok(()) })
}
fn read<'a>(
&'a self,
_: &'a ProviderAccountId,
) -> BoxFuture<'a, Result<Option<ProviderCredentialState>, ProviderStoreError>> {
Box::pin(async { Ok(None) })
}
fn clear<'a>(
&'a self,
_: &'a ProviderAccountId,
) -> BoxFuture<'a, Result<bool, ProviderStoreError>> {
Box::pin(async { Ok(false) })
}
fn record_refresh_backoff<'a>(
&'a self,
_: &'a ProviderAccountId,
_: Duration,
) -> BoxFuture<'a, Result<u32, ProviderStoreError>> {
Box::pin(async { Ok(1) })
}
fn clear_refresh_backoff<'a>(
&'a self,
_: &'a ProviderAccountId,
) -> BoxFuture<'a, Result<(), ProviderStoreError>> {
Box::pin(async { Ok(()) })
}
}
struct MutableRuntimePolicy {
policy: Mutex<ProviderRefreshPolicy>,
}
impl MutableRuntimePolicy {
fn new(margin: Duration) -> Arc<Self> {
Arc::new(Self {
policy: Mutex::new(refresh_policy(margin)),
})
}
fn set_margin(&self, margin: Duration) {
*self.policy.lock().expect("runtime policy lock") = refresh_policy(margin);
}
}
impl ProviderRuntimePolicyPort for MutableRuntimePolicy {
fn load_refresh_policy(
&self,
) -> BoxFuture<'_, Result<ProviderRefreshPolicy, ProviderStoreError>> {
Box::pin(async { Ok(*self.policy.lock().expect("runtime policy lock")) })
}
}
fn refresh_policy(margin: Duration) -> ProviderRefreshPolicy {
ProviderRefreshPolicy::try_new(margin, NonZeroU32::new(1).expect("positive concurrency"))
.expect("valid refresh policy")
}
fn refresh_service(
store: &Arc<MemoryAccountStore>,
refresher: Arc<SingleUseRefresher>,
runtime_policy: Arc<MutableRuntimePolicy>,
) -> CodexCredentialRefreshService {
CodexCredentialRefreshService::new(
store.repository(),
refresher,
Arc::new(RefreshLeases),
Arc::new(RefreshCredentialState),
runtime_policy,
Arc::new(crate::RecordingDiagnostics::default()),
)
}
async fn seed_refreshable_account(
store: &Arc<MemoryAccountStore>,
account_id: &str,
access_token_expires_at: SystemTime,
retry_not_before: Option<SystemTime>,
) {
let mut verified_account = profile(&format!("chatgpt-{account_id}"));
verified_account.access_token_expires_at = Some(DateTime::<Utc>::from(access_token_expires_at));
store
.seed_oauth_credential(ImportCodexOAuthCredential {
account_id: account_id.to_owned(),
name: account_id.to_owned(),
secret: secret(&format!("access-{account_id}")),
verified_account,
next_refresh_at: retry_not_before.map(DateTime::<Utc>::from),
enabled: true,
})
.await;
}
#[tokio::test]
async fn scheduled_refresh_rotates_tokens_without_enabling_scheduling() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let refresher = SingleUseRefresher::new();
let service = refresh_service(&store, Arc::clone(&refresher), policy);
let account_id = "acct_disabled_refresh";
seed_refreshable_account(&store, account_id, SystemTime::now(), None).await;
let before = store.account(account_id).expect("seeded account");
store
.set_enabled(before.id(), false)
.await
.expect("disable scheduling");
let outcomes = service.refresh_due().await.expect("refresh cycle");
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Refreshed { account_id: refreshed_id, .. }]
if refreshed_id == account_id
));
assert_eq!(refresher.calls(), 1);
let after = store.account(account_id).expect("refreshed account");
assert!(!after.enabled());
assert_eq!(after.quota(), before.quota());
assert_eq!(
after.status_projection(SystemTime::now(), None).status,
AccountStatus::Disabled
);
let loaded = store
.load_credential(after.id(), after.revision())
.await
.expect("refreshed credential");
let runtime = CodexCredentialCodec::decode(&loaded.credential).expect("runtime credential");
assert_eq!(
runtime
.authentication
.oauth()
.expect("OAuth credential")
.access_token
.expose_secret(),
"refreshed-access-token"
);
}
#[tokio::test]
async fn scheduled_refresh_stops_retrying_rejected_disabled_credentials() {
let store = Arc::new(MemoryAccountStore::default());
let service = CodexCredentialRefreshService::new(
store.repository(),
Arc::new(FailingRefresher {
failure: RefreshFailure::InvalidGrant {
message: None,
upstream: None,
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(5 * 60)),
Arc::new(crate::RecordingDiagnostics::default()),
);
let account_id = "acct_disabled_rejected";
seed_refreshable_account(&store, account_id, SystemTime::now(), None).await;
let account = store.account(account_id).expect("seeded account");
store
.set_enabled(account.id(), false)
.await
.expect("disable scheduling");
assert!(matches!(
service
.refresh_due()
.await
.expect("refresh cycle")
.as_slice(),
[CodexCredentialRefreshOutcome::Invalidated { .. }]
));
let account = store.account(account_id).expect("rejected account");
assert!(!account.enabled());
assert_eq!(account.credential_state(), CredentialState::Expired);
assert!(
service
.refresh_due()
.await
.expect("next refresh cycle")
.is_empty()
);
}
#[tokio::test]
async fn scheduled_refresh_uses_the_current_margin_without_persisting_a_normal_schedule() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(1));
let refresher = SingleUseRefresher::new();
let service = refresh_service(&store, Arc::clone(&refresher), Arc::clone(&policy));
let account_id = "acct_dynamic_margin";
seed_refreshable_account(
&store,
account_id,
SystemTime::now()
.checked_add(Duration::from_secs(120))
.expect("test expiry"),
None,
)
.await;
assert!(
service
.refresh_due()
.await
.expect("refresh cycle below margin")
.is_empty()
);
assert_eq!(refresher.calls(), 0);
assert!(
store
.account(account_id)
.expect("seeded account")
.next_refresh_at()
.is_none()
);
policy.set_margin(Duration::from_secs(5 * 60));
let outcomes = service
.refresh_due()
.await
.expect("refresh cycle inside margin");
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Refreshed {
account_id: refreshed_account_id,
..
}] if refreshed_account_id == account_id
));
assert_eq!(refresher.calls(), 1);
assert!(
store
.account(account_id)
.expect("refreshed account")
.next_refresh_at()
.is_none()
);
}
#[tokio::test]
async fn scheduled_refresh_staggers_accounts_sharing_the_same_expiry() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let refresher = SingleUseRefresher::new();
let service = refresh_service(&store, Arc::clone(&refresher), policy);
// margin=300s:寻找一个错峰偏移覆盖到 exp、一个未覆盖的账号,两者共享同一到期时刻。
let policy_value = refresh_policy(Duration::from_secs(5 * 60));
let mut covered = None;
let mut pending = None;
for index in 0..64 {
let candidate =
ProviderAccountId::new(format!("acct_stagger_{index}")).expect("valid account");
let stagger = policy_value.refresh_stagger(&candidate).as_secs();
if stagger >= 150 && covered.is_none() {
covered = Some(candidate.clone());
}
if stagger < 60 && pending.is_none() {
pending = Some(candidate);
}
}
let covered = covered.expect("an account covered by its stagger");
let pending = pending.expect("an account not yet covered by its stagger");
// exp = now+400s:covered 的有效提前量 ≥ 450s(到期);pending 的 ≤ 360s,
// 即使种子与扫描之间存在秒级耗时也不会提前触发。
let expires_at = SystemTime::now()
.checked_add(Duration::from_secs(400))
.expect("test expiry");
seed_refreshable_account(&store, covered.as_str(), expires_at, None).await;
seed_refreshable_account(&store, pending.as_str(), expires_at, None).await;
let outcomes = service.refresh_due().await.expect("refresh cycle");
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Refreshed { account_id, .. }] if account_id == covered.as_str()
));
assert_eq!(refresher.calls(), 1);
// 未到错峰窗口的账号本轮零接触:不刷新、也不落退避计划。
let pending_account = store.account(pending.as_str()).expect("seeded account");
assert!(pending_account.next_refresh_at().is_none());
assert_eq!(pending_account.credential_state(), CredentialState::Ready);
}
#[tokio::test]
async fn quota_revocation_overrides_exhaustion_until_scheduled_refresh_replaces_the_token() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let service = refresh_service(&store, SingleUseRefresher::new(), policy);
let account_id = "acct_exhausted_quota_refresh";
seed_refreshable_account(
&store,
account_id,
SystemTime::now()
.checked_add(Duration::from_secs(24 * 3600))
.expect("test expiry"),
None,
)
.await;
let account = store.account(account_id).expect("seeded account");
assert_eq!(
store
.apply_quota_access(QuotaAccessChange {
account_id: account.id().clone(),
expected_revision: account.revision(),
state: QuotaState::exhausted(
QuotaEvidence::UsageLimitReached,
SystemTime::now(),
None,
),
})
.await
.expect("persist exhausted quota"),
QuotaWriteOutcome::Updated
);
let before = store.account(account_id).expect("exhausted account");
assert_eq!(
before.status_projection(SystemTime::now(), None).status,
AccountStatus::QuotaExhausted
);
assert!(service.refresh_due().await.unwrap().is_empty());
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(
ResponseTemplate::new(401)
.set_body_raw(r#"{"detail":{"code":"token_revoked"}}"#, "text/plain"),
)
.expect(1)
.mount(&server)
.await;
let quota = super::quota::quota_service_with_base_url(
&store,
reqwest::Client::builder().no_proxy().build().unwrap(),
server.uri(),
);
assert_eq!(quota.synchronize().await.unwrap().revoked, 1);
let revoked = store.account(account_id).expect("revoked account");
let status = revoked.status_projection(SystemTime::now(), None);
assert_eq!(status.status, AccountStatus::Error);
assert_eq!(
status.error_reason,
Some(AccountErrorReason::AccessTokenExpired)
);
assert_eq!(revoked.quota(), before.quota());
assert_eq!(revoked.revision(), before.revision());
let outcomes = service.refresh_due().await.expect("refresh cycle");
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Refreshed {
account_id: refreshed_account_id,
..
}] if refreshed_account_id == account_id
));
let account = store.account(account_id).expect("refreshed account");
assert!(account.quota().is_exhausted());
assert_eq!(
account.status_projection(SystemTime::now(), None).status,
AccountStatus::QuotaExhausted
);
assert!(
!store
.expire_access_token(&before, SystemTime::now())
.await
.unwrap()
);
let loaded = store
.load_credential(account.id(), account.revision())
.await
.expect("refreshed credential");
let runtime = CodexCredentialCodec::decode(&loaded.credential).expect("runtime credential");
let oauth = runtime.authentication.oauth().expect("OAuth credential");
assert_eq!(oauth.access_token.expose_secret(), "refreshed-access-token");
let expected_refresh_token = format!("rt-access-{account_id}");
assert_eq!(
oauth
.refresh_token
.as_ref()
.map(SecretString::expose_secret),
Some(expected_refresh_token.as_str())
);
}
#[tokio::test]
async fn scheduled_refresh_persists_the_original_upstream_error_message() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let upstream_message = "Refresh token has already been used.";
let service = CodexCredentialRefreshService::new(
store.repository(),
Arc::new(FailingRefresher {
failure: RefreshFailure::InvalidGrant {
message: Some(upstream_message.to_owned()),
upstream: None,
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshCredentialState),
policy,
Arc::new(crate::RecordingDiagnostics::default()),
);
let account_id = "acct_invalid_refresh_token";
seed_refreshable_account(
&store,
account_id,
SystemTime::now()
.checked_add(Duration::from_secs(120))
.expect("test expiry"),
None,
)
.await;
let outcomes = service.refresh_due().await.expect("refresh cycle");
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Invalidated {
account_id: invalidated_account_id,
}] if invalidated_account_id == account_id
));
assert_eq!(
store
.account(account_id)
.expect("invalidated account")
.last_error_message(),
Some(upstream_message)
);
}
#[tokio::test]
async fn scheduled_refresh_persists_retryable_message_inside_the_two_hour_window() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let upstream_message = "Invalid refresh token.";
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/oauth/token"))
.respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({
"error": {
"message": upstream_message,
"type": "invalid_request_error",
"code": "invalid_refresh_token"
}
})))
.expect(1)
.mount(&server)
.await;
let service = CodexCredentialRefreshService::new(
store.repository(),
Arc::new(OpenAiTokenClient::new(
reqwest::Client::builder()
.no_proxy()
.build()
.expect("test HTTP client"),
TokenClientConfig {
client_id: "test-public-client".to_owned(),
token_endpoint: format!("{}/oauth/token", server.uri()),
},
provider_openai::profile::CodexWireProfileState::new(Default::default()),
crate::support::runtime_policy(),
)),
Arc::new(RefreshLeases),
Arc::new(RefreshCredentialState),
policy,
Arc::new(crate::RecordingDiagnostics::default()),
);
let account_id = "acct_retryable_unauthorized";
let expires_at = SystemTime::now()
.checked_sub(Duration::from_secs(30 * 60))
.expect("expired access token");
seed_refreshable_account(&store, account_id, expires_at, None).await;
let outcomes = service.refresh_due().await.expect("refresh cycle");
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Transient {
account_id: deferred_account_id,
}] if deferred_account_id == account_id
));
let account = store.account(account_id).expect("deferred account");
assert_eq!(account.credential_state(), CredentialState::Ready);
assert_eq!(
account.last_error_reason(),
Some(AccountErrorReason::AccessTokenExpired)
);
assert_eq!(account.last_error_message(), Some(upstream_message));
let retry_at = account.next_refresh_at().expect("next refresh attempt");
assert!(retry_at > SystemTime::now());
assert!(
retry_at
<= expires_at
.checked_add(Duration::from_secs(2 * 60 * 60))
.expect("recovery deadline")
);
let projection = account.status_projection(SystemTime::now(), None);
assert_eq!(projection.status, AccountStatus::Error);
assert_eq!(projection.error_message.as_deref(), Some(upstream_message));
}
#[tokio::test]
async fn scheduled_refresh_uses_the_final_message_after_the_two_hour_window() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let upstream_message = "Invalid refresh token.";
let service = CodexCredentialRefreshService::new(
store.repository(),
Arc::new(FailingRefresher {
failure: RefreshFailure::Transport {
redacted: false,
source: None,
message: Some(upstream_message.to_owned()),
upstream: None,
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshCredentialState),
policy,
Arc::new(crate::RecordingDiagnostics::default()),
);
let account_id = "acct_exhausted_unauthorized";
seed_refreshable_account(
&store,
account_id,
SystemTime::now()
.checked_sub(Duration::from_secs(2 * 60 * 60 + 60))
.expect("expired recovery window"),
None,
)
.await;
let outcomes = service.refresh_due().await.expect("refresh cycle");
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Invalidated {
account_id: invalidated_account_id,
}] if invalidated_account_id == account_id
));
let account = store.account(account_id).expect("invalidated account");
assert_eq!(account.credential_state(), CredentialState::Expired);
assert_eq!(account.last_error_message(), Some(upstream_message));
}
#[tokio::test]
async fn scheduled_refresh_success_clears_a_deferred_failure_message() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let account_id = "acct_recovered_after_backoff";
seed_refreshable_account(
&store,
account_id,
SystemTime::now()
.checked_sub(Duration::from_secs(60))
.expect("expired access token"),
None,
)
.await;
let account = store.account(account_id).expect("seeded account");
store
.apply_state_change(AccountStateChange {
account_id: account.id().clone(),
expected_revision: account.revision(),
credential_state: CredentialState::Ready,
observed_at: SystemTime::now(),
error_reason: Some(AccountErrorReason::AccessTokenExpired),
message: Some("Invalid refresh token.".to_owned()),
})
.await
.expect("seed deferred failure");
let service = refresh_service(&store, SingleUseRefresher::new(), policy);
let outcomes = service.refresh_due().await.expect("refresh cycle");
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Refreshed {
account_id: refreshed_account_id,
..
}] if refreshed_account_id == account_id
));
let account = store.account(account_id).expect("refreshed account");
assert_eq!(account.credential_state(), CredentialState::Ready);
assert_eq!(account.last_error_reason(), None);
assert_eq!(account.last_error_message(), None);
}
#[tokio::test]
async fn scheduled_refresh_persists_a_returned_id_token() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let refresher = SingleUseRefresher::with_id_token("header.rotated-id.signature");
let service = refresh_service(&store, refresher, policy);
let account_id = "acct_rotated_id_token";
seed_refreshable_account(
&store,
account_id,
SystemTime::now()
.checked_add(Duration::from_secs(120))
.expect("test expiry"),
None,
)
.await;
service.refresh_due().await.expect("refresh cycle");
let account = store.account(account_id).expect("refreshed account");
let loaded = store
.load_credential(account.id(), account.revision())
.await
.expect("refreshed credential");
let runtime = CodexCredentialCodec::decode(&loaded.credential).expect("runtime credential");
assert_eq!(
runtime
.authentication
.oauth()
.and_then(|oauth| oauth.id_token.as_ref())
.map(SecretString::expose_secret),
Some("header.rotated-id.signature")
);
}
#[tokio::test]
async fn scheduled_refresh_uses_the_rotated_access_token_jwt_expiration() {
let expires_at = Utc
.timestamp_opt(2_000_000_000, 0)
.single()
.expect("valid test timestamp");
let payload = URL_SAFE_NO_PAD.encode(
serde_json::to_vec(&serde_json::json!({"exp": expires_at.timestamp()}))
.expect("test JWT payload"),
);
let refresher = SingleUseRefresher::with_access_token(format!(
"unverified-header.{payload}.unverified-signature"
));
let store = Arc::new(MemoryAccountStore::default());
let service = refresh_service(
&store,
refresher,
MutableRuntimePolicy::new(Duration::from_secs(5 * 60)),
);
let account_id = "acct_rotated_access_expiration";
seed_refreshable_account(
&store,
account_id,
SystemTime::now()
.checked_add(Duration::from_secs(120))
.expect("test expiry"),
None,
)
.await;
service.refresh_due().await.expect("refresh cycle");
assert_eq!(
store
.account(account_id)
.expect("refreshed account")
.access_token_expires_at()
.map(DateTime::<Utc>::from),
Some(expires_at)
);
}
#[tokio::test]
async fn scheduled_refresh_preserves_the_stored_token_set_when_rotation_fields_are_omitted() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let refresher = SingleUseRefresher::without_rotated_tokens();
let service = refresh_service(&store, refresher, policy);
let account_id = "acct_omitted_token_rotation";
let expires_at = SystemTime::now()
.checked_add(Duration::from_secs(120))
.expect("test expiry");
seed_refreshable_account(&store, account_id, expires_at, None).await;
store.set_oauth_transport(
account_id,
provider_openai::credential::ResponsesTransport::Http,
);
service.refresh_due().await.expect("refresh cycle");
let account = store.account(account_id).expect("refreshed account");
assert_eq!(account.access_token_expires_at(), Some(expires_at));
let loaded = store
.load_credential(account.id(), account.revision())
.await
.expect("refreshed credential");
let runtime = CodexCredentialCodec::decode(&loaded.credential).expect("runtime credential");
assert_eq!(
runtime.transport,
provider_openai::credential::ResponsesTransport::Http
);
let oauth = runtime.authentication.oauth().expect("OAuth credential");
assert_eq!(
oauth.access_token.expose_secret(),
format!("access-{account_id}")
);
let expected_refresh_token = format!("rt-access-{account_id}");
assert_eq!(
oauth
.refresh_token
.as_ref()
.map(SecretString::expose_secret),
Some(expected_refresh_token.as_str())
);
}
#[tokio::test]
async fn scheduled_refresh_respects_retry_not_before_until_it_has_elapsed() {
let store = Arc::new(MemoryAccountStore::default());
let policy = MutableRuntimePolicy::new(Duration::from_secs(5 * 60));
let refresher = SingleUseRefresher::new();
let service = refresh_service(&store, Arc::clone(&refresher), policy);
let expires_at = SystemTime::now()
.checked_add(Duration::from_secs(120))
.expect("test expiry");
seed_refreshable_account(
&store,
"acct_future_retry",
expires_at,
Some(
SystemTime::now()
.checked_add(Duration::from_secs(60))
.expect("future retry"),
),
)
.await;
assert!(
service
.refresh_due()
.await
.expect("refresh cycle before retry")
.is_empty()
);
assert_eq!(refresher.calls(), 0);
seed_refreshable_account(
&store,
"acct_elapsed_retry",
expires_at,
Some(
SystemTime::now()
.checked_sub(Duration::from_secs(1))
.expect("past retry"),
),
)
.await;
let outcomes = service
.refresh_due()
.await
.expect("refresh cycle after retry");
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Refreshed {
account_id,
..
}] if account_id == "acct_elapsed_retry"
));
assert_eq!(refresher.calls(), 1);
}
struct QuotaRejectionDuringRefresh {
quota: provider_openai::credential::CodexCredentialQuotaService,
account_id: ProviderAccountId,
background_quota: bool,
failure: RefreshFailure,
}
#[async_trait]
impl TokenRefresher for QuotaRejectionDuringRefresh {
async fn refresh(&self, _: &str) -> Result<TokenPair, RefreshFailure> {
// 模拟 RT 请求在途时,手动或周期额度查询先收到 401
if self.background_quota {
assert_eq!(
self.quota.synchronize().await.expect("quota cycle").revoked,
1
);
} else {
assert!(self.quota.refresh_account(&self.account_id).await.is_err());
}
Err(self.failure.clone())
}
}
#[tokio::test]
async fn quota_revocation_during_oauth_refresh_preserves_terminal_and_retry_results() {
for (background_quota, retryable) in [(false, false), (true, false), (true, true)] {
let store = Arc::new(MemoryAccountStore::default());
let account_id = "acct_quota_during_refresh";
seed_refreshable_account(
&store,
account_id,
SystemTime::now() + Duration::from_secs(60),
None,
)
.await;
let account = store.account(account_id).expect("account");
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({
"error": {"code": "token_revoked"}
})))
.expect(1)
.mount(&server)
.await;
let quota = super::quota::quota_service_with_base_url(
&store,
reqwest::Client::builder()
.no_proxy()
.build()
.expect("client"),
server.uri(),
);
let service = CodexCredentialRefreshService::new(
store.repository(),
Arc::new(QuotaRejectionDuringRefresh {
quota,
account_id: account.id().clone(),
background_quota,
failure: if retryable {
RefreshFailure::Transport {
redacted: false,
source: None,
message: None,
upstream: None,
}
} else {
RefreshFailure::InvalidGrant {
message: Some("refresh token invalidated".to_owned()),
upstream: None,
}
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(5 * 60)),
Arc::new(crate::RecordingDiagnostics::default()),
);
let outcomes = service.refresh_due().await.expect("refresh cycle");
let current = store.account(account_id).expect("account after refresh");
if retryable {
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Transient { .. }]
));
assert!(current.next_refresh_at().is_some());
assert_eq!(current.credential_state(), CredentialState::Ready);
assert_eq!(
current
.status_projection(SystemTime::now(), None)
.error_reason,
Some(AccountErrorReason::AccessTokenExpired)
);
} else {
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Invalidated { .. }]
));
assert_eq!(current.credential_state(), CredentialState::Expired);
assert_eq!(
current.last_error_message(),
Some("refresh token invalidated")
);
}
}
}
#[tokio::test]
async fn scheduled_refresh_records_native_failure_once_and_keeps_retry_state() {
let store = Arc::new(MemoryAccountStore::default());
let diagnostics = Arc::new(crate::RecordingDiagnostics::default());
let service = CodexCredentialRefreshService::new(
store.repository(),
Arc::new(FailingRefresher {
failure: RefreshFailure::Transport {
redacted: false,
message: Some("safe transport summary".to_owned()),
upstream: None,
source: Some(std::io::Error::other("PRIVATE_OAUTH_NATIVE_CAUSE").into()),
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(300)),
diagnostics.clone(),
);
seed_refreshable_account(&store, "acct_diagnostic", SystemTime::now(), None).await;
let outcomes = service.refresh_due().await.unwrap();
assert!(matches!(
outcomes.as_slice(),
[CodexCredentialRefreshOutcome::Transient { .. }]
));
let failures = diagnostics.0.lock().unwrap();
assert_eq!(failures.len(), 1);
assert_eq!(
failures[0].account_id.as_ref().unwrap().as_str(),
"acct_diagnostic"
);
assert_eq!(failures[0].operation, "scheduled_refresh");
assert!(
failures[0]
.details
.as_ref()
.unwrap()
.as_str()
.contains("PRIVATE_OAUTH_NATIVE_CAUSE")
);
assert!(!format!("{:?}", failures[0]).contains("PRIVATE_OAUTH_NATIVE_CAUSE"));
}