diff --git a/backend/crates/providers/antigravity/src/credential/catalog.rs b/backend/crates/providers/antigravity/src/credential/catalog.rs index f80ecd4ea..f3f91f2e4 100644 --- a/backend/crates/providers/antigravity/src/credential/catalog.rs +++ b/backend/crates/providers/antigravity/src/credential/catalog.rs @@ -2,7 +2,6 @@ use crate::{ credential::{CredentialService, oauth::error}, - profile::ReleaseService, transport::{Catalog, CloudCodeClient, unsent}, }; use gateway_admin::{ @@ -29,7 +28,6 @@ pub(crate) struct CatalogService { kind: gateway_core::routing::ProviderKind, accounts: Arc, registration: String, - pub(crate) release: Arc, pub(crate) origin: url::Url, pub(crate) generation: AtomicU64, observed: @@ -109,7 +107,6 @@ impl CatalogService { credentials: Arc, registration: String, origin: url::Url, - release: Arc, ) -> Self { Self { kind, @@ -117,7 +114,6 @@ impl CatalogService { credentials, registration, origin, - release, generation: AtomicU64::new(0), observed: Mutex::default(), refresh_cursor: AtomicUsize::new(0), @@ -222,12 +218,9 @@ impl CatalogService { .credentials .material(¤t) .map_err(|e| error(AdminKind::CredentialRefreshRequired).with_source(e))?; - let client = CloudCodeClient::new( - &self.origin, - current.account.outbound_proxy(), - &crate::profile::default_profile(&self.release), - ) - .map_err(|e| error(AdminKind::Unavailable).with_source(e))?; + let profile = self.credentials.request_profile().await?; + let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile) + .map_err(|e| error(AdminKind::Unavailable).with_source(e))?; let observed_at = SystemTime::now(); let catalog = client .catalog(&material.access_token) diff --git a/backend/crates/providers/antigravity/src/credential/quota/service.rs b/backend/crates/providers/antigravity/src/credential/quota/service.rs index 4ba255507..fb238e669 100644 --- a/backend/crates/providers/antigravity/src/credential/quota/service.rs +++ b/backend/crates/providers/antigravity/src/credential/quota/service.rs @@ -4,7 +4,6 @@ use super::document::Document; use crate::{ credential::catalog::CatalogService, credential::{CredentialService, oauth::error}, - profile::ReleaseService, transport::CloudCodeClient, }; use futures::{StreamExt, stream}; @@ -35,7 +34,6 @@ pub(crate) struct QuotaService { accounts: Arc, credentials: Arc, catalog: Arc, - release: Arc, origin: url::Url, cursor: AtomicUsize, } @@ -107,7 +105,6 @@ impl QuotaService { accounts: Arc, credentials: Arc, catalog: Arc, - release: Arc, origin: url::Url, ) -> Self { Self { @@ -115,7 +112,6 @@ impl QuotaService { accounts, credentials, catalog, - release, origin, cursor: AtomicUsize::new(0), } @@ -153,12 +149,9 @@ impl QuotaService { .credentials .material(¤t) .map_err(|e| error(Kind::CredentialRefreshRequired).with_source(e))?; - let client = CloudCodeClient::new( - &self.origin, - current.account.outbound_proxy(), - &crate::profile::default_profile(&self.release), - ) - .map_err(upstream)?; + let profile = self.credentials.request_profile().await?; + let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile) + .map_err(upstream)?; // 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照 let observed_at = SystemTime::now(); let info = client diff --git a/backend/crates/providers/antigravity/src/lib.rs b/backend/crates/providers/antigravity/src/lib.rs index 9c318a5a1..aa0bd4bbd 100644 --- a/backend/crates/providers/antigravity/src/lib.rs +++ b/backend/crates/providers/antigravity/src/lib.rs @@ -32,14 +32,12 @@ pub fn initialize(ports: ProviderStorePorts) -> Result ProviderAdminError }) => (Kind::Unavailable, "无法连接授权服务,请检查出站连接"), Error::Exchange(Exchange::Unavailable) => (Kind::Unavailable, "授权服务暂不可用"), Error::StorageUnavailable => (Kind::Unavailable, "授权状态存储暂不可用"), + Error::Profile(_) => (Kind::Unavailable, "授权客户端身份暂不可用"), }; provider_admin_error(kind) .with_public_message(message) @@ -169,6 +170,7 @@ pub(super) const fn oauth_error_code(error: &CodexOAuthAdminError) -> &'static s }) => "connect_failed", CodexOAuthAdminError::Exchange(Exchange::Ambiguous { .. }) => "ambiguous", CodexOAuthAdminError::StorageUnavailable => "storage_unavailable", + CodexOAuthAdminError::Profile(_) => "profile_unavailable", CodexOAuthAdminError::Credential => "credential", } } @@ -179,7 +181,7 @@ pub(super) fn map_quota_error(error: CodexCredentialQuotaError) -> ProviderAdmin let (kind, public_message, upstream_message) = match error { Error::Profile(source) => { return provider_admin_error(Kind::Unavailable) - .with_public_message("预热客户端身份不可用") + .with_public_message("客户端身份不可用") .with_source(source); } Error::InvalidCredentialData => (Kind::Invalid, "凭据或额度数据无效", None), diff --git a/backend/crates/providers/openai/src/credential/oauth.rs b/backend/crates/providers/openai/src/credential/oauth.rs index a7dd88d09..33926811c 100644 --- a/backend/crates/providers/openai/src/credential/oauth.rs +++ b/backend/crates/providers/openai/src/credential/oauth.rs @@ -15,6 +15,7 @@ use gateway_admin::model::{ use gateway_core::account::{ LoadedCredential, NewProviderAccount, ProviderAccountId, ProviderAccountStore, }; +use gateway_core::provider_ports::ProviderRuntimePolicyPort; use secrecy::{ExposeSecret, SecretString}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq as _; @@ -32,13 +33,12 @@ use super::token_client::{ OFFICIAL_CODEX_OAUTH_CLIENT_ID, OFFICIAL_CODEX_REDIRECT_URI, }; use super::types::{parse_access_token_expiration, parse_chatgpt_jwt_claims}; -use crate::profile::CodexWireProfileState; +use crate::profile::{CodexWireProfile, CodexWireProfileState}; const AUTHORIZATION_ENDPOINT: &str = "https://auth.openai.com/oauth/authorize"; const DESKTOP_AUTH_ENDPOINT: &str = "https://chatgpt.com/codex/desktop-auth"; const AUTHORIZATION_SCOPE: &str = "openid profile email offline_access api.connectors.read api.connectors.invoke"; -const AUTHORIZATION_ORIGINATOR: &str = "Codex Desktop"; const STREAMLINED_LOGIN_QUERY: &str = "codex_streamlined_login"; const NO_UNIVERSAL_LINKS_QUERY: &str = "no_universal_links"; const SURFACE_STABLE_ID_DOMAIN: &[u8] = b"openai/codex-desktop/surface-stable-id/v1\0"; @@ -336,6 +336,8 @@ pub enum CodexOAuthAdminError { Exchange(#[source] AuthorizationCodeExchangeError), #[error("Codex OAuth pending storage is unavailable")] StorageUnavailable, + #[error("Codex OAuth client profile is unavailable")] + Profile(#[source] gateway_core::error::ErrorSource), #[error("Codex OAuth account mutation failed")] Credential, } @@ -360,6 +362,7 @@ pub struct CodexOAuthAdminService { credentials: CodexCredentialAdmin, oauth_client_id: String, profile: CodexWireProfileState, + runtime_policy: Arc, } struct CodexOAuthAuthorizationCommitGuard { @@ -408,6 +411,7 @@ impl CodexOAuthAdminService { store: Arc, credentials: CodexCredentialAdmin, profile: CodexWireProfileState, + runtime_policy: Arc, ) -> Self { Self { pending, @@ -416,6 +420,7 @@ impl CodexOAuthAdminService { credentials, oauth_client_id: OFFICIAL_CODEX_OAUTH_CLIENT_ID.to_owned(), profile, + runtime_policy, } } @@ -603,9 +608,12 @@ impl CodexOAuthAdminService { mutation, }) .map_err(map_pending_error)?; - let profile = self.profile.snapshot(); - let authorization_url = - authorization_url(&pending, &self.oauth_client_id, &profile.desktop_version)?; + let profile = self + .profile + .resolve_global_request_profile(self.runtime_policy.as_ref()) + .await + .map_err(CodexOAuthAdminError::Profile)?; + let authorization_url = authorization_url(&pending, &self.oauth_client_id, &profile)?; self.pending .create(&pending) .await @@ -736,11 +744,8 @@ fn derive_surface_stable_id(installation_id: &str) -> Result Result { - if !valid_text(desktop_version) { - return Err(CodexOAuthAdminError::InvalidInput); - } let mut inner = Url::parse(AUTHORIZATION_ENDPOINT).map_err(|_| CodexOAuthAdminError::InvalidInput)?; let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest( @@ -759,8 +764,11 @@ fn authorization_url( .append_pair("scope", AUTHORIZATION_SCOPE) .append_pair("id_token_add_organizations", "true") .append_pair("codex_cli_simplified_flow", "true") - .append_pair("originator", AUTHORIZATION_ORIGINATOR) - .append_pair("codex_app_version", desktop_version) + .append_pair("originator", &profile.originator); + if !profile.desktop_version.is_empty() { + query.append_pair("codex_app_version", &profile.desktop_version); + } + query .append_pair("source_surface_stable_id", &stable_id) .append_pair("codex_origin_stable_id", &stable_id) .append_pair(STREAMLINED_LOGIN_QUERY, "true"); diff --git a/backend/crates/providers/openai/src/credential/profile_statistics.rs b/backend/crates/providers/openai/src/credential/profile_statistics.rs index c80b81d64..87d21db49 100644 --- a/backend/crates/providers/openai/src/credential/profile_statistics.rs +++ b/backend/crates/providers/openai/src/credential/profile_statistics.rs @@ -2,11 +2,12 @@ use std::{ collections::HashMap, - sync::Mutex, + sync::{Arc, Mutex}, time::{Duration, Instant, SystemTime}, }; use gateway_core::account::ProviderAccountId; +use gateway_core::provider_ports::ProviderRuntimePolicyPort; use reqwest::Client; use secrecy::{ExposeSecret as _, SecretString}; use thiserror::Error; @@ -108,6 +109,7 @@ struct CachedProfileAvatarSource { pub struct CodexCredentialProfileService { repository: CodexCredentialRepository, profile: CodexWireProfileState, + runtime_policy: Arc, http: Client, base_url: String, avatar_sources: Mutex>, @@ -120,16 +122,34 @@ impl CodexCredentialProfileService { profile: CodexWireProfileState, http: Client, base_url: String, + runtime_policy: Arc, ) -> Self { Self { repository, profile, http, base_url, + runtime_policy, avatar_sources: Mutex::new(HashMap::new()), } } + async fn global_profile_client( + &self, + ) -> Result { + let profile = self + .profile + .resolve_global_request_profile(self.runtime_policy.as_ref()) + .await + .map_err(|_| CodexProfileStatisticsError::TransportUnavailable)?; + Ok(CodexBackendClient::new( + self.http.clone(), + self.base_url.clone(), + self.profile.clone(), + ) + .with_request_profile(profile)) + } + /// 订阅只按需读取;不缓存、不刷新凭据,也不更新额度状态 pub async fn subscription( &self, @@ -141,23 +161,21 @@ impl CodexCredentialProfileService { return Ok(None); }; let request_id = format!("subscription_{}", Uuid::now_v7().simple()); - let subscription = CodexBackendClient::new( - self.http.clone(), - self.base_url.clone(), - self.profile.clone(), - ) - .for_account(&account) - .map_err(map_client_error)? - .fetch_subscription( - CodexRequestContext::auxiliary( - authorization.expose_secret(), - Some(&upstream_account_id), - &request_id, - None, - ), - &upstream_account_id, - ) - .await; + let subscription = self + .global_profile_client() + .await? + .for_account(&account) + .map_err(map_client_error)? + .fetch_subscription( + CodexRequestContext::auxiliary( + authorization.expose_secret(), + Some(&upstream_account_id), + &request_id, + None, + ), + &upstream_account_id, + ) + .await; // 请求期间重新授权、换绑或删除账号时,丢弃旧身份的结果 let current = self .repository @@ -183,32 +201,35 @@ impl CodexCredentialProfileService { ) -> Result { let (authorization, upstream_account_id, account) = self.account_authentication(account_id).await?; - self.fetch_profile_statistics(&authorization, upstream_account_id.as_deref(), &account) - .await + let client = self.global_profile_client().await?; + self.fetch_profile_statistics( + &client, + &authorization, + upstream_account_id.as_deref(), + &account, + ) + .await } async fn fetch_profile_statistics( &self, + client: &CodexBackendClient, authorization: &SecretString, upstream_account_id: Option<&str>, account: &gateway_core::account::ProviderAccount, ) -> Result { let request_id = format!("profile_statistics_{}", Uuid::now_v7().simple()); - let statistics = CodexBackendClient::new( - self.http.clone(), - self.base_url.clone(), - self.profile.clone(), - ) - .for_account(account) - .map_err(map_client_error)? - .fetch_profile_statistics(CodexRequestContext::auxiliary( - authorization.expose_secret(), - upstream_account_id, - &request_id, - None, - )) - .await - .map_err(map_client_error)?; + let statistics = client + .for_account(account) + .map_err(map_client_error)? + .fetch_profile_statistics(CodexRequestContext::auxiliary( + authorization.expose_secret(), + upstream_account_id, + &request_id, + None, + )) + .await + .map_err(map_client_error)?; self.remember_avatar_source( crate::request_identity::oauth_identity_key(account), statistics.image_url.as_deref(), @@ -268,12 +289,18 @@ impl CodexCredentialProfileService { ) -> Result { let (authorization, upstream_account_id, account) = self.account_authentication(account_id).await?; + let client = self.global_profile_client().await?; let source = match self .cached_avatar_source(&crate::request_identity::oauth_identity_key(&account)) { Some(source) => source, None => self - .fetch_profile_statistics(&authorization, upstream_account_id.as_deref(), &account) + .fetch_profile_statistics( + &client, + &authorization, + upstream_account_id.as_deref(), + &account, + ) .await? .image_url .ok_or(CodexProfileAvatarError::Missing)?, @@ -290,7 +317,7 @@ impl CodexCredentialProfileService { fetch_profile_avatar( &http, &self.base_url, - &self.profile.snapshot(), + &client.profile_state().snapshot(), &source, CodexRequestContext::auxiliary( authorization.expose_secret(), diff --git a/backend/crates/providers/openai/src/credential/quota/bucket_warmup.rs b/backend/crates/providers/openai/src/credential/quota/bucket_warmup.rs index 8da70d944..14750a92c 100644 --- a/backend/crates/providers/openai/src/credential/quota/bucket_warmup.rs +++ b/backend/crates/providers/openai/src/credential/quota/bucket_warmup.rs @@ -231,17 +231,7 @@ impl CodexCredentialQuotaService { .await?; return Ok(None); }; - let profile = self - .profile - .resolve_global_request_profile(self.runtime_policy.as_ref()) - .await - .map_err(CodexCredentialQuotaError::Profile)?; - let client = CodexBackendClient::new( - self.http.clone(), - self.base_url.clone(), - self.profile.clone(), - ) - .with_request_profile(profile); + let client = self.global_profile_client().await?; // 先持久化领取再发请求;超时、取消或重启后不重放结果不明的推理 // 通用窗口共享请求用量,同批到期窗口只发一次轻量请求 for (key, _, reset) in &due { diff --git a/backend/crates/providers/openai/src/credential/quota/mod.rs b/backend/crates/providers/openai/src/credential/quota/mod.rs index ab0ef63ef..18c1581e7 100644 --- a/backend/crates/providers/openai/src/credential/quota/mod.rs +++ b/backend/crates/providers/openai/src/credential/quota/mod.rs @@ -145,7 +145,7 @@ pub struct CodexWarmupSummary { #[derive(Debug, Error)] pub enum CodexCredentialQuotaError { - #[error("Codex warmup client profile is unavailable")] + #[error("Codex quota client profile is unavailable")] Profile(#[source] gateway_core::error::ErrorSource), #[error("Codex quota response is invalid")] InvalidCredentialData, diff --git a/backend/crates/providers/openai/src/credential/quota/reset_credits.rs b/backend/crates/providers/openai/src/credential/quota/reset_credits.rs index c8d0f49b6..fe3a2d00d 100644 --- a/backend/crates/providers/openai/src/credential/quota/reset_credits.rs +++ b/backend/crates/providers/openai/src/credential/quota/reset_credits.rs @@ -126,11 +126,10 @@ impl CodexCredentialQuotaService { account_id: &ProviderAccountId, ) -> Result { let account = self.reset_credit_account(account_id).await?; - let client = CodexBackendClient::new( - self.http.clone(), - self.base_url.clone(), - self.profile.clone(), - ); + let client = self + .global_profile_client() + .await + .map_err(|_| CodexResetCreditsError::TransportUnavailable)?; let credential = self .repository .load_runtime_credential(&account) @@ -157,11 +156,10 @@ impl CodexCredentialQuotaService { let entry = self.reset_consume_locks.entry(account_id); let _guard = entry.lock().await; let account = self.reset_credit_account(account_id).await?; - let client = CodexBackendClient::new( - self.http.clone(), - self.base_url.clone(), - self.profile.clone(), - ); + let client = self + .global_profile_client() + .await + .map_err(|_| CodexResetCreditsError::TransportUnavailable)?; let credential = self .repository .load_runtime_credential(&account) diff --git a/backend/crates/providers/openai/src/credential/quota/service.rs b/backend/crates/providers/openai/src/credential/quota/service.rs index 80a0cb51d..0e8c43873 100644 --- a/backend/crates/providers/openai/src/credential/quota/service.rs +++ b/backend/crates/providers/openai/src/credential/quota/service.rs @@ -35,6 +35,22 @@ fn upstream_error_status(error: &CodexClientError) -> Option { } impl CodexCredentialQuotaService { + pub(super) async fn global_profile_client( + &self, + ) -> Result { + let profile = self + .profile + .resolve_global_request_profile(self.runtime_policy.as_ref()) + .await + .map_err(CodexCredentialQuotaError::Profile)?; + Ok(CodexBackendClient::new( + self.http.clone(), + self.base_url.clone(), + self.profile.clone(), + ) + .with_request_profile(profile)) + } + pub fn new( repository: CodexCredentialRepository, profile: CodexWireProfileState, @@ -174,11 +190,17 @@ impl CodexCredentialQuotaService { if accounts.is_empty() { return Ok(summary); } - let client = CodexBackendClient::new( - self.http.clone(), - self.base_url.clone(), - self.profile.clone(), - ); + let client = match self.global_profile_client().await { + Ok(client) => client, + Err(error) => { + // 身份配置失败尚未发出请求,也需要释放已预留的首查任务 + self.scheduling.defer_failed_initial_refreshes( + &pending_initial, + self.initial_sync_delays.as_ref(), + ); + return Err(error); + } + }; for account in accounts { let observed_at = SystemTime::now(); match self.fetch_usage(&client, &account).await { @@ -410,11 +432,7 @@ impl CodexCredentialQuotaService { if !access_token_is_current(&account, observed_at) { return Err(CodexCredentialQuotaError::CredentialRefreshRequired); } - let client = CodexBackendClient::new( - self.http.clone(), - self.base_url.clone(), - self.profile.clone(), - ); + let client = self.global_profile_client().await?; let FetchedCodexQuota { account, value } = match self.fetch_usage(&client, &account).await { Ok(fetched) => fetched, Err(CodexQuotaFetchError::InvalidCredential) => { diff --git a/backend/crates/providers/openai/src/credential/quota/warmup.rs b/backend/crates/providers/openai/src/credential/quota/warmup.rs index caeff8b31..5909c8133 100644 --- a/backend/crates/providers/openai/src/credential/quota/warmup.rs +++ b/backend/crates/providers/openai/src/credential/quota/warmup.rs @@ -140,17 +140,7 @@ impl CodexCredentialQuotaService { }) .collect::>(); - let profile = self - .profile - .resolve_global_request_profile(self.runtime_policy.as_ref()) - .await - .map_err(CodexCredentialQuotaError::Profile)?; - let client = CodexBackendClient::new( - self.http.clone(), - self.base_url.clone(), - self.profile.clone(), - ) - .with_request_profile(profile); + let client = self.global_profile_client().await?; for account in accounts { if account.quota().is_exhausted() { diff --git a/backend/crates/providers/openai/src/credential/token_client.rs b/backend/crates/providers/openai/src/credential/token_client.rs index 8770731fe..bad31550b 100644 --- a/backend/crates/providers/openai/src/credential/token_client.rs +++ b/backend/crates/providers/openai/src/credential/token_client.rs @@ -8,10 +8,12 @@ use crate::transport::{ tls::{build_reqwest_client_with_custom_ca, ensure_rustls_provider}, }; use async_trait::async_trait; +use gateway_core::provider_ports::ProviderRuntimePolicyPort; use reqwest::{Client, StatusCode, redirect::Policy}; use secrecy::{ExposeSecret, SecretString}; use serde::{Deserialize, Serialize}; use std::fmt; +use std::sync::Arc; use std::time::Duration; const MAX_OAUTH_RESPONSE_BYTES: usize = 64 * 1024; @@ -386,6 +388,7 @@ pub struct OpenAiTokenClient { client: Client, config: TokenClientConfig, profile: CodexWireProfileState, + runtime_policy: Arc, } /// 官方 Codex token client 无法安全构建 @@ -408,14 +411,23 @@ impl OpenAiTokenClient { .timeout(TOKEN_REQUEST_TIMEOUT); let client = build_reqwest_client_with_custom_ca(builder).map_err(|_| TokenClientBuildError)?; - Ok(Self::new(client, self.config.clone(), self.profile.clone())) + Ok(Self { + client, + ..self.clone() + }) } - /// 共享运行时画像;刷新时取快照,授权码交换仍使用 raw auth 请求 - pub fn new(client: Client, config: TokenClientConfig, profile: CodexWireProfileState) -> Self { + /// 认证请求按执行时的全局配置解析身份 + pub fn new( + client: Client, + config: TokenClientConfig, + profile: CodexWireProfileState, + runtime_policy: Arc, + ) -> Self { Self { client, config, profile, + runtime_policy, } } @@ -439,7 +451,12 @@ impl OpenAiTokenClient { endpoint.set_path(PERSONAL_ACCESS_TOKEN_WHOAMI_PATH); endpoint.set_query(None); endpoint.set_fragment(None); - let headers = build_codex_profile_headers(&self.profile.snapshot()) + let profile = self + .profile + .resolve_global_request_profile(self.runtime_policy.as_ref()) + .await + .map_err(|_| PersonalAccessTokenError::Unavailable)?; + let headers = build_codex_profile_headers(&profile) .map_err(|_| PersonalAccessTokenError::Unavailable)?; let client = self .with_proxy(proxy) @@ -495,6 +512,7 @@ impl OpenAiTokenClient { pub fn openai_token_client( config: TokenClientConfig, profile: CodexWireProfileState, + runtime_policy: Arc, ) -> Result { ensure_rustls_provider(); let builder = gateway_egress::http_client(None) @@ -503,7 +521,12 @@ pub fn openai_token_client( .connect_timeout(TOKEN_CONNECT_TIMEOUT) .timeout(TOKEN_REQUEST_TIMEOUT); let client = build_reqwest_client_with_custom_ca(builder).map_err(|_| TokenClientBuildError)?; - Ok(OpenAiTokenClient::new(client, config, profile)) + Ok(OpenAiTokenClient::new( + client, + config, + profile, + runtime_policy, + )) } #[derive(Deserialize)] @@ -591,14 +614,22 @@ impl TokenRefresher for OpenAiTokenClient { .await } async fn refresh(&self, refresh_token: &str) -> Result { - let headers = build_codex_profile_headers(&self.profile.snapshot()).map_err(|source| { - RefreshFailure::Transport { + let profile = self + .profile + .resolve_global_request_profile(self.runtime_policy.as_ref()) + .await + .map_err(|source| RefreshFailure::RetryableTransport { + redacted: false, + source: Some(source), + message: "OpenAI OAuth refresh profile is unavailable".to_owned(), + })?; + let headers = + build_codex_profile_headers(&profile).map_err(|source| RefreshFailure::Transport { redacted: false, source: Some(source.into()), message: Some("OpenAI OAuth refresh profile is invalid".to_owned()), upstream: None, - } - })?; + })?; let response = self .client .post(&self.config.token_endpoint) @@ -642,9 +673,17 @@ impl AuthorizationCodeExchanger for OpenAiTokenClient { &self, grant: AuthorizationCodeGrant, ) -> Result { + let profile = self + .profile + .resolve_global_request_profile(self.runtime_policy.as_ref()) + .await + .map_err(|_| AuthorizationCodeExchangeError::Unavailable)?; + let headers = build_codex_profile_headers(&profile) + .map_err(|_| AuthorizationCodeExchangeError::Unavailable)?; let response = self .client .post(&self.config.token_endpoint) + .headers(headers) .form(&[ ("grant_type", "authorization_code"), ("client_id", self.config.client_id.as_str()), diff --git a/backend/crates/providers/openai/src/lib.rs b/backend/crates/providers/openai/src/lib.rs index e71d84af2..d196dc497 100644 --- a/backend/crates/providers/openai/src/lib.rs +++ b/backend/crates/providers/openai/src/lib.rs @@ -162,6 +162,7 @@ pub async fn initialize( profile.clone(), http.clone(), config.base_url().to_owned(), + Arc::clone(&runtime_policy), )); let selector = Arc::new(CodexCredentialSelector::new( provider_kind.clone(), @@ -197,6 +198,7 @@ pub async fn initialize( credential::token_client::openai_token_client( config.token_client_config(), profile.clone(), + Arc::clone(&runtime_policy), ) .map_err(|_| OpenAiInitializeError::TokenClient)?, ); @@ -230,6 +232,7 @@ pub async fn initialize( Arc::clone(&accounts), CodexCredentialAdmin, profile.clone(), + Arc::clone(&runtime_policy), ) .with_oauth_client_id(config.oauth_client_id()), ); diff --git a/backend/crates/providers/openai/src/profile/identity.rs b/backend/crates/providers/openai/src/profile/identity.rs index d9279ab81..35b66fe81 100644 --- a/backend/crates/providers/openai/src/profile/identity.rs +++ b/backend/crates/providers/openai/src/profile/identity.rs @@ -18,7 +18,7 @@ pub(super) const USER_AGENT_PRODUCTS: [&str; 4] = ["Codex Desktop", "codex-tui", "codex_exec", "codex_cli_rs"]; impl CodexWireProfileState { - /// 后台模型操作没有 Client Key,按当前全局选择冻结整套身份 + /// 账号后台操作没有 Client Key,按当前全局选择冻结整套身份 pub(crate) async fn resolve_global_request_profile( &self, policy: &dyn ProviderRuntimePolicyPort, diff --git a/backend/crates/providers/openai/src/profile/state.rs b/backend/crates/providers/openai/src/profile/state.rs index f860f6902..7f6c662ba 100644 --- a/backend/crates/providers/openai/src/profile/state.rs +++ b/backend/crates/providers/openai/src/profile/state.rs @@ -105,6 +105,10 @@ impl CodexWireProfile { /// 复合 User-Agent 是两个独立 surface #[must_use] pub fn desktop_user_agent(&self) -> String { + // 非 Desktop 预设及完整自定义 UA 没有独立桌面格式,保持所选身份 + if self.client_kind != ClientKind::Desktop || self.exact_user_agent.is_some() { + return self.user_agent(); + } format!( "{}/{} ({}; {})", self.originator, self.desktop_version, self.os_type, self.arch diff --git a/backend/crates/providers/openai/src/transport/headers.rs b/backend/crates/providers/openai/src/transport/headers.rs index 9cebddc09..2225db3a5 100644 --- a/backend/crates/providers/openai/src/transport/headers.rs +++ b/backend/crates/providers/openai/src/transport/headers.rs @@ -59,7 +59,7 @@ pub fn build_codex_model_headers( Ok(headers) } -/// Core 默认客户端身份,用于模型接口及 OAuth refresh;raw token exchange 不使用 +/// 客户端身份头供模型接口和服务端认证请求共用,不携带账号凭据 pub fn build_codex_profile_headers(profile: &CodexWireProfile) -> CodexClientResult { let mut headers = HeaderMap::new(); headers.insert( diff --git a/backend/crates/providers/openai/tests/credential/admin.rs b/backend/crates/providers/openai/tests/credential/admin.rs index eaaa6f027..fc51add23 100644 --- a/backend/crates/providers/openai/tests/credential/admin.rs +++ b/backend/crates/providers/openai/tests/credential/admin.rs @@ -389,6 +389,7 @@ fn pat_service(server: &MockServer) -> CodexCredentialAdminService { token_endpoint: format!("{}/oauth/token", server.uri()), }, provider_openai::profile::CodexWireProfileState::new(Default::default()), + runtime_policy(), ) .expect("auth client"); CodexCredentialAdminService::new( @@ -505,6 +506,7 @@ async fn pat_import_times_out_without_falling_back_to_document_identity() { token_endpoint: format!("{}/oauth/token", server.uri()), }, provider_openai::profile::CodexWireProfileState::new(Default::default()), + runtime_policy(), ); let service = CodexCredentialAdminService::new( Arc::new(UnusedRefresher), diff --git a/backend/crates/providers/openai/tests/credential/oauth.rs b/backend/crates/providers/openai/tests/credential/oauth.rs index aa7d31cd0..0a39b0248 100644 --- a/backend/crates/providers/openai/tests/credential/oauth.rs +++ b/backend/crates/providers/openai/tests/credential/oauth.rs @@ -171,6 +171,7 @@ async fn complete_with_name( Arc::new(MemoryAccountStore::default()), CodexCredentialAdmin, profile(), + crate::support::runtime_policy(), ); let started = service .start_authorization(StartCodexOAuthAuthorization { @@ -228,6 +229,11 @@ async fn authorize_url_matches_the_official_desktop_parameter_contract() { Arc::new(MemoryAccountStore::default()), CodexCredentialAdmin, wire_profile, + Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new( + gateway_core::account::OpaqueProviderData::new(serde_json::json!({ + "client": "desktop", "platform": "macos", "versionMode": "latest", "osVersion": "27.0.1" + }).as_object().unwrap().clone()), + ))), ); let started = service .start_authorization(StartCodexOAuthAuthorization { @@ -379,6 +385,54 @@ async fn authorize_url_matches_the_official_desktop_parameter_contract() { assert!(!parameters.contains_key("nonce")); } +#[tokio::test] +async fn authorization_uses_global_cli_metadata_and_rejects_invalid_configuration() { + let document = |value: serde_json::Value| { + gateway_core::account::OpaqueProviderData::new(value.as_object().unwrap().clone()) + }; + let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new( + document( + serde_json::json!({"client":"cli","platform":"macos","versionMode":"fixed","codexVersion":"0.170.0"}), + ), + ))); + let service = CodexOAuthAdminService::new( + Arc::new(PendingStore::default()), + Arc::new(Exchanger { + id_token: "unused".into(), + }), + Arc::new(MemoryAccountStore::default()), + CodexCredentialAdmin, + profile(), + policy.clone(), + ); + let started = service + .start_authorization(StartCodexOAuthAuthorization { + mutation: mutation(), + }) + .await + .unwrap(); + let outer = Url::parse(&started.authorization_url).unwrap(); + let inner = outer + .query_pairs() + .find(|(name, _)| name == "authorize_url") + .unwrap() + .1 + .into_owned(); + let inner = Url::parse(&inner).unwrap(); + let parameters: std::collections::BTreeMap<_, _> = inner.query_pairs().into_owned().collect(); + assert_eq!(parameters["originator"], "codex_cli_rs"); + assert!(!parameters.contains_key("codex_app_version")); + *policy.0.lock().unwrap() = document(serde_json::json!({"client":"unsupported"})); + assert!(matches!( + service + .start_authorization(StartCodexOAuthAuthorization { + mutation: mutation() + }) + .await, + Err(CodexOAuthAdminError::Profile(_)) + )); +} + fn profile() -> CodexWireProfileState { provider_openai::profile::CodexWireProfileState::new(Default::default()) } @@ -395,6 +449,7 @@ async fn separate_new_authorizations_use_distinct_surface_stable_ids() { Arc::new(MemoryAccountStore::default()), CodexCredentialAdmin, profile(), + crate::support::runtime_policy(), ); let started = service .start_authorization(StartCodexOAuthAuthorization { @@ -452,6 +507,7 @@ async fn repeated_reauthorization_preserves_surface_id_with_a_cleared_name() { store.clone(), CodexCredentialAdmin, profile(), + crate::support::runtime_policy(), ); let started = service .start_authorization(StartCodexOAuthAuthorization { @@ -510,6 +566,7 @@ async fn reauthorization_binds_the_selected_slot_to_the_new_oauth_account() { store, CodexCredentialAdmin, profile(), + crate::support::runtime_policy(), ); let started = service .start_authorization(StartCodexOAuthAuthorization { diff --git a/backend/crates/providers/openai/tests/credential/profile_statistics.rs b/backend/crates/providers/openai/tests/credential/profile_statistics.rs index dc04c8b0e..444b5d44b 100644 --- a/backend/crates/providers/openai/tests/credential/profile_statistics.rs +++ b/backend/crates/providers/openai/tests/credential/profile_statistics.rs @@ -13,6 +13,60 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; use crate::support::{MemoryAccountStore, profile, secret}; +#[tokio::test] +async fn profile_subscription_and_avatar_follow_global_identity_changes() { + let server = MockServer::start().await; + let (store, _) = service("acct_global_profile", &server).await; + let account = store.account("acct_global_profile").unwrap(); + for (endpoint, body) in [ + ( + "/api/codex/profiles/me", + json!({"profile":{"profile_picture_url":"https://chatgpt.com/backend-api/estuary/public_content/enc/avatar-token="},"stats":{}}), + ), + ("/backend-api/subscriptions", json!({"will_renew":true})), + ] { + Mock::given(path(endpoint)) + .respond_with(ResponseTemplate::new(200).set_body_json(body)) + .mount(&server) + .await; + } + Mock::given(path("/estuary/public_content/enc/avatar-token=")) + .respond_with(ResponseTemplate::new(200).set_body_raw("", "image/svg+xml")) + .mount(&server) + .await; + let policy = Arc::new(crate::support::RequestProfileRuntimePolicy( + std::sync::Mutex::new(gateway_core::account::OpaqueProviderData::new( + Default::default(), + )), + )); + let service = CodexCredentialProfileService::new( + store.repository(), + wire_profile(), + reqwest::Client::builder().no_proxy().build().unwrap(), + server.uri(), + policy.clone(), + ); + for os in ["27.0.1", "27.0.2"] { + let ua = format!("codex_cli_rs/0.170.0 (Mac OS {os}; arm64) global-test"); + *policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new( + json!({"mode":"custom","userAgent":ua}) + .as_object() + .unwrap() + .clone(), + ); + let before = server.received_requests().await.unwrap().len(); + service.profile_statistics(account.id()).await.unwrap(); + service.subscription(account.id()).await.unwrap(); + let mut avatar = service.profile_avatar(account.id()).await.unwrap(); + while avatar.body.try_next().await.unwrap().is_some() {} + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len() - before, 3); + for request in &requests[before..] { + assert_eq!(request.headers["user-agent"], ua); + } + } +} + fn wire_profile() -> CodexWireProfileState { CodexWireProfileState::new(CodexWireProfile { client_kind: provider_openai::profile::selection::ClientKind::Desktop, @@ -58,6 +112,7 @@ async fn service( .build() .expect("client"), server.uri(), + crate::support::runtime_policy(), ); (store, service) } diff --git a/backend/crates/providers/openai/tests/credential/quota/mod.rs b/backend/crates/providers/openai/tests/credential/quota/mod.rs index 79e34bcf0..73c7aa287 100644 --- a/backend/crates/providers/openai/tests/credential/quota/mod.rs +++ b/backend/crates/providers/openai/tests/credential/quota/mod.rs @@ -33,6 +33,74 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; use crate::support::{MemoryAccountStore, profile, secret}; +#[tokio::test] +async fn quota_background_operations_use_current_global_identity_and_recover_from_invalid_profile() +{ + use gateway_core::account::OpaqueProviderData; + let server = MockServer::start().await; + for (endpoint, body) in [ + ( + "/api/codex/usage", + json!({"rate_limit":{"allowed":true,"primary_window":{"used_percent":10}}}), + ), + ( + "/api/codex/rate-limit-reset-credits", + json!({"available_count":0,"credits":[]}), + ), + ( + "/api/codex/rate-limit-reset-credits/consume", + json!({"code":"reset","credit":{"id":"test-credit","reset_type":"codex_rate_limits"}}), + ), + ] { + Mock::given(path(endpoint)) + .respond_with(ResponseTemplate::new(200).set_body_json(body)) + .mount(&server) + .await; + } + let store = Arc::new(MemoryAccountStore::default()); + create_account(&store, "acct_global_identity").await; + let account = store.account("acct_global_identity").unwrap(); + let document = + |value: serde_json::Value| OpaqueProviderData::new(value.as_object().unwrap().clone()); + let policy = Arc::new(crate::support::RequestProfileRuntimePolicy( + std::sync::Mutex::new(document(json!({"mode":"custom","userAgent":"invalid"}))), + )); + let service = CodexCredentialQuotaService::new( + store.repository(), + wire_profile(), + reqwest::Client::builder().no_proxy().build().unwrap(), + server.uri(), + Arc::new(crate::support::MemoryCooldownPort::new()), + policy.clone(), + ) + .with_initial_sync_delays(Arc::new(|| Duration::ZERO)); + assert!(matches!( + service.synchronize().await, + Err(CodexCredentialQuotaError::Profile(_)) + )); + assert!(server.received_requests().await.unwrap().is_empty()); + for os in ["27.0.1", "27.0.2"] { + let ua = format!("codex_cli_rs/0.170.0 (Mac OS {os}; arm64) global-test"); + *policy.0.lock().unwrap() = document(json!({"mode":"custom","userAgent":ua})); + let before = server.received_requests().await.unwrap().len(); + if os == "27.0.1" { + assert_eq!(service.synchronize().await.unwrap().updated, 1); + } else { + service.refresh_account(account.id()).await.unwrap(); + } + service.list_reset_credits(account.id()).await.unwrap(); + service + .consume_reset_credit(account.id(), Some("test-credit"), uuid::Uuid::new_v4()) + .await + .unwrap(); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len() - before, 3); + for request in &requests[before..] { + assert_eq!(request.headers["user-agent"], ua); + } + } +} + fn wire_profile() -> CodexWireProfileState { CodexWireProfileState::new(CodexWireProfile { client_kind: provider_openai::profile::selection::ClientKind::Desktop, diff --git a/backend/crates/providers/openai/tests/credential/refresh.rs b/backend/crates/providers/openai/tests/credential/refresh.rs index 635528181..ae1ebab5a 100644 --- a/backend/crates/providers/openai/tests/credential/refresh.rs +++ b/backend/crates/providers/openai/tests/credential/refresh.rs @@ -614,6 +614,7 @@ async fn scheduled_refresh_persists_retryable_message_inside_the_two_hour_window token_endpoint: format!("{}/oauth/token", server.uri()), }, provider_openai::profile::CodexWireProfileState::new(Default::default()), + crate::support::runtime_policy(), )), Arc::new(RefreshLeases), Arc::new(RefreshCredentialState), diff --git a/backend/crates/providers/openai/tests/credential/token_client.rs b/backend/crates/providers/openai/tests/credential/token_client.rs index 3e172af4d..032a237cc 100644 --- a/backend/crates/providers/openai/tests/credential/token_client.rs +++ b/backend/crates/providers/openai/tests/credential/token_client.rs @@ -49,7 +49,7 @@ async fn refresh_and_code_exchange_use_the_selected_account_proxy() { } #[tokio::test] -async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange() { +async fn authentication_requests_track_global_identity_and_releases() { let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/oauth/token")) @@ -60,18 +60,33 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange() .mount(&server) .await; let profile = provider_openai::profile::CodexWireProfileState::new(Default::default()); + let policy = std::sync::Arc::new(crate::support::RequestProfileRuntimePolicy( + std::sync::Mutex::new(gateway_core::account::OpaqueProviderData::new( + Default::default(), + )), + )); let client = provider_openai::credential::token_client::openai_token_client( TokenClientConfig { client_id: "audit-client".to_owned(), token_endpoint: format!("{}/oauth/token", server.uri()), }, profile.clone(), + policy.clone(), ) .expect("production auth transport"); - for (core, desktop, build) in [ - ("1.2.3", "26.800.10000", "8000"), - ("1.2.4", "26.901.10000", "8109"), + for (core, desktop, build, os_version) in [ + ("1.2.3", "26.800.10000", "8000", "27.0.1"), + ("1.2.4", "26.901.10000", "8109", "27.0.2"), ] { + *policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new( + serde_json::json!({ + "client": "desktop", "platform": "macos", "versionMode": "latest", + "osVersion": os_version + }) + .as_object() + .unwrap() + .clone(), + ); profile.update_bundled_release(&provider_openai::profile::CodexBundledReleaseProfile { codex_version: core.to_owned(), desktop_version: desktop.to_owned(), @@ -91,7 +106,9 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange() let exchange = &requests[requests.len() - 1]; assert_eq!( refresh.headers["user-agent"], - profile.snapshot().user_agent() + format!( + "Codex Desktop/{core} (Mac OS {os_version}; arm64) unknown (Codex Desktop; {desktop})" + ) ); assert_eq!(refresh.headers["originator"], "Codex Desktop"); assert_eq!(refresh.headers["content-type"], "application/json"); @@ -99,18 +116,32 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange() exchange.headers["content-type"], "application/x-www-form-urlencoded" ); - for name in [ - "originator", - "user-agent", - "version", - "x-openai-internal-codex-residency", - ] { - assert!(!exchange.headers.contains_key(name), "raw exchange: {name}"); - } - for name in ["authorization", "chatgpt-account-id", "version"] { - assert!(!refresh.headers.contains_key(name), "refresh: {name}"); + assert_eq!( + exchange.headers["user-agent"], + refresh.headers["user-agent"] + ); + assert_eq!(exchange.headers["originator"], "Codex Desktop"); + for request in [refresh, exchange] { + for name in ["authorization", "chatgpt-account-id", "version"] { + assert!(!request.headers.contains_key(name), "auth request: {name}"); + } } } + *policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(Default::default()); + assert!(matches!( + client.refresh("audit-refresh").await, + Err(RefreshFailure::RetryableTransport { .. }) + )); + assert!(matches!( + client + .exchange_authorization_code(AuthorizationCodeGrant { + code: SecretString::from("audit-code"), + code_verifier: SecretString::from("audit-verifier") + }) + .await, + Err(AuthorizationCodeExchangeError::Unavailable) + )); + assert_eq!(server.received_requests().await.unwrap().len(), 4); } fn client(server: &MockServer) -> OpenAiTokenClient { @@ -124,6 +155,7 @@ fn client(server: &MockServer) -> OpenAiTokenClient { token_endpoint: format!("{}/oauth/token", server.uri()), }, provider_openai::profile::CodexWireProfileState::new(Default::default()), + crate::support::runtime_policy(), ) } @@ -392,6 +424,7 @@ async fn authorization_code_response_timeouts_remain_ambiguous_without_exposing_ token_endpoint: format!("http://{address}/oauth/token?PRIVATE_URL_MARKER"), }, provider_openai::profile::CodexWireProfileState::new(Default::default()), + crate::support::runtime_policy(), ); let error = client .exchange_authorization_code(AuthorizationCodeGrant { diff --git a/backend/crates/providers/xai/src/admin/error.rs b/backend/crates/providers/xai/src/admin/error.rs index ff1ee1f72..27606a356 100644 --- a/backend/crates/providers/xai/src/admin/error.rs +++ b/backend/crates/providers/xai/src/admin/error.rs @@ -94,6 +94,11 @@ pub(super) fn map_quota_error(error: GrokQuotaError) -> ProviderAdminError { Error::InvalidData => (Kind::Invalid, "凭据或额度数据无效"), Error::Upstream => (Kind::Unavailable, "额度查询失败"), Error::Store => (Kind::Unavailable, "额度查询暂不可用"), + Error::Profile(source) => { + return provider_error(Kind::Unavailable) + .with_public_message("客户端身份不可用") + .with_source(source); + } }; provider_error(kind).with_public_message(message) } @@ -108,6 +113,11 @@ pub(super) fn map_catalog_error(error: GrokCredentialCatalogError) -> ProviderAd Error::StaleCredentialSnapshot => (Kind::Conflict, "凭据已更新,请刷新账号列表"), Error::Upstream => (Kind::Unavailable, "模型查询失败"), Error::Cache | Error::Store => (Kind::Unavailable, "模型查询暂不可用"), + Error::Profile(source) => { + return provider_error(Kind::Unavailable) + .with_public_message("客户端身份不可用") + .with_source(source); + } }; provider_error(kind).with_public_message(message) } diff --git a/backend/crates/providers/xai/src/credential/catalog.rs b/backend/crates/providers/xai/src/credential/catalog.rs index 384c7e9bf..4b1217410 100644 --- a/backend/crates/providers/xai/src/credential/catalog.rs +++ b/backend/crates/providers/xai/src/credential/catalog.rs @@ -12,6 +12,7 @@ use gateway_core::account::{ }; use gateway_core::provider_ports::{ ProviderCatalogCacheKey, ProviderCatalogCachePort, ProviderCatalogScope, + ProviderRuntimePolicyPort, }; use gateway_core::routing::{ProviderCatalogGeneration, ProviderKind}; @@ -348,6 +349,8 @@ pub enum GrokCredentialCatalogError { ConflictingModelFacts, #[error("Grok model catalog cache update failed")] Cache, + #[error("Grok client profile is unavailable")] + Profile(#[source] gateway_core::error::ErrorSource), #[error("Grok provider account store is unavailable")] Store, } @@ -359,6 +362,7 @@ pub struct GrokCredentialCatalogService { cache: Arc, published: Arc>, wire_profile: XaiWireProfileState, + runtime_policy: Arc, } /// 同一目录模型可由多个套餐的成员账号发现 @@ -377,6 +381,7 @@ impl GrokCredentialCatalogService { transport: Arc, cache: Arc, wire_profile: XaiWireProfileState, + runtime_policy: Arc, ) -> Self { Self { repository, @@ -384,6 +389,7 @@ impl GrokCredentialCatalogService { cache, published: Arc::new(RwLock::new(PublishedCatalogState::default())), wire_profile, + runtime_policy, } } @@ -578,12 +584,18 @@ impl GrokCredentialCatalogService { candidates: Vec, ) -> Result { let mut last_error = None; + let profile = XaiWireProfileState::new( + self.wire_profile + .resolve_global_request_profile(self.runtime_policy.as_ref()) + .await + .map_err(GrokCredentialCatalogError::Profile)?, + ); for candidate in candidates.into_iter().take(MAX_CATALOG_FETCH_ATTEMPTS) { match fetch_candidate_catalog( Arc::clone(&self.client), scope.clone(), candidate, - self.wire_profile.clone(), + profile.clone(), ) .await { diff --git a/backend/crates/providers/xai/src/credential/client.rs b/backend/crates/providers/xai/src/credential/client.rs index 1298f7916..5c4234984 100644 --- a/backend/crates/providers/xai/src/credential/client.rs +++ b/backend/crates/providers/xai/src/credential/client.rs @@ -2,12 +2,14 @@ use std::sync::Arc; +use gateway_core::provider_ports::ProviderRuntimePolicyPort; + use crate::credential::token::{parse_oauth_error, parse_refresh_success, parse_token_success}; use crate::{ AllowedRedirectUri, AuthorizationCodeGrant, DiscoveryDocument, FormField, GrokOAuthConfig, - HttpHeader, OAuthError, OAuthHttpRequest, OAuthHttpResponse, OAuthHttpTransport, - OAuthOperation, OAuthPrincipal, PendingAuthorization, RefreshTokenGrant, RefreshedTokenSet, - TokenCandidate, TokenVerificationContext, TokenVerifier, VerificationFailure, VerificationFlow, + OAuthError, OAuthHttpRequest, OAuthHttpResponse, OAuthHttpTransport, OAuthOperation, + OAuthPrincipal, PendingAuthorization, RefreshTokenGrant, RefreshedTokenSet, TokenCandidate, + TokenVerificationContext, TokenVerifier, VerificationFailure, VerificationFlow, VerificationMethod, VerifiedTokenSet, }; @@ -16,6 +18,7 @@ use crate::{ pub struct GrokOAuthClient { config: GrokOAuthConfig, wire_profile: crate::XaiWireProfileState, + runtime_policy: Arc, transport: Arc, verifier: Arc, outbound_proxy: Option, @@ -29,12 +32,14 @@ impl GrokOAuthClient { wire_profile: crate::XaiWireProfileState, transport: Arc, verifier: Arc, + runtime_policy: Arc, ) -> Self { Self { config, wire_profile, transport, verifier, + runtime_policy, outbound_proxy: None, } } @@ -59,10 +64,11 @@ impl GrokOAuthClient { /// transport 失败、非成功状态、JSON 非法、issuer 不匹配、端点跨 origin、 /// 缺少 JWKS 或算法不安全时返回错误 pub async fn discover(&self) -> Result { + let profile = self.request_profile(OAuthOperation::Discovery).await?; let response = self .execute( OAuthOperation::Discovery, - OAuthHttpRequest::get(self.config.discovery_url()), + OAuthHttpRequest::get(self.config.discovery_url()).with_profile(&profile), ) .await?; if !is_success(&response) { @@ -101,10 +107,13 @@ impl GrokOAuthClient { discovery: &DiscoveryDocument, grant: AuthorizationCodeGrant, ) -> Result { + let profile = self + .request_profile(OAuthOperation::AuthorizationCodeToken) + .await?; let (code, redirect_uri, code_verifier, nonce) = grant.into_parts(); let request = OAuthHttpRequest::post( discovery.token_endpoint().clone(), - vec![self.version_header()], + vec![], vec![ FormField::public("grant_type", "authorization_code"), FormField::secret("code", code), @@ -114,7 +123,10 @@ impl GrokOAuthClient { ], ); let response = self - .execute(OAuthOperation::AuthorizationCodeToken, request) + .execute( + OAuthOperation::AuthorizationCodeToken, + request.with_profile(&profile), + ) .await?; if !is_success(&response) { return Err(parse_oauth_error( @@ -144,7 +156,9 @@ impl GrokOAuthClient { let evidence = self .verifier .verify( - context.with_outbound_proxy(self.outbound_proxy.as_ref()), + context + .with_outbound_proxy(self.outbound_proxy.as_ref()) + .with_wire_profile(&profile), candidate, ) .await?; @@ -172,6 +186,9 @@ impl GrokOAuthClient { candidate: crate::GrokOAuthImportCandidate, ) -> Result { let validated = candidate.validate(&self.config, chrono::Utc::now())?; + let profile = self + .request_profile(OAuthOperation::CredentialImport) + .await?; let scope = validated.scope; let mut tokens = validated.tokens; let flow = if validated.requires_refresh { @@ -180,7 +197,11 @@ impl GrokOAuthClient { .take() .ok_or(crate::GrokOAuthImportError::InvalidField("refresh_token"))?; let refreshed = self - .refresh(discovery, &RefreshTokenGrant::new(refresh_token.clone())) + .refresh_with_profile( + discovery, + &RefreshTokenGrant::new(refresh_token.clone()), + &profile, + ) .await?; tokens = crate::credential::token::UnverifiedTokenSet { access_token: refreshed.access_token().clone(), @@ -214,7 +235,9 @@ impl GrokOAuthClient { let evidence = self .verifier .verify( - context.with_outbound_proxy(self.outbound_proxy.as_ref()), + context + .with_outbound_proxy(self.outbound_proxy.as_ref()) + .with_wire_profile(&profile), verification_candidate, ) .await @@ -250,6 +273,16 @@ impl GrokOAuthClient { &self, discovery: &DiscoveryDocument, grant: &RefreshTokenGrant, + ) -> Result { + let profile = self.request_profile(OAuthOperation::RefreshToken).await?; + self.refresh_with_profile(discovery, grant, &profile).await + } + + async fn refresh_with_profile( + &self, + discovery: &DiscoveryDocument, + grant: &RefreshTokenGrant, + profile: &crate::XaiWireProfile, ) -> Result { let form = vec![ FormField::public("grant_type", "refresh_token"), @@ -259,11 +292,8 @@ impl GrokOAuthClient { let response = self .execute( OAuthOperation::RefreshToken, - OAuthHttpRequest::post( - discovery.token_endpoint().clone(), - vec![self.version_header()], - form, - ), + OAuthHttpRequest::post(discovery.token_endpoint().clone(), vec![], form) + .with_profile(profile), ) .await?; if !is_success(&response) { @@ -284,8 +314,19 @@ impl GrokOAuthClient { .map_err(|failure| OAuthError::transport(operation, failure)) } - fn version_header(&self) -> HttpHeader { - HttpHeader::new("x-grok-client-version", self.wire_profile.client_version()) + async fn request_profile( + &self, + operation: OAuthOperation, + ) -> Result { + self.wire_profile + .resolve_global_request_profile(self.runtime_policy.as_ref()) + .await + .map_err(|_| { + OAuthError::transport( + operation, + crate::TransportFailure::new(crate::TransportFailureKind::NotSent), + ) + }) } } diff --git a/backend/crates/providers/xai/src/credential/oidc_verifier.rs b/backend/crates/providers/xai/src/credential/oidc_verifier.rs index 792939263..99d560bab 100644 --- a/backend/crates/providers/xai/src/credential/oidc_verifier.rs +++ b/backend/crates/providers/xai/src/credential/oidc_verifier.rs @@ -161,7 +161,9 @@ impl ReqwestOidcTokenVerifier { return Err(VerificationFailure::Rejected); } let kid = header.kid.as_deref().ok_or(VerificationFailure::Rejected)?; - let key = self.decoding_key(context.jwks_uri(), kid, egress).await?; + let key = self + .decoding_key(context.jwks_uri(), kid, egress, context.wire_profile()) + .await?; let mut validation = Validation::new(Algorithm::ES256); validation.leeway = 0; @@ -221,11 +223,12 @@ impl ReqwestOidcTokenVerifier { if !valid_bearer_token(access_token) { return Err(VerificationFailure::Rejected); } - let response = egress + let request = egress .client .get(context.userinfo_endpoint().clone()) .header(ACCEPT, "application/json") - .bearer_auth(access_token) + .bearer_auth(access_token); + let response = with_profile(request, context.wire_profile()) .send() .await .map_err(|_| VerificationFailure::Unavailable)?; @@ -253,6 +256,7 @@ impl ReqwestOidcTokenVerifier { jwks_uri: &Url, kid: &str, egress: &OidcEgress, + profile: Option<&crate::XaiWireProfile>, ) -> Result { if !valid_key_id(kid) { return Err(VerificationFailure::Rejected); @@ -270,7 +274,7 @@ impl ReqwestOidcTokenVerifier { } // fresh cache 未命中 kid 时只强制刷新一次,以支持官方密钥轮换 - let keys = self.fetch_jwks(jwks_uri, &egress.client).await?; + let keys = self.fetch_jwks(jwks_uri, &egress.client, profile).await?; cache.replace(jwks_uri.clone(), keys); return cache .keys @@ -280,7 +284,7 @@ impl ReqwestOidcTokenVerifier { } // 过期缓存不会在网络或协议失败时作为 stale fallback 使用 - let keys = self.fetch_jwks(jwks_uri, &egress.client).await?; + let keys = self.fetch_jwks(jwks_uri, &egress.client, profile).await?; cache.replace(jwks_uri.clone(), keys); cache .keys @@ -293,13 +297,15 @@ impl ReqwestOidcTokenVerifier { &self, jwks_uri: &Url, client: &Client, + profile: Option<&crate::XaiWireProfile>, ) -> Result, VerificationFailure> { if !self.endpoint_policy.validate_jwks(jwks_uri) { return Err(VerificationFailure::Rejected); } - let response = client + let request = client .get(jwks_uri.clone()) - .header(ACCEPT, "application/json") + .header(ACCEPT, "application/json"); + let response = with_profile(request, profile) .send() .await .map_err(|_| VerificationFailure::Unavailable)?; @@ -318,6 +324,18 @@ impl ReqwestOidcTokenVerifier { } } +fn with_profile( + request: reqwest::RequestBuilder, + profile: Option<&crate::XaiWireProfile>, +) -> reqwest::RequestBuilder { + match profile { + Some(profile) => request + .header("user-agent", profile.user_agent()) + .header("x-grok-client-version", &profile.client_version), + None => request, + } +} + impl TokenVerifier for ReqwestOidcTokenVerifier { fn verify<'a>( &'a self, diff --git a/backend/crates/providers/xai/src/credential/quota.rs b/backend/crates/providers/xai/src/credential/quota.rs index 0697a4d9d..939b6a1c5 100644 --- a/backend/crates/providers/xai/src/credential/quota.rs +++ b/backend/crates/providers/xai/src/credential/quota.rs @@ -10,6 +10,7 @@ use gateway_core::account::{ AccountQuotaResetWindow, AccountQuotaSignals, CredentialRevision, ProviderAccount, ProviderAccountId, QuotaObservation, QuotaResetPeriod, QuotaState, }; +use gateway_core::provider_ports::ProviderRuntimePolicyPort; use tokio::sync::Mutex; use super::repository::{GrokCredentialRepository, LoadedGrokCredential}; @@ -145,7 +146,7 @@ impl GrokQuotaSnapshot { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, Clone, thiserror::Error)] pub enum GrokQuotaError { #[error("xAI quota account is unavailable")] AccountUnavailable, @@ -155,6 +156,8 @@ pub enum GrokQuotaError { InvalidData, #[error("xAI quota upstream request failed")] Upstream, + #[error("xAI quota client profile is unavailable")] + Profile(#[source] gateway_core::error::ErrorSource), #[error("xAI quota store is unavailable")] Store, } @@ -166,6 +169,7 @@ pub struct GrokCredentialQuotaService { client: Arc, scheduling: GrokQuotaSchedulingProjection, wire_profile: XaiWireProfileState, + runtime_policy: Arc, } #[derive(Clone, Default)] @@ -346,12 +350,14 @@ impl GrokCredentialQuotaService { repository: GrokCredentialRepository, transport: Arc, wire_profile: XaiWireProfileState, + runtime_policy: Arc, ) -> Self { Self { repository, client: Arc::new(GrokBillingClient::new(transport)), scheduling: GrokQuotaSchedulingProjection::default(), wire_profile, + runtime_policy, } } @@ -420,7 +426,13 @@ impl GrokCredentialQuotaService { { return Err(GrokQuotaError::AccountUnavailable); } - let session = billing_session(&loaded, &self.wire_profile)?; + let profile = XaiWireProfileState::new( + self.wire_profile + .resolve_global_request_profile(self.runtime_policy.as_ref()) + .await + .map_err(GrokQuotaError::Profile)?, + ); + let session = billing_session(&loaded, &profile)?; let billing = self .client .fetch(&session) diff --git a/backend/crates/providers/xai/src/credential/verification.rs b/backend/crates/providers/xai/src/credential/verification.rs index 2bb1ef194..f3d78cb38 100644 --- a/backend/crates/providers/xai/src/credential/verification.rs +++ b/backend/crates/providers/xai/src/credential/verification.rs @@ -91,6 +91,7 @@ pub struct TokenVerificationContext<'a> { signing_algorithms: &'a [String], expected_nonce: Option<&'a SecretValue>, outbound_proxy: Option<&'a gateway_core::account::OutboundProxy>, + wire_profile: Option<&'a crate::XaiWireProfile>, } impl<'a> TokenVerificationContext<'a> { @@ -112,9 +113,22 @@ impl<'a> TokenVerificationContext<'a> { signing_algorithms, expected_nonce, outbound_proxy: None, + wire_profile: None, } } + /// 认证验证沿用当前 OAuth 操作已冻结的全局客户端身份 + #[must_use] + pub fn with_wire_profile(mut self, profile: &'a crate::XaiWireProfile) -> Self { + self.wire_profile = Some(profile); + self + } + + #[must_use] + pub fn wire_profile(&self) -> Option<&crate::XaiWireProfile> { + self.wire_profile + } + /// 绑定 OAuth owner 选择的账号出口,供公开的 [`TokenVerifier`] 实现遵守同一代理合同 /// 出口只决定路由,不改变 issuer、JWKS、签名和 nonce 的信任校验 #[must_use] diff --git a/backend/crates/providers/xai/src/lib.rs b/backend/crates/providers/xai/src/lib.rs index 96caabb59..9331361d2 100644 --- a/backend/crates/providers/xai/src/lib.rs +++ b/backend/crates/providers/xai/src/lib.rs @@ -129,11 +129,13 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result = Arc::new(GrokAccountSessionSelector::new( provider_kind.clone(), @@ -162,6 +164,7 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result = Arc::new(GrokOAuthRefreshClient::new(Arc::clone(&oauth))); diff --git a/backend/crates/providers/xai/src/oauth_http.rs b/backend/crates/providers/xai/src/oauth_http.rs index 4ceed9635..142d01684 100644 --- a/backend/crates/providers/xai/src/oauth_http.rs +++ b/backend/crates/providers/xai/src/oauth_http.rs @@ -129,6 +129,14 @@ pub struct OAuthHttpRequest { } impl OAuthHttpRequest { + pub(crate) fn with_profile(mut self, profile: &crate::XaiWireProfile) -> Self { + self.headers.extend([ + HttpHeader::new("x-grok-client-version", &profile.client_version), + HttpHeader::new("user-agent", profile.user_agent()), + ]); + self + } + pub fn get(url: Url) -> Self { Self { method: HttpMethod::Get, diff --git a/backend/crates/providers/xai/src/profile/state.rs b/backend/crates/providers/xai/src/profile/state.rs index 83b917092..2cd613ff6 100644 --- a/backend/crates/providers/xai/src/profile/state.rs +++ b/backend/crates/providers/xai/src/profile/state.rs @@ -47,6 +47,20 @@ impl XaiWireProfile { pub struct XaiWireProfileState(Arc>); impl XaiWireProfileState { + /// 账号后台操作按当前全局配置冻结身份,不读取 Client Key 覆盖 + pub(crate) async fn resolve_global_request_profile( + &self, + policy: &dyn gateway_core::provider_ports::ProviderRuntimePolicyPort, + ) -> Result { + let kind = gateway_core::routing::ProviderKind::new("xai")?; + let Some(configuration) = policy.load_request_profile(&kind).await? else { + return Ok(self.snapshot()); + }; + super::selection::GrokClientProfileSelection::parse(&configuration) + .and_then(|selection| selection.resolve(self)) + .map_err(Into::into) + } + #[must_use] pub fn new(profile: XaiWireProfile) -> Self { Self(Arc::new(RwLock::new(profile))) diff --git a/backend/crates/providers/xai/src/transport/catalog.rs b/backend/crates/providers/xai/src/transport/catalog.rs index 8e270aa0c..a51d7588e 100644 --- a/backend/crates/providers/xai/src/transport/catalog.rs +++ b/backend/crates/providers/xai/src/transport/catalog.rs @@ -126,6 +126,7 @@ impl GrokModelCatalogRequest { session.wire_profile.client_version(), ), GrokHeader::public("x-grok-client-mode", session.wire_profile.client_mode()), + GrokHeader::public("user-agent", session.wire_profile.user_agent()), GrokHeader::public("accept", "application/json"), ]; if let Some(email) = &session.email { @@ -289,6 +290,7 @@ impl GrokBillingRequest { session.wire_profile.client_version(), ), GrokHeader::public("x-grok-client-mode", session.wire_profile.client_mode()), + GrokHeader::public("user-agent", session.wire_profile.user_agent()), GrokHeader::public("accept", "application/json"), ]; if let Some(email) = &session.email { diff --git a/backend/crates/providers/xai/tests/credential/catalog.rs b/backend/crates/providers/xai/tests/credential/catalog.rs index 9b40227eb..da8274ced 100644 --- a/backend/crates/providers/xai/tests/credential/catalog.rs +++ b/backend/crates/providers/xai/tests/credential/catalog.rs @@ -27,6 +27,103 @@ use crate::support::{ const CLI_PROXY_FIXTURE: &[u8] = include_bytes!("../transport/catalog/fixtures/cli_proxy_models.json"); +#[tokio::test] +async fn catalog_billing_and_subscription_use_current_global_identity() { + use provider_xai::profile::selection::{GrokClientProfileSelection, VersionMode}; + use provider_xai::{ + GrokBillingRequest, GrokBillingTransport, GrokBillingTransportFuture, + GrokBillingTransportResponse, GrokCredentialCatalogService, GrokCredentialQuotaService, + }; + #[derive(Default)] + struct RecordingTransport(Mutex>>); + impl RecordingTransport { + fn record(&self, headers: &[provider_xai::GrokHeader]) { + self.0.lock().unwrap().push( + headers + .iter() + .filter(|h| matches!(h.name(), "user-agent" | "x-grok-client-version")) + .map(|h| (h.name().to_owned(), h.value().expose().to_owned())) + .collect(), + ); + } + } + impl GrokModelCatalogTransport for RecordingTransport { + fn execute(&self, request: GrokModelCatalogRequest) -> GrokModelCatalogTransportFuture<'_> { + self.record(request.headers()); + Box::pin(async { + Ok(GrokModelCatalogTransportResponse::new( + CLI_PROXY_FIXTURE, + None, + )) + }) + } + } + impl GrokBillingTransport for RecordingTransport { + fn execute(&self, request: GrokBillingRequest) -> GrokBillingTransportFuture<'_> { + self.record(request.headers()); + Box::pin(async { + Ok(GrokBillingTransportResponse::new( + br#"{"config":{"creditUsagePercent":25},"subscriptionTier":"SuperGrokPro"}"#, + )) + }) + } + } + let store = MemoryProviderAccountStore::shared(); + seed_input(&store, &create_input("global_profile", "global-subject")) + .await + .unwrap(); + let repository = GrokCredentialRepository::new(store); + let selected = |version: &str| { + GrokClientProfileSelection { + version_mode: VersionMode::Fixed, + client_version: Some(version.into()), + target_os: "windows".into(), + target_arch: "arm64".into(), + ..Default::default() + } + .document() + .unwrap() + }; + let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new( + selected("9.8.7"), + ))); + let transport = Arc::new(RecordingTransport::default()); + let catalog = GrokCredentialCatalogService::new( + repository.clone(), + transport.clone(), + Arc::new(MemoryGrokCatalogCache::default()), + crate::support::xai_wire_profile(), + policy.clone(), + ); + let quota = GrokCredentialQuotaService::new( + repository, + transport.clone(), + crate::support::xai_wire_profile(), + policy.clone(), + ); + for version in ["9.8.7", "9.8.8"] { + *policy.0.lock().unwrap() = selected(version); + catalog + .refresh_account_catalog(&account_id("global_profile")) + .await + .unwrap(); + quota + .refresh_account(&account_id("global_profile")) + .await + .unwrap(); + let mut requests = transport.0.lock().unwrap(); + assert_eq!(requests.len(), 3); + for headers in requests.drain(..) { + let header = |name| headers.iter().find(|h| h.0 == name).unwrap().1.as_str(); + assert_eq!( + header("user-agent"), + format!("grok-shell/{version} (windows; aarch64)") + ); + assert_eq!(header("x-grok-client-version"), version); + } + } +} + struct QueueCatalogTransport { calls: AtomicUsize, responses: diff --git a/backend/crates/providers/xai/tests/credential/client.rs b/backend/crates/providers/xai/tests/credential/client.rs index 0d09ba6d8..439b7ccd8 100644 --- a/backend/crates/providers/xai/tests/credential/client.rs +++ b/backend/crates/providers/xai/tests/credential/client.rs @@ -21,6 +21,80 @@ const DISCOVERY: &[u8] = include_bytes!("fixtures/discovery.json"); const TOKEN_SUCCESS: &[u8] = include_bytes!("fixtures/token_success.json"); const REFRESH_SUCCESS: &[u8] = include_bytes!("fixtures/refresh_success.json"); +#[tokio::test] +async fn oauth_discovery_exchange_and_refresh_use_current_global_identity() { + use provider_xai::profile::selection::{GrokClientProfileSelection, VersionMode}; + let selected = |version: &str| { + GrokClientProfileSelection { + version_mode: VersionMode::Fixed, + client_version: Some(version.to_owned()), + target_os: "windows".into(), + target_arch: "arm64".into(), + ..Default::default() + } + .document() + .unwrap() + }; + let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new( + selected("9.8.7"), + ))); + let transport = Arc::new(FixtureTransport::new(vec![ + response(200, DISCOVERY), + response(200, TOKEN_SUCCESS), + response(200, REFRESH_SUCCESS), + ])); + let client = GrokOAuthClient::new( + config(), + crate::support::xai_wire_profile(), + transport.clone(), + Arc::new(FixtureVerifier), + policy.clone(), + ); + let discovery = client.discover().await.unwrap(); + let allowlist = + RedirectUriAllowlist::new(["https://gateway.example/oauth/grok/callback"]).unwrap(); + let pending = client + .start_authorization_code( + &discovery, + allowlist + .authorize("https://gateway.example/oauth/grok/callback") + .unwrap(), + None, + ) + .unwrap(); + let state = state_from_authorization_url(&pending); + let grant = pending + .accept_callback( + AuthorizationCallback::parse(&format!("code=fixture-code&state={state}")).unwrap(), + ) + .unwrap(); + client + .exchange_authorization_code(&discovery, grant) + .await + .unwrap(); + *policy.0.lock().unwrap() = selected("9.8.8"); + let grant = RefreshTokenGrant::new(SecretValue::new("refresh-test")); + client.refresh(&discovery, &grant).await.unwrap(); + for (request, version) in transport.requests().iter().zip(["9.8.7", "9.8.7", "9.8.8"]) { + let header = |name| { + request + .headers() + .iter() + .find(|h| h.name() == name) + .unwrap() + .value() + }; + assert_eq!( + header("user-agent"), + format!("grok-shell/{version} (windows; aarch64)") + ); + assert_eq!(header("x-grok-client-version"), version); + } + *policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(Default::default()); + assert!(client.refresh(&discovery, &grant).await.is_err()); + assert_eq!(transport.requests().len(), 3); +} + struct FixtureTransport { responses: Mutex>>, requests: Mutex>, @@ -92,6 +166,7 @@ async fn credential_import_should_require_exact_metadata_and_official_userinfo() crate::support::xai_wire_profile(), transport, Arc::new(FixtureVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("discovery succeeds"); let now = chrono::Utc::now(); @@ -157,6 +232,7 @@ async fn expired_import_should_refresh_then_require_authoritative_userinfo() { crate::support::xai_wire_profile(), transport.clone(), Arc::new(FixtureVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("discovery succeeds"); let now = chrono::Utc::now(); @@ -203,6 +279,7 @@ async fn credential_import_should_reject_non_official_client_before_verification crate::support::xai_wire_profile(), transport, Arc::new(FixtureVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("discovery succeeds"); let now = chrono::Utc::now(); @@ -260,6 +337,7 @@ async fn authorization_code_flow_should_verify_before_returning_tokens() { crate::support::xai_wire_profile(), transport.clone(), Arc::new(FixtureVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("discovery succeeds"); let allowlist = RedirectUriAllowlist::new(["https://gateway.example/oauth/grok/callback"]) @@ -305,6 +383,7 @@ async fn authorization_code_flow_should_fail_closed_without_verifier() { crate::support::xai_wire_profile(), transport, Arc::new(FailClosedTokenVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("discovery succeeds"); let allowlist = RedirectUriAllowlist::new(["https://gateway.example/oauth/grok/callback"]) @@ -344,6 +423,7 @@ async fn refresh_should_preserve_ambiguous_send_classification() { crate::support::xai_wire_profile(), transport, Arc::new(FailClosedTokenVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("discovery succeeds"); let grant = RefreshTokenGrant::new(SecretValue::new( @@ -369,6 +449,7 @@ async fn refresh_should_return_rotated_token_without_id_token() { crate::support::xai_wire_profile(), transport, Arc::new(FailClosedTokenVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("discovery succeeds"); let grant = RefreshTokenGrant::new(SecretValue::new( diff --git a/backend/crates/providers/xai/tests/credential/import.rs b/backend/crates/providers/xai/tests/credential/import.rs index 81c0d9ef6..d2eacd6d7 100644 --- a/backend/crates/providers/xai/tests/credential/import.rs +++ b/backend/crates/providers/xai/tests/credential/import.rs @@ -66,6 +66,7 @@ async fn expired_access_token_requires_official_refresh_before_identity_verifica crate::support::xai_wire_profile(), transport.clone(), Arc::new(FailClosedTokenVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("official discovery fixture"); let error = client @@ -125,6 +126,7 @@ async fn verified_import_inside_refresh_margin_should_not_persist_a_refresh_sche crate::support::xai_wire_profile(), Arc::new(DiscoveryTransport), Arc::new(AcceptingUserInfoVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("official discovery fixture"); let tokens = client @@ -351,6 +353,7 @@ async fn verify(candidate: GrokOAuthImportCandidate) -> GrokOAuthImportError { crate::support::xai_wire_profile(), Arc::new(DiscoveryTransport), Arc::new(FailClosedTokenVerifier), + crate::support::runtime_policy(), ); let discovery = client.discover().await.expect("official discovery fixture"); client diff --git a/backend/crates/providers/xai/tests/credential/oidc_verifier.rs b/backend/crates/providers/xai/tests/credential/oidc_verifier.rs index cc4d3fddc..d4675138f 100644 --- a/backend/crates/providers/xai/tests/credential/oidc_verifier.rs +++ b/backend/crates/providers/xai/tests/credential/oidc_verifier.rs @@ -23,6 +23,53 @@ use crate::support::loopback_endpoint_policy; const CACHE_TTL: Duration = Duration::from_secs(60 * 60); +#[tokio::test] +async fn jwks_and_userinfo_use_the_frozen_oauth_identity() { + let server = MockServer::start().await; + let endpoint = endpoints(&server); + let key = TestKey::new(37, "global-profile-key"); + mount_jwks(&server, key.jwks(), 1).await; + Mock::given(path("/oauth2/userinfo")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"sub":"test-user"}))) + .expect(1) + .mount(&server) + .await; + let verifier = verifier(&endpoint.origin, CACHE_TTL); + let nonce = SecretValue::new("global-profile-nonce"); + let algorithms = vec!["ES256".into()]; + let access = SecretValue::new("test-access"); + let token = SecretValue::new(key.sign(&valid_claims(&nonce), Algorithm::ES256)); + let profile = provider_xai::XaiWireProfile { + client_version: "9.8.7".into(), + target_os: "windows".into(), + target_arch: "arm64".into(), + ..Default::default() + }; + verifier + .verify( + auth_context(&endpoint, &algorithms, &nonce).with_wire_profile(&profile), + TokenCandidate::new(&access, Some(&token), None), + ) + .await + .unwrap(); + verifier + .verify( + import_context(&endpoint, &algorithms).with_wire_profile(&profile), + TokenCandidate::new(&access, None, Some(Duration::from_secs(60))), + ) + .await + .unwrap(); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 2); + for request in requests { + assert_eq!( + request.headers["user-agent"], + "grok-shell/9.8.7 (windows; aarch64)" + ); + assert_eq!(request.headers["x-grok-client-version"], "9.8.7"); + } +} + #[tokio::test] async fn proxy_jwks_cache_evicts_idle_exits_at_the_fixed_bound() { let origin = MockServer::start().await; diff --git a/backend/crates/providers/xai/tests/support.rs b/backend/crates/providers/xai/tests/support.rs index ce1ca809d..260849c06 100644 --- a/backend/crates/providers/xai/tests/support.rs +++ b/backend/crates/providers/xai/tests/support.rs @@ -55,14 +55,25 @@ pub fn grok_catalog_service( transport: Arc, cache: Arc, ) -> GrokCredentialCatalogService { - GrokCredentialCatalogService::new(repository, transport, cache, xai_wire_profile()) + GrokCredentialCatalogService::new( + repository, + transport, + cache, + xai_wire_profile(), + crate::support::runtime_policy(), + ) } pub fn grok_quota_service( repository: GrokCredentialRepository, transport: Arc, ) -> GrokCredentialQuotaService { - GrokCredentialQuotaService::new(repository, transport, xai_wire_profile()) + GrokCredentialQuotaService::new( + repository, + transport, + xai_wire_profile(), + crate::support::runtime_policy(), + ) } #[derive(Debug, Clone, Copy)] @@ -807,6 +818,28 @@ pub fn create_input(suffix: &str, subject: &str) -> CreateGrokCredential { pub struct StaticRuntimePolicy; +pub struct RequestProfileRuntimePolicy(pub Mutex); + +impl ProviderRuntimePolicyPort for RequestProfileRuntimePolicy { + fn load_request_profile<'a>( + &'a self, + provider: &'a ProviderKind, + ) -> futures::future::BoxFuture< + 'a, + Result, ProviderStoreError>, + > { + assert_eq!(provider.as_str(), "xai"); + let profile = self.0.lock().unwrap().clone(); + Box::pin(async move { Ok(Some(profile)) }) + } + + fn load_refresh_policy( + &self, + ) -> futures::future::BoxFuture<'_, Result> { + Box::pin(async { Ok(refresh_policy()) }) + } +} + #[derive(Default)] pub struct TestSessionAffinity { pub bindings: Mutex< diff --git a/backend/crates/providers/xai/tests/transport/network.rs b/backend/crates/providers/xai/tests/transport/network.rs index 1e23735ce..400a062fb 100644 --- a/backend/crates/providers/xai/tests/transport/network.rs +++ b/backend/crates/providers/xai/tests/transport/network.rs @@ -208,6 +208,7 @@ async fn inference_and_oauth_connect_through_each_accounts_authenticated_proxy() crate::support::xai_wire_profile(), Arc::new(ReqwestOAuthTransport::new(Arc::new(OfficialGrokEndpointPolicy)).unwrap()), Arc::new(FailClosedTokenVerifier), + crate::support::runtime_policy(), ) .with_outbound_proxy(Some(proxy)); assert!( @@ -1277,6 +1278,7 @@ async fn official_oauth_transport_should_resolve_through_the_production_policy_w .expect("production OAuth transport"), ), Arc::new(FailClosedTokenVerifier), + crate::support::runtime_policy(), ); let discovery = client diff --git a/docs/api.md b/docs/api.md index 64a8b3a6a..ed9ec3c73 100644 --- a/docs/api.md +++ b/docs/api.md @@ -2669,6 +2669,10 @@ models.dev 同步只导入可表示为当前文本 Token 计价的 OpenAI/xAI 更新时省略某项保留原值,对象替换该项,`null` 删除显式选择并使用 Provider 默认值;不清除其他 Provider 的配置。 配置内容由对应 Provider 校验,不包含账号凭据。Key 可通过 `providerRequestProfileOverrides` 整体覆盖所属 Provider 的选择 +OpenAI、xAI、Antigravity 的模型请求均按 Key 覆盖优先、其次全局的顺序选择身份。 +OAuth、令牌续期、额度刷新、订阅和模型目录查询等账号后台操作使用所属平台的全局身份, +不读取单个 Key 的覆盖;修改全局配置后,下次执行采用新选择 + 各 Provider 的选项响应均包含 `globalConfiguration`。OpenAI 返回六个 `presets`、`maxVersionLag` 和 `recognizedUserAgentPrefixes`。匹配前缀时,OpenAI 从 UA 派生 originator 与 Core 版本,其他自定义 UA 需要提供这两个字段。 xAI 返回 `defaults`,Antigravity 返回 `defaults` 与 `presets` @@ -2676,9 +2680,9 @@ xAI 返回 `defaults`,Antigravity 返回 `defaults` 与 `presets` ### OpenAI 上游客户端身份 OpenAI 通用身份默认使用 `MacOS · Desktop · 自动最新`。 -该配置作用于 Client Key 的 OpenAI 模型请求,适用于 HTTP/SSE、WebSocket、Images 和 Search, -也用于账号模型目录的后台发现、手动刷新、导出及定时预热;下次执行时采用当前全局选择,不使用单个 Key 的覆盖。 -不改变 xAI、入站客户端版本门禁、账号认证或后台 Desktop 专属操作 +模型请求覆盖 HTTP/SSE、WebSocket、Images 和 Search。后台全局身份还作用于授权链接的客户端参数、 +PAT 验证、额度重置卡、资料、头像和定时预热;各端点保留各自的请求头格式。 +该配置不覆盖浏览器授权页的 UA,不保证上游登录通知中的设备标签与之相同,也不改变入站客户端版本门禁 自定义配置使用 `{ "mode": "custom", "userAgent": "完整 UA" }`。 已识别的 `Codex Desktop`、`codex-tui`、`codex_exec`、`codex_cli_rs` 前缀由后端解析 `originator` 和 Core `version`, diff --git a/docs/architecture.md b/docs/architecture.md index 71478cbfd..579237543 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1069,6 +1069,9 @@ OpenAI 从账号目录生成原生列表;先按冻结政策选择来源,再 credential 与 quota 是两组独立事实:credential refresh 不等于 quota refresh,额度接口的 401/403 也不能单独证明 refresh token 永久失效 +OpenAI、xAI、Antigravity 的认证及账号后台操作由各 Provider 通过自身 profile 解析器读取当前全局身份, +冻结到对应上游请求,不读取 Key 覆盖;模型请求由请求上下文按 Key 覆盖优先、其次全局解析身份 + - OpenAI 支持 OAuth、AT/RT、PAT 和上游 API Key。OAuth 身份来自官方 JWT claims,PAT 经官方身份接口验证, 不信任导入文档顶层身份字段。RT-only 导入先换取 AT;AT-only、PAT 与 API Key 不参加 OAuth 自动续期。 输入形态和适用操作见 [账号能力与导入](api.md#账号能力导入与-oauth)