diff --git a/backend/crates/gateway-core/src/engine/execution/service.rs b/backend/crates/gateway-core/src/engine/execution/service.rs index 58fa3fa25..5203bbaf4 100644 --- a/backend/crates/gateway-core/src/engine/execution/service.rs +++ b/backend/crates/gateway-core/src/engine/execution/service.rs @@ -1562,7 +1562,12 @@ impl ExecutionService for DefaultExecutionService { for kind in scope.provider_kinds() { let provider = providers.get(kind).ok_or(ProviderCatalogUnavailable)?; let Some(models) = provider - .query_client_model_catalog(scope, protocol, client_version) + .query_client_model_catalog( + client.policy.key_id(), + scope, + protocol, + client_version, + ) .await? else { for profile in client.snapshot.profiles_for_provider_scope(kind, scope) { diff --git a/backend/crates/gateway-core/src/engine/provider.rs b/backend/crates/gateway-core/src/engine/provider.rs index 8ed8f454d..a49a712f7 100644 --- a/backend/crates/gateway-core/src/engine/provider.rs +++ b/backend/crates/gateway-core/src/engine/provider.rs @@ -1219,6 +1219,7 @@ pub trait Provider: Send + Sync { /// `None` 表示不提供该协议的原生目录;读取失败不能伪装成不支持 async fn query_client_model_catalog( &self, + _client_api_key_id: &ClientApiKeyId, _scope: &crate::account::scope::FrozenAccountScope, _protocol: &str, _client_version: &str, diff --git a/backend/crates/gateway-core/tests/engine/execution/mod.rs b/backend/crates/gateway-core/tests/engine/execution/mod.rs index 3d213002b..4125e3e96 100644 --- a/backend/crates/gateway-core/tests/engine/execution/mod.rs +++ b/backend/crates/gateway-core/tests/engine/execution/mod.rs @@ -3340,6 +3340,7 @@ impl Provider for CatalogProvider { } async fn query_client_model_catalog( &self, + _client_api_key_id: &ClientApiKeyId, scope: &FrozenAccountScope, protocol: &str, version: &str, diff --git a/backend/crates/providers/openai/src/admin/mod.rs b/backend/crates/providers/openai/src/admin/mod.rs index cdb9f43c0..33d9175e4 100644 --- a/backend/crates/providers/openai/src/admin/mod.rs +++ b/backend/crates/providers/openai/src/admin/mod.rs @@ -234,11 +234,11 @@ impl ProviderAdmin for OpenAiAdminProvider { ) -> Result { if configuration .expose_to_provider() - .contains_key("installationId") + .contains_key("installationSeed") || gateway_core::settings::request_profiles::inherited_fields(configuration).is_some() { return Err(provider_admin_error(ProviderAdminErrorKind::Invalid) - .with_public_message("安装 ID 只能在 API 密钥中设置")); + .with_public_message("安装身份种子只能在 API 密钥中设置")); } self.profile .preview_selection(configuration) @@ -2125,7 +2125,7 @@ fn map_client_profile_error( use crate::transport::profile::selection::ClientProfileError; let message = match error { ClientProfileError::Invalid => "客户端身份字段或版本组合不合法", - ClientProfileError::InvalidInstallationId => "安装 ID 必须是带连字符的 UUID", + ClientProfileError::InvalidInstallationSeed => "安装身份种子必须是带连字符的 UUID", ClientProfileError::InvalidUserAgent => { "User-Agent 必须是 1 至 4096 字节的单行 ASCII 文本,且首尾不能含空白" } diff --git a/backend/crates/providers/openai/src/credential/catalog.rs b/backend/crates/providers/openai/src/credential/catalog.rs index 12b67315d..71f18273c 100644 --- a/backend/crates/providers/openai/src/credential/catalog.rs +++ b/backend/crates/providers/openai/src/credential/catalog.rs @@ -10,6 +10,7 @@ use futures::{StreamExt, stream}; use gateway_core::account::{ CredentialRevision, CredentialState, OpaqueProviderData, ProviderAccount, ProviderAccountId, }; +use gateway_core::policy::ClientApiKeyId; use gateway_core::provider_ports::{ ProviderCatalogCacheKey, ProviderCatalogCachePort, ProviderCatalogScope, }; @@ -206,6 +207,7 @@ struct CatalogCacheState { #[derive(PartialEq, Eq)] struct ClientCatalogKey { + client_key_id: Option, account_id: ProviderAccountId, revision: CredentialRevision, plan: Option, @@ -311,6 +313,7 @@ impl CodexCredentialCatalogService { /// 同一账号/凭据版本/客户端版本的并发读取合并;原生正文仅保留在有界进程缓存 pub async fn client_model_catalog( &self, + client_key_id: &ClientApiKeyId, scope: &FrozenAccountScope, client_version: &str, ) -> ClientCatalogResult { @@ -339,7 +342,12 @@ impl CodexCredentialCatalogService { let profile = request_profile.clone(); async move { let result = self - .cached_client_account_catalog(&account, client_version, profile) + .cached_client_account_catalog( + client_key_id, + &account, + client_version, + profile, + ) .await; (account, result) } @@ -374,7 +382,12 @@ impl CodexCredentialCatalogService { let mut last_error = CodexCredentialCatalogError::NoEligibleCredential; for account in accounts.iter().take(MAX_CATALOG_FETCH_ATTEMPTS) { match self - .cached_client_account_catalog(account, client_version, request_profile.clone()) + .cached_client_account_catalog( + client_key_id, + account, + client_version, + request_profile.clone(), + ) .await { Ok(models) => { @@ -403,11 +416,17 @@ impl CodexCredentialCatalogService { async fn cached_client_account_catalog( &self, + client_key_id: &ClientApiKeyId, account: &ProviderAccount, client_version: &str, profile: CodexWireProfile, ) -> ClientCatalogResult { let key = ClientCatalogKey { + // 无种子时沿用账号级目录缓存,启用后按 Key 隔离出站身份 + client_key_id: profile + .installation_seed + .as_ref() + .map(|_| client_key_id.clone()), account_id: account.id().clone(), revision: account.revision(), plan: account.plan_type().map(str::to_owned), @@ -450,7 +469,7 @@ impl CodexCredentialCatalogService { CodexWireProfileState::new(profile), ); let result = self - .fetch_account_models(&client, account, Some(client_version)) + .fetch_account_models(&client, account, Some((client_key_id, client_version))) .await .map(|fetched| { fetched @@ -805,7 +824,7 @@ impl CodexCredentialCatalogService { &self, client: &CodexBackendClient, account: &ProviderAccount, - client_version: Option<&str>, + client_identity: Option<(&ClientApiKeyId, &str)>, ) -> Result { tokio::time::timeout(MODEL_CATALOG_TIMEOUT, async { let credential = self @@ -813,6 +832,14 @@ impl CodexCredentialCatalogService { .load_runtime_credential(account) .await .map_err(|_| CodexCredentialCatalogError::InvalidCredentialData)?; + let installation_id = client_identity.map(|(key_id, _)| { + client.profile_state().effective_installation_id( + key_id, + account.id(), + &credential.installation_id, + ) + }); + let client_version = client_identity.map(|(_, version)| version); let request_id = format!("catalog_{}", Uuid::now_v7().simple()); let authorization = credential .authentication @@ -829,7 +856,7 @@ impl CodexCredentialCatalogService { authorization.expose_secret(), account.upstream_account_id(), &request_id, - client_version.map(|_| credential.installation_id.as_str()), + installation_id.as_deref(), ), client_version, ) diff --git a/backend/crates/providers/openai/src/provider/execution.rs b/backend/crates/providers/openai/src/provider/execution.rs index e4935b53c..4cfd3ed52 100644 --- a/backend/crates/providers/openai/src/provider/execution.rs +++ b/backend/crates/providers/openai/src/provider/execution.rs @@ -331,9 +331,11 @@ impl CodexProvider { // Standalone Provider 端点没有可证明的账号 owner;Images/Search metadata 必须按 // 跨账号输入收敛到当前 lease,不能沿用下游声明的账号或 installation identity let client = self.client_for_request(&context)?; - let installation_id = client - .profile_state() - .effective_installation_id(lease.installation_id()); + let installation_id = client.profile_state().effective_installation_id( + context.client_api_key_ref(), + lease.account_id(), + lease.installation_id(), + ); let turn_metadata = payload .context() .get("turn_metadata") diff --git a/backend/crates/providers/openai/src/provider/failure.rs b/backend/crates/providers/openai/src/provider/failure.rs index 783458039..4691fae19 100644 --- a/backend/crates/providers/openai/src/provider/failure.rs +++ b/backend/crates/providers/openai/src/provider/failure.rs @@ -1101,7 +1101,7 @@ pub(super) fn profile_diagnostic( use crate::transport::profile::selection::ClientProfileError; let code = match error { ClientProfileError::Invalid => "request_profile_invalid", - ClientProfileError::InvalidInstallationId => "request_profile_installation_id_invalid", + ClientProfileError::InvalidInstallationSeed => "request_profile_installation_seed_invalid", ClientProfileError::InvalidUserAgent => "request_profile_user_agent_invalid", ClientProfileError::CompanionHeadersRequired => "request_profile_headers_required", ClientProfileError::CompanionHeadersConflict => "request_profile_headers_conflict", diff --git a/backend/crates/providers/openai/src/provider/live.rs b/backend/crates/providers/openai/src/provider/live.rs index a36e6ed95..bcda56f0a 100644 --- a/backend/crates/providers/openai/src/provider/live.rs +++ b/backend/crates/providers/openai/src/provider/live.rs @@ -433,13 +433,18 @@ fn cold_live_call_stream(request: ColdLiveCall) -> EventStream { .map_err(|_| { provider_error(ProviderErrorKind::Unauthorized, UpstreamSendState::NotSent) })?; + let installation_id = profile.effective_installation_id( + request.context.client_api_key_ref(), + request.lease.account_id(), + request.lease.installation_id(), + ); let request_id = request.context.request_id().as_str().to_owned(); let trace = request.context.trace(); let mut request_context = CodexRequestContext::auxiliary( authorization.expose_secret(), active_account.upstream_account_id(), &request_id, - Some(request.lease.installation_id()), + Some(&installation_id), ); request_context.trace = Some(&trace); request_context.account_selection = CodexAccountSelectionTelemetry::new( @@ -681,6 +686,11 @@ impl LiveGateway for CodexLiveGateway { let claim = LiveCallClaim::new(Arc::clone(&self.registry), request.call_id.to_owned()); let (account, authorization, installation_id) = self.load_pinned_credential(&account_id).await?; + let installation_id = profile.effective_installation_id( + request.client_api_key_id, + &account_id, + &installation_id, + ); if !account.enabled() { return Err(LiveGatewayError::new( LiveGatewayErrorKind::OwnerMismatch, @@ -739,6 +749,11 @@ impl LiveGateway for CodexLiveGateway { })?; let (account, authorization, installation_id) = self.load_pinned_credential(&account_id).await?; + let installation_id = profile.effective_installation_id( + request.client_api_key_id, + &account_id, + &installation_id, + ); // hangup 与引导同源:必须走钉住账号的出口代理与连接池, // 不能使用共享 client 直连发出。 let client = self diff --git a/backend/crates/providers/openai/src/provider/mod.rs b/backend/crates/providers/openai/src/provider/mod.rs index 986d90de2..62946b7e4 100644 --- a/backend/crates/providers/openai/src/provider/mod.rs +++ b/backend/crates/providers/openai/src/provider/mod.rs @@ -549,6 +549,7 @@ impl Provider for CodexProvider { async fn query_client_model_catalog( &self, + client_api_key_id: &gateway_core::policy::ClientApiKeyId, scope: &gateway_core::account::scope::FrozenAccountScope, protocol: &str, client_version: &str, @@ -560,7 +561,7 @@ impl Provider for CodexProvider { return Ok(None); } self.catalog - .client_model_catalog(scope, client_version) + .client_model_catalog(client_api_key_id, scope, client_version) .await .map(Some) .map_err(|_| gateway_core::routing::ProviderCatalogUnavailable) @@ -977,9 +978,11 @@ impl CodexProvider { .map(|affinity| (response_id.to_owned(), affinity)) }); let client = self.client_for_request(&context)?; - let installation_id = client - .profile_state() - .effective_installation_id(lease.installation_id()); + let installation_id = client.profile_state().effective_installation_id( + context.client_api_key_ref(), + lease.account_id(), + lease.installation_id(), + ); scope_request_to_account(&mut upstream_request, &installation_id, account_scope); // 父响应的可信关联只恢复此字段,不把首次 Guardian 请求的其他账号状态视为可信 if let Some((response_id, _)) = &guardian_parent diff --git a/backend/crates/providers/openai/src/transport/client_catalog.rs b/backend/crates/providers/openai/src/transport/client_catalog.rs index d79d147c8..707f1b821 100644 --- a/backend/crates/providers/openai/src/transport/client_catalog.rs +++ b/backend/crates/providers/openai/src/transport/client_catalog.rs @@ -25,16 +25,7 @@ impl CodexBackendClient { OpenAiUpstreamProtocol::ResponsesApi => "models", }; let profile = self.profile.snapshot(); - let headers = self.model_request_headers( - &profile, - CodexRequestContext { - installation_id: profile - .installation_id - .as_deref() - .or(context.installation_id), - ..context - }, - )?; + let headers = self.model_request_headers(&profile, context)?; let mut request = self .client .get(endpoint_url(&self.base_url, path)) diff --git a/backend/crates/providers/openai/src/transport/client_live.rs b/backend/crates/providers/openai/src/transport/client_live.rs index 6778180e8..3d8846ff8 100644 --- a/backend/crates/providers/openai/src/transport/client_live.rs +++ b/backend/crates/providers/openai/src/transport/client_live.rs @@ -32,13 +32,6 @@ impl CodexBackendClient { content_type: Option<&str>, ) -> CodexClientResult { let profile = self.profile.snapshot(); - let context = CodexRequestContext { - installation_id: profile - .installation_id - .as_deref() - .or(context.installation_id), - ..context - }; let mut headers = self.model_request_headers(&profile, context)?; for header in extra_protocol_headers { let name = HeaderName::from_bytes(header.name().as_bytes())?; diff --git a/backend/crates/providers/openai/src/transport/profile/identity.rs b/backend/crates/providers/openai/src/transport/profile/identity.rs index c913261a7..9970310a6 100644 --- a/backend/crates/providers/openai/src/transport/profile/identity.rs +++ b/backend/crates/providers/openai/src/transport/profile/identity.rs @@ -4,6 +4,7 @@ use chrono::DateTime; use gateway_core::account::OpaqueProviderData; use serde::Deserialize; use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; use super::selection::{ ClientKind, ClientProfileError, ClientProfileSelection, VersionMode, object, @@ -14,7 +15,7 @@ use super::{CodexWireProfile, CodexWireProfileState}; #[derive(Debug, Clone)] pub struct RequestProfileSelection { selection: ParsedSelection, - installation_id: Option, + installation_seed: Option, } #[derive(Debug, Clone)] @@ -23,6 +24,34 @@ enum ParsedSelection { Custom(ExactIdentity), } +impl CodexWireProfile { + pub(crate) fn effective_installation_id( + &self, + client_key_id: &gateway_core::policy::ClientApiKeyId, + account_id: &gateway_core::account::ProviderAccountId, + account_installation_id: &str, + ) -> String { + let Some(seed) = &self.installation_seed else { + return account_installation_id.to_owned(); + }; + // 稳定记录 ID 不受 UA、令牌刷新或账号凭据中的安装身份变化影响 + // 长度前缀避免字段边界歧义,独立用途域不与会话关联标识共享派生空间 + let mut digest = Sha256::new(); + digest.update(b"codex-key-account-installation-v1\0"); + for part in [seed.as_str(), client_key_id.as_str(), account_id.as_str()] { + digest.update((part.len() as u64).to_be_bytes()); + digest.update(part.as_bytes()); + } + let hash = digest.finalize(); + let mut bytes = [0_u8; 16]; + bytes.copy_from_slice(&hash[..16]); + // 沿用出站关联标识的 UUID 形状,值由种子确定,不按请求重新随机生成 + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + uuid::Uuid::from_bytes(bytes).to_string() + } +} + #[derive(Deserialize)] #[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)] enum SelectionDocument { @@ -39,7 +68,8 @@ pub(crate) fn inherited_identity_fields( document: &OpaqueProviderData, ) -> Result>, ClientProfileError> { let inherited = gateway_core::settings::request_profiles::inherited_fields(document); - if inherited.is_some_and(|fields| fields.len() != 1 || !fields.contains_key("installationId")) { + if inherited.is_some_and(|fields| fields.len() != 1 || !fields.contains_key("installationSeed")) + { return Err(ClientProfileError::Invalid); } Ok(inherited) @@ -65,18 +95,18 @@ impl RequestProfileSelection { let mut fields = inherited .unwrap_or_else(|| document.expose_to_provider()) .clone(); - let installation_id = match fields.remove("installationId") { + let installation_seed = match fields.remove("installationSeed") { None | Some(Value::Null) => None, Some(Value::String(value)) if value.is_empty() => None, Some(Value::String(value)) => { let parsed = uuid::Uuid::try_parse(&value) - .map_err(|_| ClientProfileError::InvalidInstallationId)?; + .map_err(|_| ClientProfileError::InvalidInstallationSeed)?; if value.len() != uuid::fmt::Hyphenated::LENGTH { - return Err(ClientProfileError::InvalidInstallationId); + return Err(ClientProfileError::InvalidInstallationSeed); } Some(parsed.to_string()) } - Some(_) => return Err(ClientProfileError::InvalidInstallationId), + Some(_) => return Err(ClientProfileError::InvalidInstallationSeed), }; let selection = if inherited.is_some() { ParsedSelection::Preset(ClientProfileSelection::default()) @@ -99,7 +129,7 @@ impl RequestProfileSelection { }; Ok(Self { selection, - installation_id, + installation_seed, }) } @@ -111,7 +141,9 @@ impl RequestProfileSelection { ParsedSelection::Preset(selection) => selection.resolve(state)?, ParsedSelection::Custom(identity) => identity.profile(state), }; - profile.installation_id.clone_from(&self.installation_id); + profile + .installation_seed + .clone_from(&self.installation_seed); Ok(profile) } @@ -123,11 +155,11 @@ impl RequestProfileSelection { ParsedSelection::Preset(selection) => state.preview_preset_selection(selection)?, ParsedSelection::Custom(identity) => identity.preview(state)?, }; - let Some(id) = &self.installation_id else { + let Some(seed) = &self.installation_seed else { return Ok(preview); }; let mut fields = preview.into_inner(); - fields["configuration"]["installationId"] = Value::String(id.clone()); + fields["configuration"]["installationSeed"] = Value::String(seed.clone()); Ok(OpaqueProviderData::new(fields)) } } @@ -222,7 +254,7 @@ impl ExactIdentity { .map(|value| value.terminal.clone()) .unwrap_or_default(), exact_user_agent: Some(self.user_agent.clone()), - installation_id: None, + installation_seed: None, residency: deployment.residency, account_routing_override: deployment.account_routing_override, verified_at: DateTime::UNIX_EPOCH, diff --git a/backend/crates/providers/openai/src/transport/profile/mod.rs b/backend/crates/providers/openai/src/transport/profile/mod.rs index 2395af26c..73b715a63 100644 --- a/backend/crates/providers/openai/src/transport/profile/mod.rs +++ b/backend/crates/providers/openai/src/transport/profile/mod.rs @@ -69,9 +69,9 @@ pub struct CodexWireProfile { /// 入口专属或自定义的完整值;存在时不得用默认预设重新拼接 #[serde(default, skip_serializing_if = "Option::is_none")] pub exact_user_agent: Option, - /// Key 独立配置的安装身份;省略时保留当前调用的账号基线 + /// Key 的安装身份种子,仅在本地按 Key 与账号派生出站身份 #[serde(default, skip_serializing_if = "Option::is_none")] - pub installation_id: Option, + pub installation_seed: Option, /// 未配置时不发送 residency 头;不随制品版本更新而改变 pub residency: Option, /// 部署指定的账号路由头;未配置时不发送,不随客户端身份选择改变 @@ -93,7 +93,7 @@ impl Default for CodexWireProfile { arch: "arm64".to_owned(), terminal: "unknown".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, // 制品核验于 2026-09-06T03:26:12.084Z;进程启动不构成重新核验 @@ -209,14 +209,16 @@ impl CodexWireProfileState { state } - pub(crate) fn effective_installation_id(&self, account_installation_id: &str) -> String { + pub(crate) fn effective_installation_id( + &self, + client_key_id: &gateway_core::policy::ClientApiKeyId, + account_id: &gateway_core::account::ProviderAccountId, + account_installation_id: &str, + ) -> String { self.profile .read() .unwrap_or_else(std::sync::PoisonError::into_inner) - .installation_id - .as_deref() - .unwrap_or(account_installation_id) - .to_owned() + .effective_installation_id(client_key_id, account_id, account_installation_id) } /// 返回当前画像的独立快照,避免持锁执行网络请求 diff --git a/backend/crates/providers/openai/src/transport/profile/selection.rs b/backend/crates/providers/openai/src/transport/profile/selection.rs index 81df2136f..e9772a0cc 100644 --- a/backend/crates/providers/openai/src/transport/profile/selection.rs +++ b/backend/crates/providers/openai/src/transport/profile/selection.rs @@ -277,7 +277,7 @@ impl ClientProfileSelection { .clone() .unwrap_or_else(|| "unknown".to_owned()), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: deployment.residency, account_routing_override: deployment.account_routing_override, verified_at: release.verified_at.unwrap_or(DateTime::UNIX_EPOCH), @@ -389,8 +389,8 @@ pub(crate) fn object(value: &impl Serialize) -> Result = + std::sync::LazyLock::new(|| ClientApiKeyId::new("key_catalog").unwrap()); + const OFFICIAL_FIXTURE: &[u8] = include_bytes!("../transport/fixtures/official_models_snapshot.json"); @@ -68,7 +72,7 @@ fn wire_profile() -> CodexWireProfileState { arch: "x86_64".to_owned(), terminal: "catalog-contract".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc @@ -171,7 +175,7 @@ async fn client_catalog_is_account_and_version_scoped_and_keeps_original_objects (vec![first], "0.154.0", "a-original"), ] { let models = service - .client_model_catalog(&client_scope(&accounts), version) + .client_model_catalog(&CLIENT_KEY, &client_scope(&accounts), version) .await .expect("catalog"); let document: serde_json::Value = serde_json::from_slice(match &models[0].content { @@ -189,7 +193,7 @@ async fn client_catalog_is_account_and_version_scoped_and_keeps_original_objects } assert!( service - .client_model_catalog(&client_scope(&[]), "0.154.0") + .client_model_catalog(&CLIENT_KEY, &client_scope(&[]), "0.154.0") .await .is_err() ); @@ -214,20 +218,20 @@ async fn client_catalog_coalesces_reads_and_invalidates_on_etag_expiry_and_expli .await; let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); let (first, second) = tokio::join!( - service.client_model_catalog(&scope, "0.154.0"), - service.client_model_catalog(&scope, "0.154.0") + service.client_model_catalog(&CLIENT_KEY, &scope, "0.154.0"), + service.client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") ); assert_eq!(first.expect("first"), second.expect("second")); service .invalidate() .expect("reset without a routing snapshot"); service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .expect("after reset"); assert!(service.observe_response_etag("catalog-new").expect("ETag")); service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .expect("after ETag"); assert!( @@ -236,14 +240,14 @@ async fn client_catalog_coalesces_reads_and_invalidates_on_etag_expiry_and_expli .expect("same ETag") ); service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .expect("still cached"); tokio::time::pause(); tokio::time::advance(std::time::Duration::from_secs(301)).await; tokio::time::resume(); service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .expect("after TTL"); server.verify().await; @@ -273,7 +277,7 @@ async fn client_catalog_cache_does_not_survive_credential_rotation() { } let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); let first = service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .expect("old"); store @@ -282,7 +286,7 @@ async fn client_catalog_cache_does_not_survive_credential_rotation() { .await .expect("rotate"); let second = service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .expect("new"); assert_ne!(first, second); @@ -307,7 +311,7 @@ async fn failed_client_catalog_never_falls_back_to_an_out_of_scope_account_or_pl for _ in 0..2 { assert!( service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .is_err() ); @@ -352,16 +356,16 @@ async fn client_catalog_evicts_old_entries_after_32_distinct_versions() { let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); for patch in 0..33 { service - .client_model_catalog(&scope, &format!("0.154.{patch}")) + .client_model_catalog(&CLIENT_KEY, &scope, &format!("0.154.{patch}")) .await .expect("catalog"); } service - .client_model_catalog(&scope, "0.154.32") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.32") .await .expect("newest is cached"); service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .expect("oldest was evicted"); server.verify().await; @@ -382,7 +386,7 @@ async fn client_catalog_retries_after_short_failure_cache_expires() { let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); assert!( service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .is_err() ); @@ -395,7 +399,7 @@ async fn client_catalog_retries_after_short_failure_cache_expires() { .await; assert!( service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .is_err() ); @@ -403,7 +407,7 @@ async fn client_catalog_retries_after_short_failure_cache_expires() { tokio::time::advance(std::time::Duration::from_secs(6)).await; tokio::time::resume(); service - .client_model_catalog(&scope, "0.154.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.154.0") .await .expect("recovered after failure TTL"); server.verify().await; @@ -840,7 +844,11 @@ async fn api_key_catalogs_are_isolated_and_join_oauth_without_claiming_native_me ["api-second"] ); let combined = service - .client_model_catalog(&client_scope(&[oauth_account, a.clone()]), "1.0.0") + .client_model_catalog( + &CLIENT_KEY, + &client_scope(&[oauth_account, a.clone()]), + "1.0.0", + ) .await .unwrap(); assert_eq!( @@ -928,8 +936,8 @@ async fn api_key_client_catalog_negotiates_and_preserves_versioned_native_object .mount(&upstream) .await; let (first, concurrent) = tokio::join!( - service.client_model_catalog(&scope, version), - service.client_model_catalog(&scope, version) + service.client_model_catalog(&CLIENT_KEY, &scope, version), + service.client_model_catalog(&CLIENT_KEY, &scope, version) ); for models in [first, concurrent] { let models = models.expect("native client catalog"); @@ -945,7 +953,7 @@ async fn api_key_client_catalog_negotiates_and_preserves_versioned_native_object } } let cached = service - .client_model_catalog(&scope, "0.155.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.155.0") .await .expect("separate version cache"); let ProviderModelContent::Native(payload) = &cached[0].content else { @@ -955,7 +963,7 @@ async fn api_key_client_catalog_negotiates_and_preserves_versioned_native_object assert_eq!(document["default_reasoning_level"], "high"); assert!( service - .client_model_catalog(&client_scope(&[]), "0.155.0") + .client_model_catalog(&CLIENT_KEY, &client_scope(&[]), "0.155.0") .await .is_err() ); @@ -999,7 +1007,7 @@ async fn api_key_native_catalog_preserves_unknown_reasoning_and_background_entit ["z-unknown-reasoning", "vendor/model"] ); let models = service - .client_model_catalog(&client_scope(&[account]), "0.155.0") + .client_model_catalog(&CLIENT_KEY, &client_scope(&[account]), "0.155.0") .await .unwrap(); assert_eq!( @@ -1049,6 +1057,7 @@ async fn api_key_client_catalog_distinguishes_filtered_empty_from_fetch_failure( let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); let result = service .client_model_catalog( + &CLIENT_KEY, &client_scope(&[store.account("acct_api").unwrap()]), "0.155.0", ) @@ -1117,7 +1126,7 @@ async fn api_key_client_catalog_keeps_native_sources_stable_and_account_scoped() (&accounts[2..], "Second native"), ] { let models = service - .client_model_catalog(&client_scope(scope_accounts), "0.155.0") + .client_model_catalog(&CLIENT_KEY, &client_scope(scope_accounts), "0.155.0") .await .unwrap(); assert_eq!(models.len(), 1); @@ -1157,7 +1166,7 @@ async fn api_key_client_catalog_cache_is_invalidated_by_credential_revision() { .mount(&upstream) .await; let models = service - .client_model_catalog(&scope, "0.155.0") + .client_model_catalog(&CLIENT_KEY, &scope, "0.155.0") .await .unwrap(); assert_eq!(models[0].model.as_str(), model); @@ -1228,7 +1237,7 @@ async fn api_key_catalog_accepts_namespaced_model_ids_without_inventing_capabili } let account = store.account("acct_api").expect("API account"); let models = service - .client_model_catalog(&client_scope(&[account]), "1.0.0") + .client_model_catalog(&CLIENT_KEY, &client_scope(&[account]), "1.0.0") .await .expect("client catalog"); assert_eq!( @@ -1325,6 +1334,7 @@ async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() { ); let mixed = service .client_model_catalog( + &CLIENT_KEY, &client_scope(&[oauth_account, api_account.clone()]), "1.0.0", ) @@ -1336,7 +1346,11 @@ async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() { }; assert_eq!(payload, before.models()[0].document()); let api_only = service - .client_model_catalog(&client_scope(std::slice::from_ref(&api_account)), "1.0.0") + .client_model_catalog( + &CLIENT_KEY, + &client_scope(std::slice::from_ref(&api_account)), + "1.0.0", + ) .await .expect("API client catalog"); assert!(matches!( @@ -1408,7 +1422,7 @@ async fn slow_api_key_catalogs_share_a_deadline_and_preserve_healthy_catalogs() let execution = tokio::spawn(async move { tokio::time::timeout(Duration::from_secs(17), async { tokio::join!( - service.client_model_catalog(&scope, "1.0.0"), + service.client_model_catalog(&CLIENT_KEY, &scope, "1.0.0"), service.refresh_account_catalog(&slow_id) ) }) @@ -1605,10 +1619,86 @@ async fn client_catalog_byte_budget_evicts_completed_entries_without_rejecting_l "small", ] { let models = service - .client_model_catalog(&scope, version) + .client_model_catalog(&CLIENT_KEY, &scope, version) .await .expect("large catalog delivered"); assert_eq!(models.len(), 1); } server.verify().await; } + +#[tokio::test] +async fn installation_seed_partitions_catalog_identity_and_cache_by_key_and_account() { + use gateway_core::account::OpaqueProviderData; + use serde_json::json; + + let store = Arc::new(MemoryAccountStore::default()); + let first = seed_account(&store, "acct_seed_a").await; + let second = seed_account(&store, "acct_seed_b").await; + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "models": [{"slug": "gpt-native", "display_name": "Native"}] + }))) + .expect(6) + .mount(&server) + .await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + let key_a = ClientApiKeyId::new("key_a").unwrap(); + let key_b = ClientApiKeyId::new("key_b").unwrap(); + let seed = "3b11bc82-c666-417d-b9ff-2a34fd040385"; + let scoped = |account: &ProviderAccount, seed: Option<&str>| { + client_scope(std::slice::from_ref(account)).with_request_profiles( + std::collections::BTreeMap::from([( + ProviderKind::new("openai").unwrap(), + OpaqueProviderData::new( + json!({ + "mode": "custom", "userAgent": "codex-tui/1.0.0", "installationSeed": seed + }) + .as_object() + .unwrap() + .clone(), + ), + )]), + ) + }; + for (key, account, seed) in [ + (&key_a, &first, Some(seed)), + (&key_a, &second, Some(seed)), + (&key_b, &first, Some(seed)), + (&key_b, &second, Some(seed)), + (&key_a, &first, Some(seed)), + (&key_a, &first, None), + (&key_b, &first, None), + ] { + service + .client_model_catalog(key, &scoped(account, seed), "1.0.0") + .await + .unwrap(); + } + // 重建进程内服务仍产生同一身份,未配置种子的不同 Key 共用账号目录缓存 + service_with_catalog_cache(&store, server.uri(), catalog_cache()) + .client_model_catalog(&key_a, &scoped(&first, Some(seed)), "1.0.0") + .await + .unwrap(); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 6); + let ids: Vec<_> = requests + .iter() + .map(|request| { + let id = request.headers["x-codex-installation-id"].to_str().unwrap(); + assert_ne!(id, seed); + assert!(uuid::Uuid::parse_str(id).is_ok()); + id + }) + .collect(); + assert_eq!( + ids[..5] + .iter() + .collect::>() + .len(), + 5 + ); + assert_eq!(ids[0], ids[5]); +} diff --git a/backend/crates/providers/openai/tests/credential/contract/mod.rs b/backend/crates/providers/openai/tests/credential/contract/mod.rs index 199362629..02bc79f24 100644 --- a/backend/crates/providers/openai/tests/credential/contract/mod.rs +++ b/backend/crates/providers/openai/tests/credential/contract/mod.rs @@ -229,7 +229,7 @@ fn selector_with_runtime( arch: "x86_64".to_owned(), terminal: "selector-contract".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: chrono::Utc::now(), diff --git a/backend/crates/providers/openai/tests/credential/profile_statistics.rs b/backend/crates/providers/openai/tests/credential/profile_statistics.rs index 5748972ef..5153c6f72 100644 --- a/backend/crates/providers/openai/tests/credential/profile_statistics.rs +++ b/backend/crates/providers/openai/tests/credential/profile_statistics.rs @@ -25,7 +25,7 @@ fn wire_profile() -> CodexWireProfileState { arch: "x86_64".to_owned(), terminal: "profile-statistics-contract".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc diff --git a/backend/crates/providers/openai/tests/credential/quota/mod.rs b/backend/crates/providers/openai/tests/credential/quota/mod.rs index 372a00f74..5111f7d2f 100644 --- a/backend/crates/providers/openai/tests/credential/quota/mod.rs +++ b/backend/crates/providers/openai/tests/credential/quota/mod.rs @@ -44,7 +44,7 @@ fn wire_profile() -> CodexWireProfileState { arch: "x86_64".to_owned(), terminal: "quota-contract".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index 906b8d1d9..18f82b5f1 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -1114,7 +1114,7 @@ fn wire_profile() -> CodexWireProfileState { arch: "x86_64".to_owned(), terminal: "provider-contract".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc::now(), @@ -6034,13 +6034,13 @@ async fn opaque_provider_options_do_not_change_openai_account_selection() { assert_eq!(error.send_state(), UpstreamSendState::NotSent); } -const KEY_INSTALLATION_ID: &str = "3b11bc82-c666-417d-b9ff-2a34fd040385"; +const KEY_INSTALLATION_SEED: &str = "3b11bc82-c666-417d-b9ff-2a34fd040385"; #[tokio::test] -async fn key_installation_override_scopes_http_headers_metadata_and_cache_without_changing_account() -{ +async fn installation_seed_scopes_http_identity_and_cache_by_key_and_account() { let store = Arc::new(MemoryAccountStore::default()); create_account(&store, "acct_scope_same").await; + create_account(&store, "acct_scope_new").await; let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/codex/responses")) @@ -6049,39 +6049,98 @@ async fn key_installation_override_scopes_http_headers_metadata_and_cache_withou .insert_header("content-type", "text/event-stream") .set_body_string(CAPTURE_COMPLETED_SSE), ) - .expect(3) + .expect(9) .mount(&server) .await; - let provider = provider_with_base_url(&store, server.uri()); - for installation_id in [None, Some(KEY_INSTALLATION_ID), None] { + let mut provider = provider_with_base_url(&store, server.uri()); + let other_seed = "a3146f84-64b3-4759-9cf1-a8a001448930"; + for (index, (key, account, seed, version)) in [ + ("key_a", "acct_scope_same", None, "1.0.0"), + ( + "key_a", + "acct_scope_same", + Some(KEY_INSTALLATION_SEED), + "1.0.0", + ), + ( + "key_a", + "acct_scope_new", + Some(KEY_INSTALLATION_SEED), + "1.0.0", + ), + ( + "key_b", + "acct_scope_same", + Some(KEY_INSTALLATION_SEED), + "1.0.0", + ), + ( + "key_b", + "acct_scope_new", + Some(KEY_INSTALLATION_SEED), + "1.0.0", + ), + ( + "key_a", + "acct_scope_same", + Some(KEY_INSTALLATION_SEED), + "2.0.0", + ), + ("key_a", "acct_scope_same", Some(other_seed), "1.0.0"), + ("key_a", "acct_scope_same", None, "1.0.0"), + ( + "key_a", + "acct_scope_same", + Some(KEY_INSTALLATION_SEED), + "1.0.0", + ), + ] + .into_iter() + .enumerate() + { + if index == 8 { + provider = provider_with_base_url(&store, server.uri()); + } let configuration = OpaqueProviderData::new(json!({ - "client": "cli", "platform": "linux", "versionMode": "fixed", "codexVersion":"1.0.0", - "installationId": installation_id + "client": "cli", "platform": "linux", "versionMode": "fixed", "codexVersion": version, + "installationSeed": seed }).as_object().unwrap().clone()); let profile = provider.resolve_request_profile(&configuration).unwrap(); let payload = ProtocolPayload::json_object( "openai", - json!({ - "model":"gpt-5.4","input":"hello","prompt_cache_key":"same-cache-key" - }) - .as_object() - .unwrap() - .clone(), + json!({"model":"gpt-5.4","input":"hello","prompt_cache_key":"same-cache-key"}) + .as_object() + .unwrap() + .clone(), ) .unwrap() .with_context(Map::from_iter([("use_websocket".to_owned(), json!(false))])); + let context = AttemptContext::new( + RequestAttemptContext::new( + ModelRequestId::new(format!("req_seed_{index}")).unwrap(), + ClientApiKeyId::new(key).unwrap(), + ) + .with_request_location(Some(global_request_location())) + .with_request_profile(Some(profile)), + NonZeroU32::new(1).unwrap(), + SystemTime::now() + Duration::from_secs(30), + account_policy(), + AccountAttemptContext::new( + BTreeSet::new(), + Some(ProviderAccountId::new(account).unwrap()), + None, + ) + .with_account_scope(contract_account_scope()), + None, + CancellationToken::new(), + ); let mut stream = Arc::clone(&provider) .execute( planned_request( "openai", Operation::Generate(GenerateRequest::from_protocol_payload(payload)), ), - context_with_state_owner_and_profile( - "req_device", - "acct_scope_same", - Some(global_request_location()), - Some(profile), - ), + context, ) .await .unwrap(); @@ -6090,24 +6149,41 @@ async fn key_installation_override_scopes_http_headers_metadata_and_cache_withou } } let requests = server.received_requests().await.unwrap(); - let bodies = requests + let bodies: Vec<_> = requests.iter().map(captured_request_body).collect(); + let ids: Vec<_> = requests .iter() - .map(captured_request_body) - .collect::>(); - for (request, body) in requests.iter().zip(&bodies) { - assert_eq!( - request.headers["x-codex-installation-id"].to_str().unwrap(), - body["client_metadata"]["x-codex-installation-id"] - .as_str() - .unwrap() - ); - } - let id = |i: usize| &bodies[i]["client_metadata"]["x-codex-installation-id"]; - assert_ne!(id(0), KEY_INSTALLATION_ID); - assert_eq!(id(1), KEY_INSTALLATION_ID); - assert_eq!(id(0), id(2)); - assert_ne!(bodies[0]["prompt_cache_key"], bodies[1]["prompt_cache_key"]); - assert_eq!(bodies[0]["prompt_cache_key"], bodies[2]["prompt_cache_key"]); + .zip(&bodies) + .map(|(request, body)| { + let id = request.headers["x-codex-installation-id"].to_str().unwrap(); + assert_eq!(id, body["client_metadata"]["x-codex-installation-id"]); + assert!(uuid::Uuid::parse_str(id).is_ok()); + assert_ne!(id, KEY_INSTALLATION_SEED); + assert_ne!(id, other_seed); + assert!(!String::from_utf8_lossy(&request.body).contains(KEY_INSTALLATION_SEED)); + id + }) + .collect(); + assert_eq!(ids[0], ids[7]); + assert_eq!(ids[1], ids[5]); + assert_eq!(ids[1], ids[8]); + assert_eq!( + [ids[0], ids[1], ids[2], ids[3], ids[4], ids[6]] + .into_iter() + .collect::>() + .len(), + 6 + ); + assert_eq!(bodies[0]["prompt_cache_key"], bodies[7]["prompt_cache_key"]); + assert_eq!(bodies[1]["prompt_cache_key"], bodies[5]["prompt_cache_key"]); + assert_eq!(bodies[1]["prompt_cache_key"], bodies[8]["prompt_cache_key"]); + assert_eq!( + [0, 1, 2, 3, 4, 6] + .map(|i| bodies[i]["prompt_cache_key"].as_str().unwrap()) + .into_iter() + .collect::>() + .len(), + 6 + ); } #[tokio::test] @@ -6234,7 +6310,7 @@ async fn websocket_account_scoping_replaces_downstream_installation_header() { ])); let provider = provider_with_base_url(&store, base_url); let configuration = OpaqueProviderData::new(json!({ - "mode": "custom", "userAgent": "codex-tui/1.0.0", "installationId": KEY_INSTALLATION_ID + "mode": "custom", "userAgent": "codex-tui/1.0.0", "installationSeed": KEY_INSTALLATION_SEED }).as_object().unwrap().clone()); let profile = provider.resolve_request_profile(&configuration).unwrap(); let mut stream = provider @@ -6259,7 +6335,8 @@ async fn websocket_account_scoping_replaces_downstream_installation_header() { let installation_id = body["client_metadata"]["x-codex-installation-id"] .as_str() .expect("account installation ID"); - assert_eq!(installation_id, KEY_INSTALLATION_ID); + assert_ne!(installation_id, KEY_INSTALLATION_SEED); + assert!(uuid::Uuid::parse_str(installation_id).is_ok()); assert_eq!(body["installation_id"], installation_id); assert_eq!(header["x-codex-installation-id"], installation_id); for encoded in [ @@ -10488,7 +10565,12 @@ async fn provider_compiles_catalog_presentation_for_codex_models() { ClientRoutingScope::all_accounts(), ); let native = provider - .query_client_model_catalog(&scope, "codex", "0.154.0") + .query_client_model_catalog( + &ClientApiKeyId::new("key_catalog").unwrap(), + &scope, + "codex", + "0.154.0", + ) .await .expect("native catalog") .expect("supported"); @@ -11384,7 +11466,12 @@ async fn api_key_default_http_uses_own_prefix_plain_json_and_only_own_authentica .await .expect("standard API catalog"); let catalog = provider - .query_client_model_catalog(&contract_account_scope(), "codex", "1.0.0") + .query_client_model_catalog( + &ClientApiKeyId::new("key_catalog").unwrap(), + &contract_account_scope(), + "codex", + "1.0.0", + ) .await .unwrap() .unwrap(); diff --git a/backend/crates/providers/openai/tests/provider/live.rs b/backend/crates/providers/openai/tests/provider/live.rs index 61a5659b2..9aa82ffd8 100644 --- a/backend/crates/providers/openai/tests/provider/live.rs +++ b/backend/crates/providers/openai/tests/provider/live.rs @@ -686,6 +686,7 @@ async fn verify_live_call_identity() { use tokio::io::AsyncWriteExt; use tokio::net::TcpListener; let profile = CodexWireProfile { + installation_seed: Some("3b11bc82-c666-417d-b9ff-2a34fd040385".to_owned()), originator: "codex_cli_rs".to_owned(), exact_user_agent: Some("codex_cli_rs/0.160.0 (Linux; x86_64) live-test".to_owned()), codex_version: "0.160.0".to_owned(), @@ -745,11 +746,17 @@ async fn verify_live_call_identity() { assert_live_correlation(&creation.headers); let scoped_session = creation.headers["session-id"].clone(); + let installation_id = creation.headers["x-codex-installation-id"].clone(); + assert_ne!( + installation_id.to_str().unwrap(), + profile.installation_seed.as_deref().unwrap() + ); let mut changed_profile = profile.clone(); changed_profile.exact_user_agent = Some("changed-key-profile".to_owned()); changed_profile.originator = "changed-originator".to_owned(); changed_profile.residency = None; + changed_profile.installation_seed = Some("a3146f84-64b3-4759-9cf1-a8a001448930".to_owned()); let current_scope = Arc::new( (*scope(AccountModelAccess::default())) .clone() @@ -816,6 +823,7 @@ async fn verify_live_call_identity() { ); let expected = profile.clone(); let expected_session = scoped_session.clone(); + let expected_installation_id = installation_id.clone(); let server = tokio::spawn(async move { let mut tls = accept_live_proxy(listener).await; if iteration < 2 { @@ -824,6 +832,10 @@ async fn verify_live_call_identity() { |request: &tokio_tungstenite::tungstenite::handshake::server::Request, _response| { assert_eq!(request.uri().path(), format!("/v1/live/{CALL}")); + assert_eq!( + request.headers()["x-codex-installation-id"], + expected_installation_id + ); assert_live_profile( request.headers(), &expected, @@ -856,6 +868,7 @@ async fn verify_live_call_identity() { ); assert_live_correlation(&headers); assert_eq!(headers["session-id"], expected_session); + assert_eq!(headers["x-codex-installation-id"], expected_installation_id); tls.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nX-Test-Response: first\r\nX-Test-Response: \x80second\r\nSet-Cookie: private=1\r\nConnection: close\r\n\r\n") .await .unwrap(); diff --git a/backend/crates/providers/openai/tests/transport/catalog.rs b/backend/crates/providers/openai/tests/transport/catalog.rs index a0856c2a2..5cb10ca78 100644 --- a/backend/crates/providers/openai/tests/transport/catalog.rs +++ b/backend/crates/providers/openai/tests/transport/catalog.rs @@ -412,7 +412,7 @@ fn profile() -> CodexWireProfileState { arch: "x86_64".to_owned(), terminal: "xterm".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc diff --git a/backend/crates/providers/openai/tests/transport/mod.rs b/backend/crates/providers/openai/tests/transport/mod.rs index aa0179c82..04b5e5997 100644 --- a/backend/crates/providers/openai/tests/transport/mod.rs +++ b/backend/crates/providers/openai/tests/transport/mod.rs @@ -138,7 +138,7 @@ pub(crate) fn test_wire_profile() -> CodexWireProfileState { arch: "x86_64".to_owned(), terminal: "transport-test".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc::now(), diff --git a/backend/crates/providers/openai/tests/transport/profile/mod.rs b/backend/crates/providers/openai/tests/transport/profile/mod.rs index 57eca6bdf..0748f2bd3 100644 --- a/backend/crates/providers/openai/tests/transport/profile/mod.rs +++ b/backend/crates/providers/openai/tests/transport/profile/mod.rs @@ -152,7 +152,7 @@ fn wire_profile_should_generate_bundled_core_app_server_user_agent() { arch: "arm64".to_owned(), terminal: "unknown".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc @@ -502,7 +502,7 @@ fn wire_profile() -> CodexWireProfile { arch: "arm64".to_owned(), terminal: "unknown".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc diff --git a/backend/crates/providers/openai/tests/transport/reset_credits.rs b/backend/crates/providers/openai/tests/transport/reset_credits.rs index ad252b872..1d3db7b9a 100644 --- a/backend/crates/providers/openai/tests/transport/reset_credits.rs +++ b/backend/crates/providers/openai/tests/transport/reset_credits.rs @@ -31,7 +31,7 @@ fn client(base_url: &str) -> CodexBackendClient { arch: "arm64".to_owned(), terminal: "xterm-256color".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc diff --git a/backend/crates/providers/openai/tests/transport/usage.rs b/backend/crates/providers/openai/tests/transport/usage.rs index dbd2a12bf..493d679ad 100644 --- a/backend/crates/providers/openai/tests/transport/usage.rs +++ b/backend/crates/providers/openai/tests/transport/usage.rs @@ -898,7 +898,7 @@ fn profile() -> CodexWireProfileState { arch: "x86_64".to_owned(), terminal: "xterm".to_owned(), exact_user_agent: None, - installation_id: None, + installation_seed: None, residency: None, account_routing_override: None, verified_at: Utc diff --git a/backend/migrations/.frozen-sha256 b/backend/migrations/.frozen-sha256 index d3c699204..eb47e14c9 100644 --- a/backend/migrations/.frozen-sha256 +++ b/backend/migrations/.frozen-sha256 @@ -38,3 +38,4 @@ b215ea90d5c8753aeb8192b17ffe65f7a95c1d620aaeaf9fc4337d8cf6f2634e 0037_retry_aft 321f4a09367717eb13c3cf5dbfd1f4b014e31c615a74bf6e3b09b8e810d87198 0038_preserve_client_key_ledger.sql 80ba91cad23667ace80a43daf905ca78fd0f6de5fb57f444c9ebbfa2fab90c34 0039_queue_timeouts.sql 2438e107835cd69effdb37e4d008b3b631a287da9e41185b04dd239449cb6733 0040_quota_credit_policy.sql +825b9144f369eca39439d7da27f477915bd904c3df90940108d8a37fcc129bac 0041_client_key_installation_seed.sql diff --git a/backend/migrations/0041_client_key_installation_seed.sql b/backend/migrations/0041_client_key_installation_seed.sql new file mode 100644 index 000000000..00f2f3a5c --- /dev/null +++ b/backend/migrations/0041_client_key_installation_seed.sql @@ -0,0 +1,33 @@ +-- Key 安装身份只保存种子,现有安装 ID 转为种子后按 Key 与账号重新派生 +WITH migrated AS ( + UPDATE client_api_keys + SET provider_request_profiles_json = jsonb_set( + provider_request_profiles_json, + '{openai}', + CASE + WHEN provider_request_profiles_json #> '{openai,inherit}' ? 'installationId' + THEN jsonb_set( + provider_request_profiles_json -> 'openai', + '{inherit}', + ((provider_request_profiles_json #> '{openai,inherit}') - 'installationId') + || jsonb_build_object( + 'installationSeed', + provider_request_profiles_json #> '{openai,inherit,installationId}' + ) + ) + ELSE ((provider_request_profiles_json -> 'openai') - 'installationId') + || jsonb_build_object( + 'installationSeed', + provider_request_profiles_json #> '{openai,installationId}' + ) + END + ), + updated_at = GREATEST(now(), updated_at) + WHERE provider_request_profiles_json -> 'openai' ? 'installationId' + OR provider_request_profiles_json #> '{openai,inherit}' ? 'installationId' + RETURNING id +) +UPDATE runtime_settings +SET config_revision = config_revision + 1, + updated_at = GREATEST(now(), updated_at) +WHERE EXISTS (SELECT 1 FROM migrated); diff --git a/deploy/README.md b/deploy/README.md index e6e1fc168..87d65d7e0 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -845,6 +845,12 @@ OAuth 账号仍使用默认授权名称(如「Codex 账号」「OpenAI 账号 升级会清空默认名称,账号列表按邮箱前缀和完整邮箱分两行展示。 自定义名称、已有改名审计记录的账号、无邮箱账号及 API Key 名称保留原值 +### Key 安装身份配置升级 + +已保存的 Key `installationId` 由数据库迁移转换为 `installationSeed`,管理 API 调用方须改用新字段。 +升级后,这些 Key 的出站安装身份及关联的会话、缓存标识会变化,已有 WebSocket 精确续写需重新发送完整上下文。 +未配置该字段的 Key 继续使用账号安装身份,配置方式见 [Key 客户端身份](../docs/api.md) + ### 错误保护配置升级 使用 `accountAutoFreeze*` 运行参数的部署升级时,数据库迁移删除全部旧保护设置,不转换规则或继承参数。 diff --git a/docs/api.md b/docs/api.md index bead183df..287c94f1c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -405,7 +405,7 @@ API Key 与 OAuth 共用模拟客户端画像(`User-Agent`、`originator`、`v 包括会话、线程、Lite 和其他业务扩展头。 上游认证只来自选中的账号;API Key 不携带 OAuth Cookie、ChatGPT 账号身份或下游的 `X-OpenAI-Actor-Authorization` 托管认证声明。 -`x-codex-installation-id` 优先使用当前 Key 设置的安装 ID,否则使用选中账号已持久化的安装 ID,与正文 `client_metadata` 中的安装身份一致。 +`x-codex-installation-id` 在 Key 配置种子时,由种子、Key ID 与选中账号 ID 稳定派生;未配置时使用账号已持久化的安装 ID,与正文 `client_metadata` 中的安装身份一致 `x-openai-internal-codex-residency` 和 `x-openai-account-routing-override` 分别由部署配置 `openai.residency`、`openai.account_routing_override` 控制,配置值原样发送并覆盖客户端同名头, 省略或 `null` 时删除对应请求头。配置说明见 [部署与运维](../deploy/README.md#启动后的运行设置) @@ -425,7 +425,7 @@ Responses 明确换号时清理 `traceparent`、`tracestate`、`sentry-trace`、 `ws_request_header_*` 副本。同账号及归属未知时保留原值,业务输入和工具结果保持原始内容 会话、线程、窗口及父子线程引用在出站时按本次安装身份稳定映射为 UUID; -默认使用账号安装身份,换账号会改变映射;Key 配置固定安装 ID 时,换账号仍沿用该 ID 的映射。HTTP 请求头、正文 metadata、WS 副本及 +默认使用账号安装身份;Key 配置种子时,每个 Key × 账号组合拥有独立的安装身份,换账号会改变映射。HTTP 请求头、正文 metadata、WS 副本及 已识别的 Desktop 自动 Git 上下文使用一致映射。 轮次及父子轮次引用保留客户端原值,包括输入项的 `internal_chat_message_metadata_passthrough.turn_id`、 请求 metadata 中的 `turn_id`、`parent_turn_id`、`root_turn_id`,以及 `x-client-turn-id`、 @@ -1860,8 +1860,8 @@ HTTP 返回 `403` 和 `image_generation_disabled`,WebSocket 每个 `response.c 未提供的 Provider 跟随通用设置;更新时省略某项保留原值,设为 `null` 清除该项覆盖。最多 256 项,每项最多 64 KiB。 独立配置整体覆盖通用设置,不逐字段继承;切换全局配置不会影响独立 Key。目录与选择规则见 [Provider 客户端身份](#provider-客户端身份) -OpenAI Key 可设置 `installationId`(带连字符的 UUID,大小写均可)。在 `providerRequestProfileOverrides.openai` 中,继承全局 UA 时使用 `{"inherit":{"installationId":"3b11bc82-c666-417d-b9ff-2a34fd040385"}}`;独立预设和自定义 UA 将该字段与各自的画像字段并列。 -省略、空字符串或 `null` 使用选中账号的安装身份;填写后仅覆盖这把 Key 的出站安装身份,换账号仍使用该值,不改写账号凭据。通用设置不接受此字段。 +OpenAI Key 可设置 `installationSeed`(带连字符的 UUID,大小写均可,保存时规范化为小写)。在 `providerRequestProfileOverrides.openai` 中,继承全局 UA 时使用 `{"inherit":{"installationSeed":"3b11bc82-c666-417d-b9ff-2a34fd040385"}}`;独立预设和自定义 UA 将该字段与各自的画像字段并列 +省略、空字符串或 `null` 使用选中账号的安装身份;填写后由种子、稳定的 Key 记录 ID 和账号记录 ID 派生安装 UUID。同一组合在重启、UA 变化和凭据更新后保持稳定,换 Key、换账号或修改种子会改变身份。种子不会发送给上游,也不改写账号凭据。通用设置不接受此字段 兼容字段 `openaiClientProfileOverride` 和 `xaiClientProfileOverride` 分别对应上述映射中的 `openai`、`xai`。 创建时省略或 `null` 表示无覆盖;更新时省略保留、`null` 清除。与通用字段同时提交时必须一致,否则拒绝整个请求; @@ -2300,7 +2300,7 @@ Responses 的自动 Desktop Git 上下文与请求头使用同一画像快照: 该同步不依赖隐私策略开关;显式隐私规则在其后执行,仍可覆盖最终字段 配置在请求开始时冻结,Provider 首次解析的版本用于该请求的全部重试与换号。 -安装 ID 不变时 WebSocket 精确续写沿用所属连接;更改或清除覆盖导致生效 ID 变化时,须重新发送完整上下文 +安装 ID 不变时 WebSocket 精确续写沿用所属连接;更改或清除种子导致生效 ID 变化时,须重新发送完整上下文 ### xAI 上游客户端身份 diff --git a/docs/architecture.md b/docs/architecture.md index 14b5185a5..6bb1ade3e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -523,7 +523,7 @@ OpenAI 模型目录用于发现与原生 Responses 账号资格筛选,OAuth 业务响应按原始字节转发,客户端错误兼容与原生续写额度恢复按明确例外处理,见 [OpenAI 透传](api.md#openai-透传)。 `transport/correlation` 在出站副本上按本次安装身份统一映射关联标识。 Responses 的账号归属判断及换号头部清理由 Provider 统一执行,各传输消费同一出站请求。 - 原生安装身份优先取自 Key,未配置时取自账号,与该 Key 是否继承全局 UA 无关;插件的身份生成、持久化及关联字段改写通过既有中间件链路自行完成。 + 原生安装身份由 OpenAI Provider 按 Key 种子、Key ID 与选中账号 ID 确定性派生,无需额外映射表;未配置种子时取自账号,与 UA 继承方式无关。模型目录缓存按生效身份隔离,Live 后续阶段使用引导时冻结的种子;插件的身份生成、持久化及关联字段改写通过既有中间件链路自行完成 内部选号、亲和、连接池与本地诊断继续读取原始身份;具体字段边界见 [API 协议](api.md#请求头与身份) canonical facts 从同一数据旁路提取,用于路由、恢复判断、观测和计费。 WebSocket transport 按完整文本消息交付,wire 同时保留原文与可选解析视图;同协议出口使用原文, diff --git a/frontend/src/api/modules/settings/profiles.ts b/frontend/src/api/modules/settings/profiles.ts index e1298c48b..3cd7f30f0 100644 --- a/frontend/src/api/modules/settings/profiles.ts +++ b/frontend/src/api/modules/settings/profiles.ts @@ -30,7 +30,7 @@ export interface CustomClientProfileSelection { export type ClientProfileSelection = PresetClientProfileSelection | CustomClientProfileSelection -export function isValidInstallationId(value: unknown) { +export function isValidInstallationSeed(value: unknown) { return value == null || value === '' || (typeof value === 'string' && value.length === 36 && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value)) } diff --git a/frontend/src/i18n/locales/en/settings.json b/frontend/src/i18n/locales/en/settings.json index 1e2423915..5359009b7 100644 --- a/frontend/src/i18n/locales/en/settings.json +++ b/frontend/src/i18n/locales/en/settings.json @@ -6,11 +6,11 @@ "globalConfiguration": "Global configuration", "customConfiguration": "Custom configuration", "enterIntegerFromTo": "Enter an integer from 1 to {version}", - "installationId": "Installation ID", - "generateInstallationId": "Generate installation ID", - "installationIdHelp": "Identifies the client device to OpenAI; set it to keep the same ID across upstream accounts, or leave it blank to use the selected account’s installation ID", - "installationIdPlaceholder": "Leave blank to use the upstream account’s installation ID", - "invalidInstallationId": "Enter a hyphenated UUID", + "installationSeed": "Installation seed", + "generateInstallationSeed": "Generate installation seed", + "installationSeedHelp": "Derives a stable installation identity for each key and upstream account without sending the seed upstream, changing the seed changes the identity", + "installationSeedPlaceholder": "Leave blank to use the upstream account’s installation ID", + "invalidInstallationSeed": "Enter a hyphenated UUID", "clientDefault": "Client default", "useCustomUserAgent": "Use a custom user agent", "cliEntry": "CLI entry", diff --git a/frontend/src/i18n/locales/zh-Hans/settings.json b/frontend/src/i18n/locales/zh-Hans/settings.json index e6453151a..5b1a4e3dd 100644 --- a/frontend/src/i18n/locales/zh-Hans/settings.json +++ b/frontend/src/i18n/locales/zh-Hans/settings.json @@ -6,11 +6,11 @@ "globalConfiguration": "全局配置", "customConfiguration": "独立配置", "enterIntegerFromTo": "请输入 1~{version} 的正整数", - "installationId": "安装 ID", - "generateInstallationId": "生成安装 ID", - "installationIdHelp": "用于向 OpenAI 标识客户端设备;填写后,这把密钥即使切换上游账号也会使用同一安装ID,留空则使用当前上游账号的安装ID", - "installationIdPlaceholder": "留空使用上游账号的安装ID", - "invalidInstallationId": "请输入带连字符的 UUID", + "installationSeed": "安装身份种子", + "generateInstallationSeed": "生成安装身份种子", + "installationSeedHelp": "按密钥和上游账号生成独立、稳定的安装身份,种子不会发送给上游,修改种子会切换身份", + "installationSeedPlaceholder": "留空使用上游账号的安装 ID", + "invalidInstallationSeed": "请输入带连字符的 UUID", "clientDefault": "客户端预设", "useCustomUserAgent": "使用自定义用户代理", "cliEntry": "CLI 入口", diff --git a/frontend/src/i18n/locales/zh-Hant/settings.json b/frontend/src/i18n/locales/zh-Hant/settings.json index 4cdbe04ab..ff55ff7c3 100644 --- a/frontend/src/i18n/locales/zh-Hant/settings.json +++ b/frontend/src/i18n/locales/zh-Hant/settings.json @@ -6,11 +6,11 @@ "globalConfiguration": "全局配置", "customConfiguration": "獨立配置", "enterIntegerFromTo": "請輸入 1~{version} 的正整數", - "installationId": "安裝 ID", - "generateInstallationId": "產生安裝 ID", - "installationIdHelp": "用於向 OpenAI 識別用戶端裝置;填寫後,這把金鑰即使切換上游帳號也會使用同一安裝ID,留空則使用目前上游帳號的安裝ID", - "installationIdPlaceholder": "留空使用上游帳號的安裝ID", - "invalidInstallationId": "請輸入帶連字號的 UUID", + "installationSeed": "安裝身分種子", + "generateInstallationSeed": "產生安裝身分種子", + "installationSeedHelp": "依金鑰與上游帳號產生獨立、穩定的安裝身分,種子不會傳送給上游,修改種子會切換身分", + "installationSeedPlaceholder": "留空使用上游帳號的安裝 ID", + "invalidInstallationSeed": "請輸入帶連字號的 UUID", "clientDefault": "客戶端預設", "useCustomUserAgent": "使用自定義用戶代理", "cliEntry": "CLI 入口", diff --git a/frontend/src/views/keys/components/ApiKeyFormModal.vue b/frontend/src/views/keys/components/ApiKeyFormModal.vue index b29b69568..af9120bfb 100644 --- a/frontend/src/views/keys/components/ApiKeyFormModal.vue +++ b/frontend/src/views/keys/components/ApiKeyFormModal.vue @@ -7,7 +7,7 @@ import { Dices, DollarSign, KeyRound } from '@lucide/vue' import { computed, useTemplateRef, watch } from 'vue' import { useI18n } from 'vue-i18n' -import { isValidInstallationId } from '@/api/modules/settings/profiles' +import { isValidInstallationSeed } from '@/api/modules/settings/profiles' import AccountGroupCheckboxGrid from '@/components/AccountGroupCheckboxGrid.vue' import ProviderRequestProfilesEditor from '@/components/client-profile/ProviderRequestProfilesEditor.vue' import HelpPopover from '@/components/HelpPopover.vue' @@ -36,14 +36,14 @@ const title = computed(() => props.editing const formRef = useTemplateRef>('formElement') const rules = useApiKeyFormRules(() => form.value) -const installationIdError = computed(() => isValidInstallationId(form.value.installationId) +const installationSeedError = computed(() => isValidInstallationSeed(form.value.installationSeed) ? '' - : t('settings.clientProfile.invalidInstallationId')) + : t('settings.clientProfile.invalidInstallationSeed')) watch(open, () => formRef.value?.clearValidate()) async function requestSave() { - if (props.saving || installationIdError.value || !await formRef.value?.validate().catch(() => false)) + if (props.saving || installationSeedError.value || !await formRef.value?.validate().catch(() => false)) return emit('save') } @@ -148,32 +148,32 @@ function updatePeerSharing(key: keyof ApiKeyPeerSharing, value: boolean) { /> - + @@ -244,7 +244,7 @@ function updatePeerSharing(key: keyof ApiKeyPeerSharing, value: boolean) { {{ editing ? t('common.actions.save') : t('common.actions.create') }} diff --git a/frontend/src/views/keys/composables/useApiKeyEditor.ts b/frontend/src/views/keys/composables/useApiKeyEditor.ts index b59927be7..fc177f0e0 100644 --- a/frontend/src/views/keys/composables/useApiKeyEditor.ts +++ b/frontend/src/views/keys/composables/useApiKeyEditor.ts @@ -10,7 +10,7 @@ import { notification as ZNotification } from '@/utils/notification' export interface ApiKeyFormValue { peerSharing: ApiKeyPeerSharing providerRequestProfileOverrides: ProviderRequestProfiles - installationId: string + installationSeed: string customKey: string name: string label: string @@ -43,17 +43,17 @@ export function useApiKeyEditor(options: { const profiles = cloneDeep(key.providerRequestProfileOverrides) const openai = profiles.openai const identity = (openai?.inherit as Record | undefined) ?? openai - const installationId = typeof identity?.installationId === 'string' - ? identity.installationId + const installationSeed = typeof identity?.installationSeed === 'string' + ? identity.installationSeed : '' if (openai?.inherit) delete profiles.openai else if (openai) - delete openai.installationId + delete openai.installationSeed form.value = { peerSharing: { ...key.peerSharing }, providerRequestProfileOverrides: profiles, - installationId, + installationSeed, customKey: '', name: key.name, label: key.label ?? '', @@ -100,13 +100,13 @@ export function useApiKeyEditor(options: { weeklyLimitUsd: form.value.weeklyLimitUsd.trim() || '0', } const profiles = cloneDeep(form.value.providerRequestProfileOverrides) - const installationId = form.value.installationId - if (installationId) { - // 仅固定安装 ID 时保留对全局 UA 的继承,不在 Key 中复制当前全局值 + const installationSeed = form.value.installationSeed + if (installationSeed) { + // 仅设置种子时仍继承全局 UA,不在 Key 中复制当前全局值 profiles.openai = profiles.openai - ? { ...profiles.openai, installationId } + ? { ...profiles.openai, installationSeed } : { - inherit: { installationId }, + inherit: { installationSeed }, } } const current = editingKey.value @@ -174,7 +174,7 @@ function emptyForm(): ApiKeyFormValue { sharePlans: false, }, providerRequestProfileOverrides: {}, - installationId: '', + installationSeed: '', customKey: '', name: '', label: '',