diff --git a/backend/crates/providers/openai/src/credential/mod.rs b/backend/crates/providers/openai/src/credential/mod.rs index 7a1f7c0dc..230126546 100644 --- a/backend/crates/providers/openai/src/credential/mod.rs +++ b/backend/crates/providers/openai/src/credential/mod.rs @@ -10,6 +10,7 @@ mod eligibility; mod oauth; mod profile_statistics; mod quota; +mod recovery_feedback; mod recovery_log; mod refresh; mod repository; diff --git a/backend/crates/providers/openai/src/credential/recovery_feedback.rs b/backend/crates/providers/openai/src/credential/recovery_feedback.rs new file mode 100644 index 000000000..036b3d0db --- /dev/null +++ b/backend/crates/providers/openai/src/credential/recovery_feedback.rs @@ -0,0 +1,167 @@ +//! OpenAI 账号的 OAuth 拒绝记录与 Cloudflare 连续失败反馈 + +use std::collections::{HashMap, VecDeque}; +use std::time::{Duration, SystemTime}; + +use gateway_core::account::{CredentialRevision, ProviderAccountId}; + +const STALE_AFTER: Duration = Duration::from_secs(60 * 60); +const CHALLENGE_BACKOFF: [Duration; 4] = [ + Duration::from_secs(10), + Duration::from_secs(30), + Duration::from_secs(90), + Duration::from_secs(120), +]; +const PATH_BLOCK_THRESHOLD: usize = 3; + +#[derive(Default)] +pub(super) struct RecoveryFeedback { + // 跨账号条目重建仍保持顺序,较早的成功不能清除后来创建的记录 + last_observation: u64, + accounts: HashMap, +} + +struct AccountFeedback { + observed_at: SystemTime, + rejection: Option, + challenges: VecDeque, + path_blocks: VecDeque, +} + +#[derive(Clone, Copy)] +struct TokenRejection { + /// 首次被拒并交给续期的版本;后续 401 不会再授予一次续期 + refresh_requested_at: CredentialRevision, + last_observation: u64, +} + +impl AccountFeedback { + fn is_active(&self, now: SystemTime) -> bool { + !matches!(now.duration_since(self.observed_at), Ok(age) if age > STALE_AFTER) + } +} + +// 超过最大退避或失效阈值的旧失败不会再影响决策 +fn record_failure(streak: &mut VecDeque, observation: u64, limit: usize) -> usize { + if streak.len() == limit { + streak.pop_front(); + } + streak.push_back(observation); + streak.len() +} + +impl RecoveryFeedback { + fn active_account( + &mut self, + id: &ProviderAccountId, + now: SystemTime, + ) -> Option<&AccountFeedback> { + if !self.accounts.get(id)?.is_active(now) { + self.accounts.remove(id); + return None; + } + self.accounts.get(id) + } + + fn next_failure( + &mut self, + id: &ProviderAccountId, + now: SystemTime, + ) -> (u64, &mut AccountFeedback) { + self.accounts.retain(|_, state| state.is_active(now)); + self.last_observation += 1; + let state = self + .accounts + .entry(id.clone()) + .or_insert_with(|| AccountFeedback { + observed_at: now, + rejection: None, + challenges: VecDeque::new(), + path_blocks: VecDeque::new(), + }); + state.observed_at = now; + (self.last_observation, state) + } + + pub(super) fn challenge_delay( + &mut self, + id: &ProviderAccountId, + now: SystemTime, + retry_after: Option, + ) -> Duration { + let (order, state) = self.next_failure(id, now); + let count = record_failure(&mut state.challenges, order, CHALLENGE_BACKOFF.len()); + retry_after + .unwrap_or_default() + .max(CHALLENGE_BACKOFF[count - 1]) + } + + pub(super) fn path_block_reached_limit( + &mut self, + id: &ProviderAccountId, + now: SystemTime, + ) -> bool { + let (order, state) = self.next_failure(id, now); + record_failure(&mut state.path_blocks, order, PATH_BLOCK_THRESHOLD) == PATH_BLOCK_THRESHOLD + } + + pub(super) fn pending_refresh( + &mut self, + id: &ProviderAccountId, + now: SystemTime, + ) -> Option { + self.active_account(id, now)? + .rejection + .map(|rejected| rejected.refresh_requested_at) + } + + pub(super) fn record_rejection( + &mut self, + id: &ProviderAccountId, + refresh_requested_at: CredentialRevision, + now: SystemTime, + ) { + let (order, state) = self.next_failure(id, now); + if state + .rejection + .is_none_or(|rejected| rejected.refresh_requested_at <= refresh_requested_at) + { + state.rejection = Some(TokenRejection { + refresh_requested_at, + last_observation: order, + }); + } + } + + /// 在任何异步核对之前记下已观察到的失败范围 + pub(super) fn success_boundary( + &mut self, + id: &ProviderAccountId, + now: SystemTime, + ) -> Option { + self.active_account(id, now)?; + Some(self.last_observation) + } + + pub(super) fn confirm_success( + &mut self, + id: &ProviderAccountId, + through: u64, + sent: CredentialRevision, + ) { + let Some(state) = self.accounts.get_mut(id) else { + return; + }; + if state.rejection.is_some_and(|rejected| { + rejected.refresh_requested_at < sent && rejected.last_observation <= through + }) { + state.rejection = None; + } + state.challenges.retain(|order| *order > through); + state.path_blocks.retain(|order| *order > through); + if state.challenges.is_empty() && state.path_blocks.is_empty() && state.rejection.is_none() + { + self.accounts.remove(id); + } + } +} diff --git a/backend/crates/providers/openai/src/credential/selector.rs b/backend/crates/providers/openai/src/credential/selector.rs index 90ab6cbf5..64490440f 100644 --- a/backend/crates/providers/openai/src/credential/selector.rs +++ b/backend/crates/providers/openai/src/credential/selector.rs @@ -43,6 +43,7 @@ use super::codec::CodexRuntimeAuthentication; use super::cookie::CodexCookiePolicy; use super::eligibility::{CodexSelectionModel, NativeProtocol}; use super::quota::CodexCredentialQuotaService; +use super::recovery_feedback::RecoveryFeedback; use super::refresh::refresh_recovery_deadline; use super::repository::{CodexCredentialRepository, CredentialRepositoryError}; use super::scheduling_projection::{SchedulingProjectionCache, SchedulingProjectionKey}; @@ -50,14 +51,6 @@ use super::types::{ CODEX_AUTHENTICATION_KIND_OAUTH, CodexCookie, CodexCookieCaptureOutcome, RuntimeCodexCookie, }; -const CLOUDFLARE_RECOVERY_STALE_AFTER: Duration = Duration::from_secs(60 * 60); -const CLOUDFLARE_CHALLENGE_BACKOFF: [Duration; 4] = [ - Duration::from_secs(10), - Duration::from_secs(30), - Duration::from_secs(90), - Duration::from_secs(120), -]; -const CLOUDFLARE_PATH_BLOCK_THRESHOLD: u32 = 3; // 绑定失败会阻止发送,预算容纳短暂调度抖动;可丢失的策略排除记录保持独立预算 const SESSION_AFFINITY_TIMEOUT: Duration = Duration::from_millis(500); const CYBER_POLICY_TIMEOUT: Duration = Duration::from_millis(100); @@ -97,15 +90,6 @@ pub enum CodexAccountFailure { CloudflarePathBlocked, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct RiskRecoveryState { - challenge_count: u32, - path_block_count: u32, - /// 已因访问令牌被拒而交给 OAuth 续期的凭据版本 - rejected_revision: Option, - observed_at: SystemTime, -} - #[derive(Debug, Clone, Copy)] enum CookieRecovery { ExpireAt(SystemTime), @@ -158,7 +142,7 @@ pub struct CodexCredentialSelector { cooldowns: Arc, upstream_info: Arc, cookie_policy: CodexCookiePolicy, - risk_recovery: Mutex>, + recovery_feedback: Mutex, account_feedback: Arc, scheduling_projection: SchedulingProjectionCache, endpoint_protocols: @@ -336,7 +320,7 @@ impl CodexCredentialSelector { cooldowns, upstream_info, cookie_policy, - risk_recovery: Mutex::new(HashMap::new()), + recovery_feedback: Mutex::default(), waiting: ConcurrencyWaitQueue::default(), reserved_waiting: ConcurrencyWaitQueue::default(), account_feedback, @@ -2070,7 +2054,9 @@ impl CodexCredentialSelector { } // Cloudflare 挑战:内存退避表(记录风险计数),不写账号事实 CodexAccountFailure::CloudflareChallenge { retry_after } => { - let delay = self.cloudflare_challenge_delay(account.id(), now, retry_after); + let delay = self + .feedback() + .challenge_delay(account.id(), now, retry_after); let recovery = now .checked_add(delay) .map_or(CookieRecovery::Clear, CookieRecovery::ExpireAt); @@ -2079,8 +2065,7 @@ impl CodexCredentialSelector { } // Cloudflare 路径被封:连续超阈值才置 Invalid;否则内存退避 CodexAccountFailure::CloudflarePathBlocked => { - let blocked = self.record_cloudflare_path_block(account.id(), now); - if blocked >= CLOUDFLARE_PATH_BLOCK_THRESHOLD { + if self.feedback().path_block_reached_limit(account.id(), now) { self.apply_credential_state( account, CredentialState::Invalid, @@ -2141,39 +2126,14 @@ impl CodexCredentialSelector { now: SystemTime, message: Option, ) -> Result { - if account.authentication_kind() == CODEX_AUTHENTICATION_KIND_OAUTH - && account.has_refresh_token() - && account - .access_token_expires_at() - .is_some_and(|expires_at| expires_at <= now) - && refresh_recovery_deadline(account.access_token_expires_at()) - .is_some_and(|deadline| deadline > now) - { - tracing::info!( - account_id = %account.id(), - access_token_expires_at = ?account.access_token_expires_at() - .map(chrono::DateTime::::from), - recovery_deadline = ?refresh_recovery_deadline(account.access_token_expires_at()) - .map(chrono::DateTime::::from), - "OpenAI access token expired; retaining account for bounded OAuth refresh recovery" - ); - return self - .apply_credential_state( - account, - CredentialState::Ready, - AccountErrorReason::AccessTokenExpired, - now, - message, - ) - .await - .map(|()| true); - } - if account.authentication_kind() == CODEX_AUTHENTICATION_KIND_OAUTH - && account.has_refresh_token() - && account - .access_token_expires_at() - .is_some_and(|expires_at| expires_at > now) - && !self.refreshed_access_token_rejected(account, now) + let expires_at = account.access_token_expires_at().filter(|_| { + account.authentication_kind() == CODEX_AUTHENTICATION_KIND_OAUTH + && account.has_refresh_token() + }); + let pending_refresh = + expires_at.and_then(|_| self.feedback().pending_refresh(account.id(), now)); + if expires_at.is_some_and(|expiry| expiry > now) + && pending_refresh.is_none_or(|rejected| rejected >= account.revision()) { // 资源服务拒绝未到期的访问令牌不能证明 refresh token 失效 // 让访问令牌到期并交给 OAuth 续期,条件写入不影响已轮换的凭据 @@ -2186,22 +2146,42 @@ impl CodexCredentialSelector { if !expired { return Ok(false); } - self.record_rejected_access_token(account, now); + self.feedback() + .record_rejection(account.id(), account.revision(), now); tracing::info!( account_id = %account.id(), "OpenAI access token rejected before expiry; deferring to OAuth refresh" ); return Ok(true); } + let state = if expires_at.is_some_and(|expiry| expiry <= now) + && refresh_recovery_deadline(expires_at).is_some_and(|deadline| deadline > now) + { + tracing::info!( + account_id = %account.id(), + access_token_expires_at = ?expires_at + .map(chrono::DateTime::::from), + recovery_deadline = ?refresh_recovery_deadline(expires_at) + .map(chrono::DateTime::::from), + "OpenAI access token expired; retaining account for bounded OAuth refresh recovery" + ); + CredentialState::Ready + } else { + CredentialState::Expired + }; self.apply_credential_state( account, - CredentialState::Expired, + state, AccountErrorReason::AccessTokenExpired, now, message, ) - .await - .map(|()| true) + .await?; + if let Some(rejected) = pending_refresh { + self.feedback() + .record_rejection(account.id(), rejected, now); + } + Ok(true) } async fn apply_credential_state( @@ -2230,51 +2210,34 @@ impl CodexCredentialSelector { sent_revision: CredentialRevision, authentication: &CodexRuntimeAuthentication, ) { + let boundary = self + .feedback() + .success_boundary(account.id(), SystemTime::now()); let Ok(current) = self.current_account(account.id()).await else { return; }; if current.provider() != &self.provider_kind || !current.enabled() { return; } - // 凭据版本保护账号和配额写回;仅 Cookie 变化时,同一 AT 的成功仍会中断连续风控失败 - let snapshot = if current.revision() == account.revision() { + let same_revision = current.revision() == account.revision(); + if same_revision { self.restore_recoverable_account_state(¤t).await; - None - } else { - let snapshot = self - .risk_recovery - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .get(account.id().as_str()) - .copied(); - if snapshot.is_none() - || !matches!( - self.current_account_for_token(account.id(), authentication) - .await, - Ok(Some(_)) - ) - { - return; - } - snapshot - }; - let mut recovery = self - .risk_recovery - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some(state) = recovery.get_mut(account.id().as_str()) - && snapshot.is_none_or(|previous| previous == *state) - { - state.challenge_count = 0; - state.path_block_count = 0; - // 本次响应自己的 Cookie 写回不改变出站版本,旧请求也不能清除较新的拒绝 - if state - .rejected_revision - .is_none_or(|rejected| rejected < sent_revision) - { - recovery.remove(account.id().as_str()); - } } + let Some(through) = boundary else { + return; + }; + // Cookie 也会推进版本;版本不同时,只有出站 AT 仍在使用才承认这次成功 + if !same_revision + && !matches!( + self.current_account_for_token(account.id(), authentication) + .await, + Ok(Some(_)) + ) + { + return; + } + self.feedback() + .confirm_success(account.id(), through, sent_revision); } async fn current_account_for_token( @@ -2408,58 +2371,10 @@ impl CodexCredentialSelector { }) } - fn cloudflare_challenge_delay( - &self, - account_id: &ProviderAccountId, - now: SystemTime, - retry_after: Option, - ) -> Duration { - let mut recovery = self - .risk_recovery + fn feedback(&self) -> std::sync::MutexGuard<'_, RecoveryFeedback> { + self.recovery_feedback .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let state = active_risk_recovery(&mut recovery, account_id.as_str(), now); - state.challenge_count = state.challenge_count.saturating_add(1); - state.observed_at = now; - let index = usize::try_from(state.challenge_count.saturating_sub(1)) - .unwrap_or(usize::MAX) - .min(CLOUDFLARE_CHALLENGE_BACKOFF.len() - 1); - retry_after - .unwrap_or_default() - .max(CLOUDFLARE_CHALLENGE_BACKOFF[index]) - } - - fn record_cloudflare_path_block(&self, account_id: &ProviderAccountId, now: SystemTime) -> u32 { - let mut recovery = self - .risk_recovery - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let state = active_risk_recovery(&mut recovery, account_id.as_str(), now); - state.path_block_count = state.path_block_count.saturating_add(1); - state.observed_at = now; - state.path_block_count - } - - /// 续期换来的访问令牌在成功请求前再次被拒,由调用方写入凭据过期 - fn refreshed_access_token_rejected(&self, account: &ProviderAccount, now: SystemTime) -> bool { - let mut recovery = self - .risk_recovery - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let state = active_risk_recovery(&mut recovery, account.id().as_str(), now); - state - .rejected_revision - .is_some_and(|rejected| rejected < account.revision()) - } - - fn record_rejected_access_token(&self, account: &ProviderAccount, now: SystemTime) { - let mut recovery = self - .risk_recovery - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let state = active_risk_recovery(&mut recovery, account.id().as_str(), now); - state.rejected_revision = state.rejected_revision.max(Some(account.revision())); - state.observed_at = now; + .unwrap_or_else(std::sync::PoisonError::into_inner) } /// Cookie 写回不能推进正在交换 RT 的凭据版本 @@ -2521,25 +2436,6 @@ fn binding_store_error( ))) } -fn active_risk_recovery<'a>( - recovery: &'a mut HashMap, - account_id: &str, - now: SystemTime, -) -> &'a mut RiskRecoveryState { - recovery.retain(|_, state| match now.duration_since(state.observed_at) { - Ok(elapsed) => elapsed <= CLOUDFLARE_RECOVERY_STALE_AFTER, - Err(_) => true, - }); - recovery - .entry(account_id.to_owned()) - .or_insert(RiskRecoveryState { - challenge_count: 0, - path_block_count: 0, - rejected_revision: None, - observed_at: now, - }) -} - impl fmt::Debug for CodexCredentialSelector { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter diff --git a/backend/crates/providers/openai/tests/credential/contract/mod.rs b/backend/crates/providers/openai/tests/credential/contract/mod.rs index 97a84b8da..5f1f56f4c 100644 --- a/backend/crates/providers/openai/tests/credential/contract/mod.rs +++ b/backend/crates/providers/openai/tests/credential/contract/mod.rs @@ -1501,6 +1501,16 @@ fn successful_request_across_cookie_revision_only_rearms_the_same_access_token() }; reject(¤t(), "initial"); rotate("renewed"); + let block_path = |token: &str| { + block_on(selector.record_failure( + ¤t(), + &oauth_auth(token), + CodexAccountFailure::CloudflarePathBlocked, + None, + )) + .unwrap(); + }; + block_path("renewed"); let in_flight = current(); // 一条并发响应更新 Cookie,另一条流随后用原请求快照报告成功 let cookie = block_on(selector.capture_response_cookies( @@ -1513,15 +1523,20 @@ fn successful_request_across_cookie_revision_only_rearms_the_same_access_token() if token_changed { rotate("replacement"); } - block_on(selector.record_success(&in_flight, in_flight.revision(), &oauth_auth("renewed"))); - reject( - ¤t(), - if token_changed { - "replacement" - } else { - "renewed" - }, - ); + let current_token = if token_changed { + "replacement" + } else { + "renewed" + }; + let sent_auth = oauth_auth("renewed"); + let release = store.hold_next_current_credential_read(); + let mut success = + std::pin::pin!(selector.record_success(&in_flight, in_flight.revision(), &sent_auth)); + assert!(futures::FutureExt::now_or_never(success.as_mut()).is_none()); + block_path(current_token); + release.send(()).unwrap(); + block_on(success); + reject(¤t(), current_token); let after = current(); if token_changed { assert_eq!(after.credential_state(), CredentialState::Expired); @@ -1529,9 +1544,61 @@ fn successful_request_across_cookie_revision_only_rearms_the_same_access_token() assert_eq!(after.credential_state(), CredentialState::Ready); assert!(after.access_token_expires_at().unwrap() <= SystemTime::now()); } + // 同一 AT 的成功只中断核对开始前的失败,真正旧 AT 的成功不打断任何失败 + block_path(current_token); + if !token_changed { + assert_eq!(current().credential_state(), CredentialState::Ready); + block_path(current_token); + } + assert_eq!(current().credential_state(), CredentialState::Invalid); } } +#[test] +fn success_does_not_clear_a_rejection_recorded_while_verifying_the_token() { + let store = Arc::new(MemoryAccountStore::default()); + create_account(&store, "acct_primary", "original"); + let selector = selector(&store, Arc::new(TestLeaseCoordinator::default())); + let current = || store.account("acct_primary").unwrap(); + let reject = |token: &str| { + block_on(selector.record_failure( + ¤t(), + &oauth_auth(token), + CodexAccountFailure::CredentialExpired, + None, + )) + .unwrap(); + }; + reject("original"); + block_on(store.repository().rotate_refreshed_oauth_secret( + ¤t(), + secret("renewed"), + Some(SystemTime::now() + Duration::from_secs(3600)), + None, + )) + .unwrap(); + let sent = current(); + let auth = oauth_auth("renewed"); + block_on(selector.capture_response_cookies( + &sent, + &Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(), + &["__cf_bm=test; Path=/; Secure".to_owned()], + )) + .unwrap(); + + let release = store.hold_next_current_credential_read(); + let mut success = std::pin::pin!(selector.record_success(&sent, sent.revision(), &auth)); + assert!(futures::FutureExt::now_or_never(success.as_mut()).is_none()); + reject("renewed"); + assert_eq!(current().credential_state(), CredentialState::Expired); + release.send(()).unwrap(); + block_on(success); + + // 早先的成功不能重新放开续期:同一 AT 再次被拒时,到期时间仍应在未来 + reject("renewed"); + assert!(current().access_token_expires_at().unwrap() > SystemTime::now()); +} + #[test] fn credential_expired_failure_keeps_expired_oauth_for_bounded_refresh_recovery() { let store = Arc::new(MemoryAccountStore::default()); diff --git a/backend/crates/providers/openai/tests/support.rs b/backend/crates/providers/openai/tests/support.rs index eae22b230..090c0568e 100644 --- a/backend/crates/providers/openai/tests/support.rs +++ b/backend/crates/providers/openai/tests/support.rs @@ -85,6 +85,7 @@ pub(crate) struct MemoryAccountStore { pending_account_reads: bool, credential_load_hook: Mutex>>, credential_loads: AtomicUsize, + next_current_credential_read: Mutex>>, } impl gateway_core::account::UpstreamInfoSource for MemoryAccountStore { @@ -327,6 +328,12 @@ impl MemoryAccountStore { .expect("credential hook lock") = Some(hook); } + pub(crate) fn hold_next_current_credential_read(&self) -> oneshot::Sender<()> { + let (release, held) = oneshot::channel(); + *self.next_current_credential_read.lock().unwrap() = Some(held); + release + } + pub(crate) fn credential_loads(&self) -> usize { self.credential_loads.load(Ordering::SeqCst) } @@ -595,6 +602,10 @@ impl ProviderAccountStore for MemoryAccountStore { &self, account: &ProviderAccountId, ) -> Result { + let held = self.next_current_credential_read.lock().unwrap().take(); + if let Some(held) = held { + held.await.expect("release current credential read"); + } let accounts = self.accounts.lock().expect("account store lock"); let stored = accounts .get(account) diff --git a/docs/architecture.md b/docs/architecture.md index 90ae785b2..9376890d6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1152,7 +1152,8 @@ OpenAI、xAI、Antigravity 的 OAuth 认证及账号后台操作由各 Provider 到期账号的集中刷新;恢复窗口内的强制刷新不受偏移影响 - OpenAI 手工与后台续期在取得账号刷新租约后复核凭据版本,租约覆盖 RT exchange 与提交。 响应 Cookie 捕获及风控清理共用该租约,避免推进版本导致已换回的 token 无法提交。 - 模型 401 只按版本写回到期时间或账号状态;若并发写回推进版本,仅对仍在使用的同一 AT 重新处理 + 模型 401 只按版本写回到期时间或账号状态;若并发写回推进版本,仅对仍在使用的同一 AT 重新处理。 + 同一 AT 的成功响应可清除更早版本的 401 记录并中断连续风控失败;核对期间新到的失败仍然有效 - xAI 支持 OAuth session 和 Responses API Key;API Key 不执行 OAuth 刷新、身份查询或官方额度操作。OAuth 刷新额度时同步查询官方实时订阅, 只把套餐事实写入现有 quota JSON。明确无付费订阅的个人账号显示 Free;查询失败、缺失字段或 团队身份不推断为 Free,订阅查询失败不影响额度观测