fix(providers): use global identity for background operations

Apply global client profiles to OAuth, token refresh and account background operations across OpenAI, xAI and Antigravity. Preserve Client Key overrides for model requests.

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-11-25 21:02:04 +08:00
co-authored by Codex
parent ee5f42ee8e
commit 3e747cb233
42 changed files with 885 additions and 173 deletions
@@ -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<dyn gateway_core::account::ProviderAccountStore>,
registration: String,
pub(crate) release: Arc<ReleaseService>,
pub(crate) origin: url::Url,
pub(crate) generation: AtomicU64,
observed:
@@ -109,7 +107,6 @@ impl CatalogService {
credentials: Arc<CredentialService>,
registration: String,
origin: url::Url,
release: Arc<ReleaseService>,
) -> 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(&current)
.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)
@@ -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<dyn ProviderAccountStore>,
credentials: Arc<CredentialService>,
catalog: Arc<CatalogService>,
release: Arc<ReleaseService>,
origin: url::Url,
cursor: AtomicUsize,
}
@@ -107,7 +105,6 @@ impl QuotaService {
accounts: Arc<dyn ProviderAccountStore>,
credentials: Arc<CredentialService>,
catalog: Arc<CatalogService>,
release: Arc<ReleaseService>,
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(&current)
.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
@@ -32,14 +32,12 @@ pub fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigErr
credentials.clone(),
oauth.registration(),
origin.clone(),
release.clone(),
));
let quota = Arc::new(credential::quota::QuotaService::new(
kind.clone(),
ports.accounts(),
credentials.clone(),
catalog.clone(),
release.clone(),
origin.clone(),
));
let core = Arc::new(provider::AntigravityProvider::new(
@@ -15,6 +15,37 @@ async fn upstream(server: &MockServer, remaining: serde_json::Value, delay: Dura
Mock::given(path("/v1internal:retrieveUserQuotaSummary")).respond_with(ResponseTemplate::new(200).set_delay(delay).set_body_json(json!({"groups":[{"displayName":"Gemini Models","buckets":[{"bucketId":"gemini-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.9,"resetTime":"2099-01-01T00:00:00Z"},{"bucketId":"gemini-5h","displayName":"Five hour","window":"5h","remainingFraction":remaining,"resetTime":"2099-01-01T00:00:00Z"}]},{"displayName":"Claude and GPT models","buckets":[{"bucketId":"3p-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.8,"resetTime":"2099-01-01T00:00:00Z"}]}]}))).mount(server).await;
}
#[tokio::test]
async fn quota_and_catalog_refresh_use_current_global_identity() {
let server = MockServer::start().await;
upstream(&server, json!(0.5), Duration::ZERO).await;
let f = Fixture::new(&server.uri());
let account = f.store.primary().loaded.lock().unwrap().account.clone();
for (version, changelist) in [("1.5.14", ""), ("1.5.15", "; cl=1027820220")] {
*f.store.request_profile.lock().unwrap() = Some(crate::profile::object(
json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":version,"arch":null}),
));
let before = server.received_requests().await.unwrap().len();
f.quota.refresh(account.id()).await.unwrap();
f.catalog.account_models(account.id(), true).await.unwrap();
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len() - before, 5);
for request in &requests[before..] {
assert_eq!(
request.headers["user-agent"],
format!(
"antigravity/cli/{version} (aidev_client; os_type=linux; arch=amd64{changelist}; auth_method=consumer)"
)
);
}
}
*f.store.request_profile.lock().unwrap() =
Some(crate::profile::object(json!({"client":"unsupported"})));
assert!(f.quota.refresh(account.id()).await.is_err());
assert!(f.catalog.account_models(account.id(), true).await.is_err());
assert_eq!(server.received_requests().await.unwrap().len(), 10);
}
#[tokio::test]
async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
let server = MockServer::start().await;
@@ -226,14 +226,12 @@ impl Fixture {
credentials.clone(),
oauth.registration(),
origin.clone(),
release.clone(),
));
let quota = Arc::new(crate::credential::quota::QuotaService::new(
kind.clone(),
store.clone(),
credentials.clone(),
catalog.clone(),
release.clone(),
origin.clone(),
));
let provider = Arc::new(AntigravityProvider::new(
@@ -144,6 +144,7 @@ pub(super) fn map_oauth_error(error: CodexOAuthAdminError) -> 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),
@@ -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<dyn ProviderRuntimePolicyPort>,
}
struct CodexOAuthAuthorizationCommitGuard {
@@ -408,6 +411,7 @@ impl CodexOAuthAdminService {
store: Arc<dyn ProviderAccountStore>,
credentials: CodexCredentialAdmin,
profile: CodexWireProfileState,
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
) -> 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<String, CodexOAuthA
fn authorization_url(
pending: &CodexPendingAuthorization,
oauth_client_id: &str,
desktop_version: &str,
profile: &CodexWireProfile,
) -> Result<String, CodexOAuthAdminError> {
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");
@@ -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<dyn ProviderRuntimePolicyPort>,
http: Client,
base_url: String,
avatar_sources: Mutex<HashMap<String, CachedProfileAvatarSource>>,
@@ -120,16 +122,34 @@ impl CodexCredentialProfileService {
profile: CodexWireProfileState,
http: Client,
base_url: String,
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
) -> Self {
Self {
repository,
profile,
http,
base_url,
runtime_policy,
avatar_sources: Mutex::new(HashMap::new()),
}
}
async fn global_profile_client(
&self,
) -> Result<CodexBackendClient, CodexProfileStatisticsError> {
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<CodexProfileStatistics, CodexProfileStatisticsError> {
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<CodexProfileStatistics, CodexProfileStatisticsError> {
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<CodexProfileAvatar, CodexProfileAvatarError> {
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(),
@@ -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 {
@@ -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,
@@ -126,11 +126,10 @@ impl CodexCredentialQuotaService {
account_id: &ProviderAccountId,
) -> Result<CodexRateLimitResetCredits, CodexResetCreditsError> {
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)
@@ -35,6 +35,22 @@ fn upstream_error_status(error: &CodexClientError) -> Option<u16> {
}
impl CodexCredentialQuotaService {
pub(super) async fn global_profile_client(
&self,
) -> Result<CodexBackendClient, CodexCredentialQuotaError> {
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) => {
@@ -140,17 +140,7 @@ impl CodexCredentialQuotaService {
})
.collect::<BTreeMap<_, _>>();
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() {
@@ -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<dyn ProviderRuntimePolicyPort>,
}
/// 官方 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<dyn ProviderRuntimePolicyPort>,
) -> 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<dyn ProviderRuntimePolicyPort>,
) -> Result<OpenAiTokenClient, TokenClientBuildError> {
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<TokenPair, RefreshFailure> {
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<AuthorizationTokenSet, AuthorizationCodeExchangeError> {
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()),
@@ -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()),
);
@@ -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,
@@ -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
@@ -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<HeaderMap> {
let mut headers = HeaderMap::new();
headers.insert(
@@ -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),
@@ -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 {
@@ -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("<svg/>", "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)
}
@@ -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,
@@ -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),
@@ -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 {
@@ -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)
}
@@ -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<dyn GrokCredentialCatalogCache>,
published: Arc<RwLock<PublishedCatalogState>>,
wire_profile: XaiWireProfileState,
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
}
/// 同一目录模型可由多个套餐的成员账号发现
@@ -377,6 +381,7 @@ impl GrokCredentialCatalogService {
transport: Arc<dyn GrokModelCatalogTransport>,
cache: Arc<dyn GrokCredentialCatalogCache>,
wire_profile: XaiWireProfileState,
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
) -> 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<LoadedGrokCredential>,
) -> Result<FetchedCredentialCatalog, GrokCredentialCatalogError> {
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
{
@@ -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<dyn ProviderRuntimePolicyPort>,
transport: Arc<dyn OAuthHttpTransport>,
verifier: Arc<dyn TokenVerifier>,
outbound_proxy: Option<gateway_core::account::OutboundProxy>,
@@ -29,12 +32,14 @@ impl GrokOAuthClient {
wire_profile: crate::XaiWireProfileState,
transport: Arc<dyn OAuthHttpTransport>,
verifier: Arc<dyn TokenVerifier>,
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
) -> 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<DiscoveryDocument, OAuthError> {
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<VerifiedTokenSet, OAuthError> {
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<VerifiedTokenSet, crate::GrokOAuthImportError> {
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<RefreshedTokenSet, OAuthError> {
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<RefreshedTokenSet, OAuthError> {
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<crate::XaiWireProfile, OAuthError> {
self.wire_profile
.resolve_global_request_profile(self.runtime_policy.as_ref())
.await
.map_err(|_| {
OAuthError::transport(
operation,
crate::TransportFailure::new(crate::TransportFailureKind::NotSent),
)
})
}
}
@@ -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<DecodingKey, VerificationFailure> {
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<HashMap<String, CachedJwk>, 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,
@@ -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<GrokBillingClient>,
scheduling: GrokQuotaSchedulingProjection,
wire_profile: XaiWireProfileState,
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
}
#[derive(Clone, Default)]
@@ -346,12 +350,14 @@ impl GrokCredentialQuotaService {
repository: GrokCredentialRepository,
transport: Arc<dyn GrokBillingTransport>,
wire_profile: XaiWireProfileState,
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
) -> 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)
@@ -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]
+3
View File
@@ -129,11 +129,13 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, Xai
catalog_transport,
catalog_cache_port,
profile.clone(),
Arc::clone(&runtime_policy),
));
let quota = Arc::new(GrokCredentialQuotaService::new(
repository.clone(),
billing_transport,
profile.clone(),
Arc::clone(&runtime_policy),
));
let selector: Arc<dyn GrokSessionSelector> = Arc::new(GrokAccountSessionSelector::new(
provider_kind.clone(),
@@ -162,6 +164,7 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, Xai
profile.clone(),
oauth_transport,
token_verifier,
Arc::clone(&runtime_policy),
));
let refresher: Arc<dyn GrokCredentialRefresher> =
Arc::new(GrokOAuthRefreshClient::new(Arc::clone(&oauth)));
@@ -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,
@@ -47,6 +47,20 @@ impl XaiWireProfile {
pub struct XaiWireProfileState(Arc<RwLock<XaiWireProfile>>);
impl XaiWireProfileState {
/// 账号后台操作按当前全局配置冻结身份,不读取 Client Key 覆盖
pub(crate) async fn resolve_global_request_profile(
&self,
policy: &dyn gateway_core::provider_ports::ProviderRuntimePolicyPort,
) -> Result<XaiWireProfile, gateway_core::error::ErrorSource> {
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)))
@@ -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 {
@@ -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<Vec<Vec<(String, String)>>>);
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:
@@ -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<VecDeque<Result<OAuthHttpResponse, TransportFailure>>>,
requests: Mutex<Vec<OAuthHttpRequest>>,
@@ -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(
@@ -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
@@ -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;
+35 -2
View File
@@ -55,14 +55,25 @@ pub fn grok_catalog_service(
transport: Arc<dyn GrokModelCatalogTransport>,
cache: Arc<dyn GrokCredentialCatalogCache>,
) -> 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<dyn GrokBillingTransport>,
) -> 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<gateway_core::account::OpaqueProviderData>);
impl ProviderRuntimePolicyPort for RequestProfileRuntimePolicy {
fn load_request_profile<'a>(
&'a self,
provider: &'a ProviderKind,
) -> futures::future::BoxFuture<
'a,
Result<Option<gateway_core::account::OpaqueProviderData>, 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<ProviderRefreshPolicy, ProviderStoreError>> {
Box::pin(async { Ok(refresh_policy()) })
}
}
#[derive(Default)]
pub struct TestSessionAffinity {
pub bindings: Mutex<
@@ -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
+7 -3
View File
@@ -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`,
+3
View File
@@ -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)