feat(admin): add account group policies and bulk API key editing (#751)

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-11-20 14:39:30 +08:00
committed by GitHub
co-authored by Codex
parent 1427dfc64a
commit 6cfe7ce2fc
102 changed files with 3273 additions and 703 deletions
@@ -183,7 +183,7 @@ async fn initialize_inner(
PluginDistributionPorts::new(plugin_distribution, store.proxies()),
snapshot.clone(),
plugin_preparation,
published_snapshot,
published_snapshot.clone(),
store.plugin_state(),
)),
key_usage,
@@ -201,6 +201,7 @@ async fn initialize_inner(
store.account_groups(),
store.account_runtime(),
snapshot.clone(),
published_snapshot,
)),
client_keys: Arc::new(DefaultClientKeyService::new(
store.client_keys(),
@@ -4,7 +4,7 @@ use std::collections::BTreeMap;
use chrono::{DateTime, Utc};
use gateway_core::{
account::{AccountStatusFacts, FastMode},
account::{AccountModelAccess, AccountStatusFacts, FastMode},
routing::AccountGroupId,
};
@@ -112,6 +112,8 @@ pub struct AccountGroupListQuery {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountGroupRecord {
pub allow_image_generation: bool,
pub allow_subagents: bool,
pub model_access: AccountModelAccess,
pub fast_mode: FastMode,
pub id: AccountGroupId,
pub name: String,
@@ -152,6 +154,8 @@ pub struct AccountGroupOptionsPage {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateAccountGroup {
pub allow_image_generation: bool,
pub allow_subagents: bool,
pub model_access: AccountModelAccess,
pub fast_mode: FastMode,
pub name: String,
pub description: Option<String>,
@@ -162,6 +166,8 @@ pub struct CreateAccountGroup {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewAccountGroup {
pub allow_image_generation: bool,
pub allow_subagents: bool,
pub model_access: AccountModelAccess,
pub fast_mode: FastMode,
pub id: AccountGroupId,
pub name: String,
@@ -173,6 +179,8 @@ pub struct NewAccountGroup {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdateAccountGroup {
pub allow_image_generation: Option<bool>,
pub allow_subagents: Option<bool>,
pub model_access: Option<AccountModelAccess>,
pub fast_mode: Option<FastMode>,
pub id: AccountGroupId,
pub name: String,
@@ -36,6 +36,7 @@ pub enum MutationAuditOperation {
PluginSourceCredentialCreate,
PluginSourceCredentialDelete,
ClientApiKeyUpdateBudgetLimits,
ClientApiKeyBatchUpdate,
ClientApiKeyCreate,
ClientApiKeyUpdate,
ClientApiKeyEnabled { enabled: bool },
@@ -97,6 +98,7 @@ impl MutationAuditOperation {
Self::PluginSourceCredentialCreate => ("create", "plugin_source_credential"),
Self::PluginSourceCredentialDelete => ("delete", "plugin_source_credential"),
Self::ClientApiKeyUpdateBudgetLimits => ("update_budget_limits", "client_api_key"),
Self::ClientApiKeyBatchUpdate => ("batch_update", "client_api_key"),
Self::ClientApiKeyCreate => ("create", "client_api_key"),
Self::ClientApiKeyUpdate => ("update", "client_api_key"),
Self::ClientApiKeyEnabled { enabled } => {
@@ -218,6 +218,66 @@ pub struct UpdateClientKey {
pub weekly_limit_usd: Option<gateway_core::metering::Decimal>,
}
/// 批量编辑只覆盖明确选择的互联选项
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ClientPeerSharingPatch {
pub enabled: Option<bool>,
pub share_pool: Option<bool>,
pub share_quota: Option<bool>,
pub share_plans: Option<bool>,
}
impl ClientPeerSharingPatch {
#[must_use]
pub fn is_empty(self) -> bool {
self == Self::default()
}
#[must_use]
pub fn apply(
self,
current: gateway_core::policy::ClientPeerSharing,
) -> gateway_core::policy::ClientPeerSharing {
gateway_core::policy::ClientPeerSharing {
enabled: self.enabled.unwrap_or(current.enabled),
share_pool: self.share_pool.unwrap_or(current.share_pool),
share_quota: self.share_quota.unwrap_or(current.share_quota),
share_plans: self.share_plans.unwrap_or(current.share_plans),
}
}
}
/// 对各个密钥独立应用同一份局部设置
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BatchUpdateClientKeys {
pub ids: Vec<ClientApiKeyId>,
pub group_ids: Option<Vec<AccountGroupId>>,
pub enabled: Option<bool>,
pub max_concurrency: Option<u64>,
pub requests_per_minute: Option<u64>,
pub daily_limit_usd: Option<gateway_core::metering::Decimal>,
pub weekly_limit_usd: Option<gateway_core::metering::Decimal>,
pub peer_sharing: ClientPeerSharingPatch,
pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates,
pub installation_seed: Option<uuid::Uuid>,
}
impl BatchUpdateClientKeys {
#[must_use]
pub fn has_changes(&self) -> bool {
self.group_ids.is_some()
|| self.enabled.is_some()
|| self.max_concurrency.is_some()
|| self.requests_per_minute.is_some()
|| self.daily_limit_usd.is_some()
|| self.weekly_limit_usd.is_some()
|| !self.peer_sharing.is_empty()
|| !self.request_profile_override_updates.is_empty()
|| self.installation_seed.is_some()
}
}
/// 修改 Client Key 启用状态
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetClientKeyEnabled {
@@ -231,6 +231,19 @@ pub trait ProviderAdmin: Send + Sync {
self.preview_client_profile(key)
}
/// 在批量更新中合并本地身份;缺省、清除和替换分别保留各自语义,不能执行 I/O
fn merge_batch_key_profile(
&self,
current: Option<&gateway_core::account::OpaqueProviderData>,
update: Option<&Option<gateway_core::account::OpaqueProviderData>>,
installation_seed: Option<uuid::Uuid>,
) -> Result<Option<gateway_core::account::OpaqueProviderData>, ProviderAdminError> {
if installation_seed.is_some() {
return Err(ProviderAdminError::new(ProviderAdminErrorKind::Unsupported));
}
Ok(update.map_or_else(|| current.cloned(), Clone::clone))
}
/// 提供最终套餐展示名称;未覆盖时采用通用的大驼峰格式
fn plan_type_display(&self, plan_type: &str) -> String {
default_plan_type_display(plan_type)
@@ -22,10 +22,11 @@ use crate::model::{
},
auth::{AdminAuditEvent, AuthSession},
client_keys::{
ClientKeyBudgetMutationOrigin, ClientKeyBudgetWindow, ClientKeyBudgetWindowPeriod,
ClientKeyListQuery, ClientKeyPage, ClientKeyRecord, ClientKeySecret, DeleteClientKey,
NewClientKey, ResetClientKeyBudget, SetClientKeyBudgetWindow, SetClientKeyEnabled,
UpdateClientKey, UpdateClientKeyBudgetLimits,
BatchUpdateClientKeys, ClientKeyBudgetMutationOrigin, ClientKeyBudgetWindow,
ClientKeyBudgetWindowPeriod, ClientKeyListQuery, ClientKeyPage, ClientKeyRecord,
ClientKeySecret, DeleteClientKey, NewClientKey, ResetClientKeyBudget,
SetClientKeyBudgetWindow, SetClientKeyEnabled, UpdateClientKey,
UpdateClientKeyBudgetLimits,
},
observability::{
DashboardObservation, DashboardQuery, DiagnosticDimension, DiagnosticsObservation,
@@ -109,6 +110,13 @@ impl AdminStoreError {
pub type AdminStoreResult<T> = Result<T, AdminStoreError>;
/// 在持有密钥行锁时用 Provider 准备好的纯合并操作更新原有画像
pub type BatchClientKeyProfileMerger = Box<
dyn Fn(&mut crate::model::client_keys::ProviderRequestProfileOverrides) -> AdminStoreResult<()>
+ Send
+ Sync,
>;
/// 账号目录与公共账号写操作
#[async_trait]
pub trait AccountStore:
@@ -415,6 +423,13 @@ pub trait ClientKeyStore: Send + Sync {
context: &MutationContext,
) -> AdminStoreResult<(Revision, ClientKeyRecord)>;
async fn batch_update_client_keys(
&self,
command: BatchUpdateClientKeys,
merge_profiles: BatchClientKeyProfileMerger,
context: &MutationContext,
) -> AdminStoreResult<Revision>;
async fn set_client_key_enabled(
&self,
command: SetClientKeyEnabled,
@@ -9,8 +9,8 @@ use std::{
use async_trait::async_trait;
use gateway_core::{
account::{AccountStatus, resolve_account_status},
routing::AccountGroupId,
runtime::SnapshotControl,
routing::{AccountGroupId, UpstreamModelId},
runtime::{RuntimeSnapshotHandle, SnapshotControl},
};
use uuid::Uuid;
@@ -32,6 +32,7 @@ use super::{map_store_error, publish_committed};
/// 面向 API 的账号分组管理服务
#[async_trait]
pub trait AccountGroupService: Send + Sync {
fn models(&self, group: &AccountGroupId) -> Result<Vec<UpstreamModelId>, AdminError>;
async fn list(&self, query: AccountGroupListQuery) -> Result<AccountGroupPage, AdminError>;
async fn list_options(
&self,
@@ -64,6 +65,7 @@ pub(crate) struct DefaultAccountGroupService {
store: Arc<dyn AccountGroupStore>,
runtime: Arc<dyn AccountRuntimeStore>,
snapshot: Arc<dyn SnapshotControl>,
published_snapshot: RuntimeSnapshotHandle,
}
impl DefaultAccountGroupService {
@@ -73,12 +75,14 @@ impl DefaultAccountGroupService {
store: Arc<dyn AccountGroupStore>,
runtime: Arc<dyn AccountRuntimeStore>,
snapshot: Arc<dyn SnapshotControl>,
published_snapshot: RuntimeSnapshotHandle,
) -> Self {
Self {
upstream_info,
store,
runtime,
snapshot,
published_snapshot,
}
}
@@ -131,6 +135,14 @@ impl DefaultAccountGroupService {
#[async_trait]
impl AccountGroupService for DefaultAccountGroupService {
fn models(&self, group: &AccountGroupId) -> Result<Vec<UpstreamModelId>, AdminError> {
let snapshot = self
.published_snapshot
.acquire()
.map_err(|_| AdminError::unavailable("模型目录尚未就绪"))?;
Ok(snapshot.upstream_models_for_group(group))
}
async fn list(&self, query: AccountGroupListQuery) -> Result<AccountGroupPage, AdminError> {
let mut page = self
.store
@@ -167,6 +179,8 @@ impl AccountGroupService for DefaultAccountGroupService {
.create_account_group(
NewAccountGroup {
allow_image_generation: command.allow_image_generation,
allow_subagents: command.allow_subagents,
model_access: command.model_access,
id,
name: command.name,
description: command.description,
@@ -1,11 +1,12 @@
//! Client API Key 管理用例
use std::sync::Arc;
use std::{collections::BTreeSet, sync::Arc};
use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use gateway_core::{
engine::budget::ClientBudgetStatus, policy::ClientApiKeyId, runtime::SnapshotControl,
account::OpaqueProviderData, engine::budget::ClientBudgetStatus, policy::ClientApiKeyId,
routing::ProviderKind, runtime::SnapshotControl,
};
use rand_core::{OsRng, RngCore as _};
use uuid::Uuid;
@@ -14,15 +15,17 @@ use crate::{
model::{
AdminError, MutationContext,
client_keys::{
ClientKeyBudgetMutationOrigin, ClientKeyBudgetWindow, ClientKeyBudgetWindowPeriod,
ClientKeyCursorValue, ClientKeyListQuery, ClientKeyMutation, ClientKeyPage,
ClientKeyRecord, ClientKeySecret, ClientKeySortField, CreateClientKey,
CreatedClientKey, DeleteClientKey, NewClientKey, ResetClientKeyBudget,
BatchUpdateClientKeys, ClientKeyBudgetMutationOrigin, ClientKeyBudgetWindow,
ClientKeyBudgetWindowPeriod, ClientKeyCursorValue, ClientKeyListQuery,
ClientKeyMutation, ClientKeyPage, ClientKeyRecord, ClientKeySecret, ClientKeySortField,
CreateClientKey, CreatedClientKey, DeleteClientKey, NewClientKey, ResetClientKeyBudget,
SetClientKeyBudgetWindow, SetClientKeyEnabled, UpdateClientKey,
UpdateClientKeyBudgetLimits,
},
},
ports::store::{AdminStoreError, AdminStoreErrorKind, ClientKeyStore},
ports::store::{
AdminStoreError, AdminStoreErrorKind, BatchClientKeyProfileMerger, ClientKeyStore,
},
};
use super::{map_store_error, publish_committed};
@@ -55,6 +58,11 @@ pub trait ClientKeyService: Send + Sync {
context: &MutationContext,
command: UpdateClientKey,
) -> Result<ClientKeyMutation, AdminError>;
async fn batch_update(
&self,
context: &MutationContext,
command: BatchUpdateClientKeys,
) -> Result<crate::model::Revision, AdminError>;
async fn set_enabled(
&self,
context: &MutationContext,
@@ -99,10 +107,111 @@ impl DefaultClientKeyService {
providers,
}
}
fn validate_profile(
&self,
kind: &ProviderKind,
profile: &OpaqueProviderData,
) -> Result<(), AdminError> {
self.providers
.require(kind)
.and_then(|provider| provider.preview_key_client_profile(profile, None))
.map(|_| ())
.map_err(|error| super::map_provider_error(error, "client profile"))
}
fn batch_profile_merger(
&self,
command: &BatchUpdateClientKeys,
) -> Result<BatchClientKeyProfileMerger, AdminError> {
let mut kinds = command
.request_profile_override_updates
.keys()
.cloned()
.collect::<BTreeSet<_>>();
let seed_kind = ProviderKind::new("openai").expect("static Provider kind is valid");
if command.installation_seed.is_some() {
kinds.insert(seed_kind.clone());
}
let mut changes = Vec::with_capacity(kinds.len());
for kind in kinds {
let provider = self
.providers
.require(&kind)
.map_err(|error| super::map_provider_error(error, "client profile"))?;
let update = command.request_profile_override_updates.get(&kind).cloned();
let seed = if kind == seed_kind {
command.installation_seed
} else {
None
};
// 先校验输入,行锁内只依据各把密钥的现值完成合并
if let Some(Some(profile)) = update.as_ref() {
provider
.merge_batch_key_profile(None, update.as_ref(), seed)
.and_then(|_| provider.preview_key_client_profile(profile, None))
.map_err(|error| super::map_provider_error(error, "client profile"))?;
}
changes.push((kind, provider, update, seed));
}
Ok(Box::new(move |profiles| {
for (kind, provider, update, seed) in &changes {
let next = provider
.merge_batch_key_profile(profiles.get(kind), update.as_ref(), *seed)
.map_err(|error| {
AdminStoreError::new(
AdminStoreErrorKind::Invalid,
"client profile",
"invalid stored client profile",
)
.with_source(error)
})?;
if let Some(profile) = next {
profiles.insert(kind.clone(), profile);
} else {
profiles.remove(kind);
}
}
Ok(())
}))
}
}
#[async_trait]
impl ClientKeyService for DefaultClientKeyService {
async fn batch_update(
&self,
context: &MutationContext,
command: BatchUpdateClientKeys,
) -> Result<crate::model::Revision, AdminError> {
if command.ids.is_empty()
|| command.ids.len() > 1000
|| command
.ids
.iter()
.collect::<std::collections::BTreeSet<_>>()
.len()
!= command.ids.len()
{
return Err(AdminError::invalid("请选择 1 至 1000 个不同的 API Key"));
}
if !command.has_changes() {
return Err(AdminError::invalid("请至少选择一项要修改的密钥设置"));
}
if let Some(groups) = &command.group_ids {
crate::model::client_keys::validate_group_ids(groups)
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
}
let merge_profiles = self.batch_profile_merger(&command)?;
let revision = self
.store
.batch_update_client_keys(command, merge_profiles, context)
.await
.map_err(|error| map_store_error(error, "client API key"))?;
publish_committed(self.snapshot.as_ref(), revision).await?;
Ok(revision)
}
async fn budget_window(
&self,
id: &ClientApiKeyId,
@@ -203,10 +312,7 @@ impl ClientKeyService for DefaultClientKeyService {
crate::model::client_keys::validate_group_ids(&command.group_ids)
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
for (provider, profile) in &command.request_profile_overrides {
self.providers
.require(provider)
.and_then(|provider| provider.preview_key_client_profile(profile, None))
.map_err(|error| super::map_provider_error(error, "client profile"))?;
self.validate_profile(provider, profile)?;
}
validate_peer_sharing(command.peer_sharing, &command.group_ids)?;
let id = ClientApiKeyId::new(format!("key_{}", Uuid::now_v7().simple()))
@@ -250,10 +356,7 @@ impl ClientKeyService for DefaultClientKeyService {
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
for (provider, profile) in &command.request_profile_override_updates {
if let Some(profile) = profile {
self.providers
.require(provider)
.and_then(|provider| provider.preview_key_client_profile(profile, None))
.map_err(|error| super::map_provider_error(error, "client profile"))?;
self.validate_profile(provider, profile)?;
}
}
if let Some(sharing) = command.peer_sharing {
@@ -53,6 +53,8 @@ impl PluginResourceAccess for DefaultPluginResourceAccess {
resource_key,
NewAccountGroup {
allow_image_generation: command.allow_image_generation,
allow_subagents: command.allow_subagents,
model_access: command.model_access,
id,
name: command.name,
description: command.description,
@@ -344,6 +344,8 @@ fn group_record() -> AccountGroupRecord {
let now = Utc::now();
AccountGroupRecord {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
id: group_id(),
name: "Primary".to_owned(),
@@ -420,6 +422,8 @@ async fn invalid_group_fields_are_rejected_before_store_mutations() {
&context,
CreateAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
name: " invalid".to_owned(),
description: None,
@@ -434,6 +438,8 @@ async fn invalid_group_fields_are_rejected_before_store_mutations() {
&context,
UpdateAccountGroup {
allow_image_generation: None,
allow_subagents: None,
model_access: None,
fast_mode: None,
id: record.id,
name: "valid".to_owned(),
@@ -35,6 +35,15 @@ struct TestClientKeyStore {
#[async_trait]
impl ClientKeyStore for TestClientKeyStore {
async fn batch_update_client_keys(
&self,
_: gateway_admin::model::client_keys::BatchUpdateClientKeys,
_: gateway_admin::ports::store::BatchClientKeyProfileMerger,
_: &MutationContext,
) -> AdminStoreResult<Revision> {
Err(unused())
}
async fn client_key_budget_window(
&self,
_: &gateway_core::policy::ClientApiKeyId,
@@ -172,6 +181,34 @@ impl ClientKeyStore for TestClientKeyStore {
}
}
#[tokio::test]
async fn batch_keys_require_a_change_and_unique_targets() {
use gateway_admin::model::client_keys::BatchUpdateClientKeys;
let services = super::AdminHarness::new()
.client_keys(Arc::new(TestClientKeyStore::default()))
.build()
.await;
let id = ClientApiKeyId::new("key_a").unwrap();
for patch in [
BatchUpdateClientKeys {
ids: vec![id.clone()],
..Default::default()
},
BatchUpdateClientKeys {
ids: vec![id.clone(), id],
enabled: Some(false),
..Default::default()
},
] {
let error = services
.client_keys()
.batch_update(&mutation_context(), patch)
.await
.unwrap_err();
assert_eq!(error.kind(), AdminErrorKind::Invalid);
}
}
#[tokio::test]
async fn reset_budget_forwards_scope_and_returns_only_key_identity() {
use gateway_admin::model::client_keys::{ClientKeyBudgetPeriod, ResetClientKeyBudget};
@@ -719,6 +719,15 @@ impl AccountRuntimeStore for UnavailableStore {
#[async_trait]
impl ClientKeyStore for UnavailableStore {
async fn batch_update_client_keys(
&self,
_: gateway_admin::model::client_keys::BatchUpdateClientKeys,
_: gateway_admin::ports::store::BatchClientKeyProfileMerger,
_: &MutationContext,
) -> AdminStoreResult<Revision> {
Err(unavailable("client key batch update"))
}
async fn client_key_budget_window(
&self,
_: &gateway_core::policy::ClientApiKeyId,
@@ -21,12 +21,15 @@ use gateway_admin::model::{
UpdateAccountGroup,
},
};
use gateway_core::{account::FastMode, routing::AccountGroupId};
use gateway_core::{
account::{AccountModelAccess, FastMode},
routing::AccountGroupId,
};
use serde::{Deserialize, Serialize};
use super::{
AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminQuery, AdminResponse, PageMeta,
WireValidationError, wire::map_admin_service_error,
WireValidationError, accounts::AccountModelView, wire::map_admin_service_error,
};
/// 账号、代理与 Client Key 共用的分组引用
@@ -90,15 +93,19 @@ impl ListAccountGroupsQuery {
}
}
const fn default_allow_image_generation() -> bool {
const fn default_allowed() -> bool {
true
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CreateAccountGroupRequest {
#[serde(default = "default_allow_image_generation")]
#[serde(default = "default_allowed")]
allow_image_generation: bool,
#[serde(default = "default_allowed")]
allow_subagents: bool,
#[serde(default)]
model_access: AccountModelAccess,
#[serde(default)]
fast_mode: FastMode,
name: String,
@@ -110,6 +117,8 @@ struct CreateAccountGroupRequest {
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct UpdateAccountGroupRequest {
allow_image_generation: Option<bool>,
allow_subagents: Option<bool>,
model_access: Option<AccountModelAccess>,
fast_mode: Option<FastMode>,
id: String,
name: String,
@@ -127,6 +136,8 @@ struct AccountGroupIdRequest {
#[serde(rename_all = "camelCase")]
struct AccountGroupView {
allow_image_generation: bool,
allow_subagents: bool,
model_access: AccountModelAccess,
fast_mode: FastMode,
id: String,
name: String,
@@ -175,6 +186,8 @@ impl From<(AccountGroupRecord, crate::time::TimePresenter)> for AccountGroupView
description: record.description,
fast_mode: record.fast_mode,
allow_image_generation: record.allow_image_generation,
allow_subagents: record.allow_subagents,
model_access: record.model_access,
color: record.color.as_str().to_owned(),
enabled: record.enabled,
member_count: record.member_count,
@@ -304,6 +317,7 @@ where
{
Router::new()
.route("/api/admin/account-groups", get(list::<S>))
.route("/api/admin/account-groups/models", get(models::<S>))
.route("/api/admin/account-groups/options", get(list_options::<S>))
.route("/api/admin/account-groups/create", post(create::<S>))
.route("/api/admin/account-groups/update", post(update::<S>))
@@ -332,6 +346,32 @@ where
))
}
#[derive(Serialize)]
struct AccountGroupModelsData {
models: Vec<AccountModelView>,
}
async fn models<S>(
_auth: AdminAuth,
State(state): State<S>,
AdminQuery(query): AdminQuery<AccountGroupIdRequest>,
) -> Result<impl IntoResponse, AdminError>
where
S: SessionState + Send + Sync,
{
let models = state
.admin_services()
.account_groups()
.models(&group_id(query.id)?)
.map_err(map_service_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(AccountGroupModelsData {
models: models.into_iter().map(AccountModelView::from).collect(),
}),
))
}
async fn list<S>(
_auth: AdminAuth,
State(state): State<S>,
@@ -371,6 +411,8 @@ where
&auth.context().mutation_context(),
CreateAccountGroup {
allow_image_generation: request.allow_image_generation,
allow_subagents: request.allow_subagents,
model_access: request.model_access,
name: request.name,
description: request.description,
fast_mode: request.fast_mode,
@@ -400,6 +442,8 @@ where
&auth.context().mutation_context(),
UpdateAccountGroup {
allow_image_generation: request.allow_image_generation,
allow_subagents: request.allow_subagents,
model_access: request.model_access,
id: group_id(request.id)?,
name: request.name,
description: request.description,
@@ -53,13 +53,7 @@ pub(super) fn account_models_data(
models: result
.models
.into_iter()
.map(|model| {
let id = model.id.to_string();
AccountModelView {
label: id.clone(),
id,
}
})
.map(|model| AccountModelView::from(model.id))
.collect(),
observed_at: observed_at.map(|value| time.rfc3339(&value)),
observed_at_display: observed_at
@@ -743,6 +743,16 @@ pub struct AccountModelView {
pub label: String,
}
impl From<UpstreamModelId> for AccountModelView {
fn from(model: UpstreamModelId) -> Self {
let id = model.to_string();
Self {
label: id.clone(),
id,
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountModelsData {
@@ -7,11 +7,12 @@ use std::{collections::BTreeMap, fmt};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use chrono::{DateTime, Utc};
use gateway_admin::model::client_keys::{
ClientKeyBudgetPeriod, ClientKeyCursor, ClientKeyCursorValue as DomainCursorValue,
ClientKeyListQuery, ClientKeyMutation, ClientKeyPage, ClientKeyPageSize, ClientKeyRecord,
ClientKeySecret, ClientKeySort as DomainSort, ClientKeySortField as DomainSortField,
CreateClientKey, CreatedClientKey, DeleteClientKey, ResetClientKeyBudget, SetClientKeyEnabled,
SortDirection, UpdateClientKey,
BatchUpdateClientKeys, ClientKeyBudgetPeriod, ClientKeyCursor,
ClientKeyCursorValue as DomainCursorValue, ClientKeyListQuery, ClientKeyMutation,
ClientKeyPage, ClientKeyPageSize, ClientKeyRecord, ClientKeySecret,
ClientKeySort as DomainSort, ClientKeySortField as DomainSortField, CreateClientKey,
CreatedClientKey, DeleteClientKey, ResetClientKeyBudget, SetClientKeyEnabled, SortDirection,
UpdateClientKey,
};
use gateway_core::{
engine::budget::ClientBudgetLimits,
@@ -867,6 +868,10 @@ where
{
Router::new()
.route("/api/admin/client-keys", get(list_client_keys::<S>))
.route(
"/api/admin/client-keys/batch-update",
post(batch_update_client_keys::<S>),
)
.route(
"/api/admin/client-keys/create",
post(create_client_key::<S>),
@@ -913,6 +918,96 @@ where
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct BatchUpdateClientKeysRequest {
ids: Vec<String>,
group_ids: Option<Vec<String>>,
enabled: Option<bool>,
max_concurrency: Option<u64>,
requests_per_minute: Option<u64>,
daily_limit_usd: Option<String>,
weekly_limit_usd: Option<String>,
peer_sharing: Option<gateway_admin::model::client_keys::ClientPeerSharingPatch>,
#[serde(default)]
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
installation_seed: Option<String>,
}
impl BatchUpdateClientKeysRequest {
/// 复用单把密钥的字段校验,缺省和显式零值分别保留
pub fn into_command(self) -> Result<BatchUpdateClientKeys, WireValidationError> {
if let Some(limit) = self.max_concurrency {
validate_limit(limit, "maxConcurrency")?;
}
if let Some(limit) = self.requests_per_minute {
validate_limit(limit, "requestsPerMinute")?;
}
let installation_seed = self
.installation_seed
.map(|value| {
if value.len() != uuid::fmt::Hyphenated::LENGTH {
return Err(WireValidationError::new("installationSeed"));
}
uuid::Uuid::try_parse(&value)
.map_err(|_| WireValidationError::new("installationSeed"))
})
.transpose()?;
Ok(BatchUpdateClientKeys {
ids: self
.ids
.into_iter()
.map(|id| client_key_id(id, "id"))
.collect::<Result<_, _>>()?,
group_ids: self.group_ids.map(validate_group_ids).transpose()?,
enabled: self.enabled,
max_concurrency: self.max_concurrency,
requests_per_minute: self.requests_per_minute,
daily_limit_usd: parse_budget(self.daily_limit_usd, "dailyLimitUsd")?,
weekly_limit_usd: parse_budget(self.weekly_limit_usd, "weeklyLimitUsd")?,
peer_sharing: self.peer_sharing.unwrap_or_default(),
request_profile_override_updates: normalize_request_profile_override_updates(
self.provider_request_profile_overrides,
None,
None,
)?,
installation_seed,
})
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct BatchUpdatedClientKeysData {
config_revision: gateway_admin::model::Revision,
updated: usize,
}
async fn batch_update_client_keys<S>(
auth: AdminAuth,
State(state): State<S>,
AdminJson(request): AdminJson<BatchUpdateClientKeysRequest>,
) -> Result<impl IntoResponse, AdminError>
where
S: SessionState + Send + Sync,
{
let command = request.into_command().map_err(map_wire_error)?;
let updated = command.ids.len();
let config_revision = state
.admin_services()
.client_keys()
.batch_update(&auth.context().mutation_context(), command)
.await
.map_err(map_service_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(BatchUpdatedClientKeysData {
config_revision,
updated,
}),
))
}
async fn create_client_key<S>(
auth: AdminAuth,
State(state): State<S>,
@@ -1088,6 +1183,7 @@ fn map_wire_error(error: WireValidationError) -> AdminError {
"dailyLimitUsd" => "每日美元限额须非负,整数和小数各最多 10 位",
"weeklyLimitUsd" => "每周美元限额须非负,整数和小数各最多 10 位",
"providerRequestProfileOverrides" => "API Key 客户端身份配置无效或字段冲突",
"installationSeed" => "安装身份种子必须是带连字符的 UUID",
"limit" => "每页数量须为 1 至 65535",
"search" => "搜索内容过长或包含控制字符",
"sortBy" => "排序字段不受支持",
@@ -115,9 +115,14 @@ async fn models_response(
}
})
.collect::<Result<Vec<_>, ()>>();
let Ok(models) = models else {
let Ok(mut models) = models else {
return catalog_unavailable_response();
};
if !client.policy().account_scope().allows_subagents() {
for model in &mut models {
model["multi_agent_version"] = json!("disabled");
}
}
return (
StatusCode::OK,
// 目录经过账号选择/别名/多 Provider 聚合,不能借用上游 ETag 表示改写后的正文
@@ -120,6 +120,7 @@ impl OpenAiRequestHeaders {
let mut context = Map::new();
insert_protocol_context(&mut context, "turn_state", self.turn_state.as_ref());
insert_protocol_context(&mut context, "turn_metadata", self.turn_metadata.as_ref());
insert_protocol_context(&mut context, "subagent", self.subagent.as_ref());
if matches!(source, RequestDecodeSource::WebSocketFrame) {
context.insert(
gateway_protocol::openai::WEBSOCKET_FRAME_CONTEXT_KEY.to_owned(),
@@ -78,6 +78,58 @@ async fn options_route_should_return_only_lightweight_group_fields() {
assert_eq!(value["data"]["configRevision"], 7);
}
#[tokio::test]
async fn models_route_reads_the_published_group_catalog() {
use gateway_core::{
account::ProviderAccountId,
routing::{
ConfigRevision, ModelCapabilities, ProviderKind, ProviderModel, RuntimeAccount,
RuntimeAccountDirectory, RuntimeSnapshot, UpstreamModelId,
},
};
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
let fixture = authenticated_fixture().await;
let uri = format!("/api/admin/account-groups/models?id={PRIMARY_GROUP_ID}");
let unavailable = request(router(&fixture), Method::GET, &uri, None, true).await;
assert_eq!(unavailable.status(), StatusCode::SERVICE_UNAVAILABLE);
let provider = ProviderKind::new("openai").unwrap();
let snapshot = RuntimeSnapshot::new(
ConfigRevision::new(7).unwrap(),
gateway_core::settings::SettingsValues::new(1, "smart", Default::default(), None, None),
vec![provider.clone()],
vec![ProviderModel::new(
provider.clone(),
UpstreamModelId::new("model-a").unwrap(),
ModelCapabilities::new(
BTreeSet::from([gateway_core::operation::OperationKind::Generate]),
None,
),
)],
vec![],
)
.unwrap()
.with_account_directory(Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([(
ProviderAccountId::new("acct_member").unwrap(),
RuntimeAccount::new(
provider,
BTreeSet::from([super::group_id(PRIMARY_GROUP_ID)]),
),
)]))));
fixture.published_snapshot.publish(snapshot);
let response = request(router(&fixture), Method::GET, &uri, None, true).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response_json(response).await["data"],
json!({"models":[{"id":"model-a", "label":"model-a"}]})
);
let unauthorized = request(router(&fixture), Method::GET, &uri, None, false).await;
assert_eq!(unauthorized.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn create_route_should_create_an_empty_group() {
let fixture = authenticated_fixture().await;
@@ -106,6 +158,11 @@ async fn create_route_should_create_an_empty_group() {
assert_eq!(value["data"]["record"]["color"], "#A855F780");
assert_eq!(value["data"]["record"]["fastMode"], "default");
assert_eq!(value["data"]["record"]["allowImageGeneration"], true);
assert_eq!(value["data"]["record"]["allowSubagents"], true);
assert_eq!(
value["data"]["record"]["modelAccess"],
json!({"mode":"all","models":[]})
);
assert_eq!(value["data"]["configRevision"], 8);
}
@@ -189,6 +246,8 @@ async fn delete_route_should_return_deleted_id_without_a_live_record() {
async fn list_route_should_reject_unknown_and_invalid_pagination_fields() {
let fixture = authenticated_fixture().await;
for uri in [
"/api/admin/account-groups/models",
"/api/admin/account-groups/models?id=bad",
"/api/admin/account-groups?other=true",
"/api/admin/account-groups?page=0",
"/api/admin/account-groups?pageSize=0",
@@ -345,6 +404,8 @@ async fn fast_mode_group_updates_preserve_omitted_and_null_values() {
for (value, expected) in [
(Some(json!("disabled")), "disabled"),
(None, "disabled"),
(Some(json!("ultrafast")), "ultrafast"),
(None, "ultrafast"),
(Some(json!("enabled")), "enabled"),
(None, "enabled"),
(Some(Value::Null), "enabled"),
@@ -376,6 +437,7 @@ async fn fast_mode_rejects_invalid_values_and_creates_groups_in_each_mode() {
for (mode, expected) in [
(json!("enabled"), StatusCode::CREATED),
(json!("disabled"), StatusCode::CREATED),
(json!("ultrafast"), StatusCode::CREATED),
(json!("default"), StatusCode::CREATED),
(json!("force"), StatusCode::UNPROCESSABLE_ENTITY),
(json!(true), StatusCode::BAD_REQUEST),
@@ -430,3 +492,53 @@ async fn image_generation_flag_round_trips_and_omitted_updates_preserve_it() {
);
}
}
#[tokio::test]
async fn subagent_and_model_policies_round_trip_independently() {
let fixture = authenticated_fixture().await;
let policy = json!({"mode":"allowlist", "models":["model-a"]});
let created = request(
router(&fixture),
Method::POST,
"/api/admin/account-groups/create",
Some(json!({
"name":"Model policy", "color":"#2563EBFF", "modelAccess":policy, "allowSubagents":false
})),
true,
)
.await;
assert_eq!(created.status(), StatusCode::CREATED);
let created = response_json(created).await;
assert_eq!(created["data"]["record"]["modelAccess"], policy);
assert_eq!(created["data"]["record"]["allowSubagents"], false);
let mut update = json!({"id":created["data"]["id"], "name":"Model policy", "color":"#2563EBFF", "allowSubagents":true});
let send = |body| {
request(
router(&fixture),
Method::POST,
"/api/admin/account-groups/update",
Some(body),
true,
)
};
let changed = send(update.clone()).await;
assert_eq!(changed.status(), StatusCode::OK);
let changed = response_json(changed).await;
assert_eq!(changed["data"]["record"]["modelAccess"], policy);
assert_eq!(changed["data"]["record"]["allowSubagents"], true);
update.as_object_mut().unwrap().remove("allowSubagents");
update["modelAccess"] = json!({"mode":"denylist","models":["model-b"]});
let changed = send(update.clone()).await;
assert_eq!(changed.status(), StatusCode::OK);
let changed = response_json(changed).await;
assert_eq!(
changed["data"]["record"]["modelAccess"],
update["modelAccess"]
);
assert_eq!(changed["data"]["record"]["allowSubagents"], true);
update["modelAccess"] = json!({"mode":"allowlist","models":[]});
assert_eq!(
send(update).await.status(),
StatusCode::UNPROCESSABLE_ENTITY
);
}
@@ -12,6 +12,63 @@ use serde_json::json;
use super::{AdminTestFixture, AdminTestState};
#[test]
fn batch_key_form_preserves_omissions_and_accepts_explicit_zero_false_and_inheritance() {
use gateway_api::admin::client_keys::BatchUpdateClientKeysRequest;
use gateway_core::routing::ProviderKind;
let parse = |value| {
serde_json::from_value::<BatchUpdateClientKeysRequest>(value)
.unwrap()
.into_command()
};
let patch = parse(json!({
"ids":["key_a","key_b"], "enabled":false,
"maxConcurrency":0, "dailyLimitUsd":"0", "weeklyLimitUsd":"1.75",
"peerSharing":{"shareQuota":false}, "providerRequestProfileOverrides":{"xai":null}
}))
.unwrap();
assert_eq!(patch.enabled, Some(false));
assert_eq!(patch.max_concurrency, Some(0));
assert_eq!(patch.daily_limit_usd.unwrap().canonical(), "0");
assert_eq!(patch.weekly_limit_usd.unwrap().canonical(), "1.75");
assert_eq!(patch.peer_sharing.share_quota, Some(false));
assert_eq!(patch.peer_sharing.enabled, None);
assert_eq!(patch.requests_per_minute, None);
assert_eq!(patch.group_ids, None);
assert_eq!(patch.installation_seed, None);
assert_eq!(
patch
.request_profile_override_updates
.get(&ProviderKind::new("xai").unwrap()),
Some(&None)
);
for (field, value) in [
("dailyLimitUsd", json!("-0.01")),
("weeklyLimitUsd", json!("1.00000000001")),
("maxConcurrency", json!(u64::MAX)),
("requestsPerMinute", json!(u64::MAX)),
(
"installationSeed",
json!("A3A4E0BDF84447068DF8BFF10DE95B3B"),
),
("providerRequestProfileOverrides", json!({"unknown": null})),
] {
let mut payload = json!({ "ids":["key_a"] });
payload[field] = value;
assert_eq!(parse(payload).unwrap_err().field(), field);
}
let seed = "A3A4E0BD-F844-4706-8DF8-BFF10DE95B3B";
assert_eq!(
parse(json!({"ids":["key_a"], "installationSeed":seed}))
.unwrap()
.installation_seed
.unwrap()
.to_string(),
seed.to_lowercase()
);
}
#[test]
fn reset_budget_requires_an_explicit_supported_period_and_valid_key() {
use gateway_api::admin::client_keys::ResetClientKeyBudgetRequest;
@@ -745,6 +745,8 @@ impl MemoryAccountGroupStore {
primary_id.clone(),
AccountGroupRecord {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
id: primary_id,
name: "Alpha routing".to_owned(),
@@ -768,6 +770,8 @@ impl MemoryAccountGroupStore {
secondary_id.clone(),
AccountGroupRecord {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
id: secondary_id,
name: "Beta routing".to_owned(),
@@ -931,6 +935,8 @@ impl AccountGroupStore for MemoryAccountGroupStore {
let now = Utc::now();
let record = AccountGroupRecord {
allow_image_generation: command.allow_image_generation,
allow_subagents: command.allow_subagents,
model_access: command.model_access,
fast_mode: command.fast_mode,
id: command.id.clone(),
name: command.name,
@@ -966,6 +972,12 @@ impl AccountGroupStore for MemoryAccountGroupStore {
if let Some(fast_mode) = command.fast_mode {
record.fast_mode = fast_mode;
}
if let Some(allowed) = command.allow_subagents {
record.allow_subagents = allowed;
}
if let Some(model_access) = command.model_access {
record.model_access = model_access;
}
if let Some(allowed) = command.allow_image_generation {
record.allow_image_generation = allowed;
}
@@ -1020,6 +1032,19 @@ fn mutation(
#[async_trait]
impl ClientKeyStore for MemoryClientKeyStore {
async fn batch_update_client_keys(
&self,
_: gateway_admin::model::client_keys::BatchUpdateClientKeys,
_: gateway_admin::ports::store::BatchClientKeyProfileMerger,
_: &MutationContext,
) -> AdminStoreResult<Revision> {
Err(AdminStoreError::new(
AdminStoreErrorKind::Unavailable,
"client key",
"unused batch update",
))
}
async fn client_key_budget_window(
&self,
_: &gateway_core::policy::ClientApiKeyId,
@@ -1,4 +1,4 @@
//! 真实 HTTP / WebSocket 路由与 Core 执行入口共同拒绝生图,不触发准入或上游
//! 真实 HTTP / WebSocket 路由与 Core 执行入口共同执行分组功能授权,不触发准入或上游
use super::*;
use axum::{
@@ -11,14 +11,15 @@ use std::{sync::Arc, time::Duration};
use tokio_tungstenite::tungstenite::{Message, client::IntoClientRequest};
use tower::ServiceExt;
fn execution() -> Arc<DefaultExecutionService> {
pub(super) fn execution() -> Arc<DefaultExecutionService> {
Arc::new(DefaultExecutionService::new(
RuntimeSnapshotHandle::new(snapshot_with_image_policy(
"sk_image_policy",
RuntimeSnapshotHandle::new(snapshot_with_group_permissions(
"sk_group_permissions",
"openai",
"key_image_policy",
"key_group_permissions",
&["acct_api_test"],
false,
false,
)),
Arc::new(UnusedExecutionStore),
ProviderRegistry::default(),
@@ -54,7 +55,7 @@ async fn denied_image_requests_return_403_before_admission_or_upstream() {
.clone()
.oneshot(
Request::post(path)
.header(AUTHORIZATION, "Bearer sk_image_policy")
.header(AUTHORIZATION, "Bearer sk_group_permissions")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
@@ -71,7 +72,7 @@ async fn denied_image_requests_return_403_before_admission_or_upstream() {
}
#[tokio::test]
async fn each_websocket_create_enforces_image_policy() {
async fn each_websocket_create_enforces_group_permissions() {
let app = api_router(execution()).await;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
@@ -81,18 +82,33 @@ async fn each_websocket_create_enforces_image_policy() {
let mut request = format!("ws://{address}/v1/responses")
.into_client_request()
.unwrap();
request
.headers_mut()
.insert(AUTHORIZATION, "Bearer sk_image_policy".parse().unwrap());
request.headers_mut().insert(
AUTHORIZATION,
"Bearer sk_group_permissions".parse().unwrap(),
);
let (mut socket, _) = tokio_tungstenite::connect_async(request).await.unwrap();
for image_fields in [
json!({"tools":[{"type":"image_generation"}]}),
json!({"tool_choice":{"type":"image_generation"}}),
for (fields, code) in [
(
json!({"tools":[{"type":"image_generation"}]}),
"image_generation_disabled",
),
(
json!({"client_metadata":{"x-codex-turn-metadata":r#"{"subagent_kind":"thread_spawn"}"#}}),
"subagents_disabled",
),
(
json!({"tool_choice":{"type":"image_generation"}}),
"image_generation_disabled",
),
(
json!({"client_metadata":{"x-openai-subagent":"collab_spawn"}}),
"subagents_disabled",
),
] {
let mut body = json!({"type":"response.create","model":"model-a","input":"test"});
body.as_object_mut()
.unwrap()
.extend(image_fields.as_object().unwrap().clone());
.extend(fields.as_object().unwrap().clone());
socket
.send(Message::Text(body.to_string().into()))
.await
@@ -105,8 +121,38 @@ async fn each_websocket_create_enforces_image_policy() {
let body: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap();
assert_eq!(body["type"], "error", "{body}");
assert_eq!(body["status"], 403);
assert_eq!(body["error"]["code"], "image_generation_disabled");
assert_eq!(body["error"]["code"], code);
}
socket.close(None).await.unwrap();
server.abort();
}
#[tokio::test]
async fn collaboration_requests_are_denied_before_admission_or_upstream() {
let app = api_router(execution()).await;
for (header, value) in [
("x-openai-subagent", "collab_spawn"),
(
"x-codex-turn-metadata",
r#"{"subagent_kind":"thread_spawn"}"#,
),
] {
let response = app
.clone()
.oneshot(
Request::post("/v1/responses")
.header(AUTHORIZATION, "Bearer sk_group_permissions")
.header("content-type", "application/json")
.header(header, value)
.body(Body::from(r#"{"model":"model-a","input":"test"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::FORBIDDEN);
let body: Value =
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap())
.unwrap();
assert_eq!(body["error"]["code"], "subagents_disabled");
}
}
+13 -4
View File
@@ -4,7 +4,7 @@ mod auth;
mod chat_completions;
mod endpoint;
mod error;
mod image_policy;
mod group_permissions;
mod images;
mod live;
mod messages;
@@ -300,15 +300,23 @@ fn snapshot_with_accounts(
client_key_id: &str,
accounts: &[&str],
) -> RuntimeSnapshot {
snapshot_with_image_policy(plaintext, provider_name, client_key_id, accounts, true)
snapshot_with_group_permissions(
plaintext,
provider_name,
client_key_id,
accounts,
true,
true,
)
}
fn snapshot_with_image_policy(
fn snapshot_with_group_permissions(
plaintext: &str,
provider_name: &str,
client_key_id: &str,
accounts: &[&str],
allow_image_generation: bool,
allow_subagents: bool,
) -> RuntimeSnapshot {
let provider = ProviderKind::new(provider_name).expect("provider");
let account_directory = Arc::new(RuntimeAccountDirectory::new(BTreeMap::from_iter(
@@ -345,7 +353,8 @@ fn snapshot_with_image_policy(
Arc::clone(&account_directory),
ClientRoutingScope::all_accounts(),
)
.with_image_generation(allow_image_generation),
.with_image_generation(allow_image_generation)
.with_subagents(allow_subagents),
),
true,
RateLimits::unlimited(),
@@ -406,13 +406,13 @@ async fn model_query_middleware_short_circuit_sets_json_content_type_without_cal
}
#[tokio::test]
async fn native_catalog_preserves_complete_objects_and_only_rewrites_alias_slug() {
async fn native_catalog_preserves_upstream_fields_except_alias_and_group_subagent_policy() {
let original = serde_json::json!({
"slug": "gpt-native", "display_name": "Official name", "priority": 47,
"base_instructions": "Official instructions\nDo not replace.",
"model_messages": {"token_budget": "upstream template", "future_section": [null, {"a": true}]},
"service_tiers": [{"id": "priority", "name": "Fast", "description": "Official speed tier"}],
"tool_mode": "code_mode_only", "use_responses_lite": true,
"tool_mode": "code_mode_only", "use_responses_lite": true, "multi_agent_version": "v2",
"supports_reasoning_summary_parameter": true, "default_reasoning_summary": "detailed",
"future_field": {"nested": [1, null, "value"]}, "explicit_null": null
});
@@ -424,35 +424,49 @@ async fn native_catalog_preserves_complete_objects_and_only_rewrites_alias_slug(
)
.expect("payload"),
};
let execution = Arc::new(ModelsExecution {
client: authenticated_client("sk_models_test"),
presentation: None,
native: Some(Ok(vec![entry("gpt-native"), entry("my-alias")])),
requested_versions: Mutex::default(),
middleware: None,
});
let response = api_router(execution.clone())
.await
.oneshot(authorized_request(
"/v1/models?client_version=0.154.0-alpha.3",
))
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["cache-control"], "private, no-store");
assert!(response.headers().get("etag").is_none());
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
assert_eq!(value["models"][0], original);
let mut alias = original;
alias["slug"] = serde_json::json!("my-alias");
assert_eq!(value["models"][1], alias);
assert_eq!(
*execution.requested_versions.lock().expect("versions"),
["0.154.0-alpha.3"]
);
for (allowed, client) in [
(true, authenticated_client("sk_models_test")),
(
false,
super::group_permissions::execution()
.authenticate("sk_group_permissions")
.unwrap(),
),
] {
let execution = Arc::new(ModelsExecution {
client,
presentation: None,
native: Some(Ok(vec![entry("gpt-native"), entry("my-alias")])),
requested_versions: Mutex::default(),
middleware: None,
});
let response = api_router(execution.clone())
.await
.oneshot(authorized_request(
"/v1/models?client_version=0.154.0-alpha.3",
))
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["cache-control"], "private, no-store");
assert!(response.headers().get("etag").is_none());
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
let mut expected = original.clone();
if !allowed {
expected["multi_agent_version"] = serde_json::json!("disabled");
}
assert_eq!(value["models"][0], expected);
let mut alias = expected;
alias["slug"] = serde_json::json!("my-alias");
assert_eq!(value["models"][1], alias);
assert_eq!(
*execution.requested_versions.lock().expect("versions"),
["0.154.0-alpha.3"]
);
}
}
#[tokio::test]
@@ -1,4 +1,4 @@
//! 账号分组的 Fast 三态策略与多分组优先级
//! 账号分组的快速模式策略与多分组优先级
use serde::{Deserialize, Serialize};
@@ -10,6 +10,7 @@ pub enum FastMode {
Default,
Enabled,
Disabled,
Ultrafast,
}
impl FastMode {
@@ -18,6 +19,7 @@ impl FastMode {
match self {
Self::Default => "default",
Self::Enabled => "enabled",
Self::Ultrafast => "ultrafast",
Self::Disabled => "disabled",
}
}
@@ -27,17 +29,19 @@ impl FastMode {
match value {
"default" => Some(Self::Default),
"enabled" => Some(Self::Enabled),
"ultrafast" => Some(Self::Ultrafast),
"disabled" => Some(Self::Disabled),
_ => None,
}
}
/// 多分组冲突时关闭优先于开启,默认不覆盖其他分组
/// 多分组冲突时禁用优先;同时强制两种加速档位时选用较低的 Fast
#[must_use]
pub const fn merge(self, other: Self) -> Self {
match (self, other) {
(Self::Disabled, _) | (_, Self::Disabled) => Self::Disabled,
(Self::Enabled, _) | (_, Self::Enabled) => Self::Enabled,
(Self::Ultrafast, _) | (_, Self::Ultrafast) => Self::Ultrafast,
_ => Self::Default,
}
}
@@ -88,6 +88,12 @@ impl AccountModelAccess {
AccountModelAccessMode::Denylist => !self.models.contains(upstream_model),
}
}
pub(crate) fn allows_optional_model(&self, upstream_model: Option<&str>) -> bool {
upstream_model.map_or(self.mode == AccountModelAccessMode::All, |model| {
self.allows(model)
})
}
}
#[derive(Deserialize)]
@@ -1,6 +1,6 @@
//! 请求认证时冻结的账号范围与目录,不依赖路由选择器
use super::{FastMode, ProviderAccountId};
use super::{AccountModelAccess, FastMode, ProviderAccountId};
use crate::identity::ProviderKind;
use crate::validation::{IdentifierError, RoutingError};
use std::{
@@ -107,6 +107,7 @@ pub struct RuntimeAccountDirectory {
accounts: BTreeMap<ProviderAccountId, RuntimeAccount>,
providers_with_accounts: BTreeSet<ProviderKind>,
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
}
impl RuntimeAccountDirectory {
@@ -127,9 +128,28 @@ impl RuntimeAccountDirectory {
accounts,
providers_with_accounts,
providers_by_group,
group_model_access: BTreeMap::new(),
}
}
#[must_use]
pub fn with_group_model_access(
mut self,
policies: BTreeMap<AccountGroupId, AccountModelAccess>,
) -> Self {
self.group_model_access = policies;
self
}
pub(crate) fn accounts_in_group(
&self,
group: &AccountGroupId,
) -> impl Iterator<Item = (&ProviderAccountId, &RuntimeAccount)> {
self.accounts
.iter()
.filter(move |(_, account)| account.group_ids.contains(group))
}
#[must_use]
pub fn account(&self, account_id: &ProviderAccountId) -> Option<&RuntimeAccount> {
self.accounts.get(account_id)
@@ -267,6 +287,7 @@ impl ClientRoutingScope {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrozenAccountScope {
allow_image_generation: bool,
allow_subagents: bool,
fast_mode: FastMode,
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
directory: Arc<RuntimeAccountDirectory>,
@@ -303,6 +324,11 @@ impl FrozenAccountScope {
self.allow_image_generation
}
#[must_use]
pub const fn allows_subagents(&self) -> bool {
self.allow_subagents
}
/// 与 Key 授权范围一同冻结;具体字段只由对应 Provider 解释
#[must_use]
pub fn with_request_profiles(
@@ -323,6 +349,12 @@ impl FrozenAccountScope {
&self.request_profiles
}
#[must_use]
pub const fn with_subagents(mut self, allowed: bool) -> Self {
self.allow_subagents = allowed;
self
}
/// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关
#[must_use]
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
@@ -343,6 +375,7 @@ impl FrozenAccountScope {
};
Self {
allow_image_generation: true,
allow_subagents: true,
fast_mode: FastMode::Default,
request_profiles: BTreeMap::new(),
directory,
@@ -399,6 +432,14 @@ impl FrozenAccountScope {
#[must_use]
pub fn allows(&self, account_id: &ProviderAccountId) -> bool {
self.allows_with_policy(account_id, |_| true)
}
fn allows_with_policy(
&self,
account_id: &ProviderAccountId,
accepts: impl Fn(&AccountModelAccess) -> bool,
) -> bool {
let Some(account) = self.directory.account(account_id) else {
return false;
};
@@ -408,6 +449,7 @@ impl FrozenAccountScope {
.allowed_account_ids
.as_ref()
.is_some_and(|accounts| !accounts.contains(account_id))
|| !accepts(account.model_access())
{
return false;
}
@@ -417,18 +459,43 @@ impl FrozenAccountScope {
enabled_group_ids, ..
} => account
.group_ids()
.iter()
.any(|group_id| enabled_group_ids.contains(group_id)),
.intersection(enabled_group_ids)
.any(|id| {
self.directory
.group_model_access
.get(id)
.is_none_or(&accepts)
}),
}
}
#[must_use]
pub fn allows_model(&self, account_id: &ProviderAccountId, upstream_model: &str) -> bool {
self.allows(account_id)
&& self
.directory
.account(account_id)
.is_some_and(|account| account.model_access.allows(upstream_model))
self.allows_with_policy(account_id, |access| access.allows(upstream_model))
}
/// 不猜测原生端点的默认模型,账号与授权它的分组均须允许任意模型
#[must_use]
pub fn allows_unidentified_model(&self, account_id: &ProviderAccountId) -> bool {
self.allows_with_policy(account_id, |access| access.allows_optional_model(None))
}
/// 只报告所有已启用绑定分组均明确拒绝模型的情况,空池沿用原路由错误
#[must_use]
pub fn groups_deny_model(&self, upstream_model: Option<&str>) -> bool {
let ClientRoutingScope::Restricted {
enabled_group_ids, ..
} = &self.client_scope
else {
return false;
};
!enabled_group_ids.is_empty()
&& enabled_group_ids.iter().all(|id| {
self.directory
.group_model_access
.get(id)
.is_some_and(|access| !access.allows_optional_model(upstream_model))
})
}
/// 目录按整个授权账号池过滤,不能只看用于获取元数据的账号政策
@@ -24,6 +24,11 @@ pub(super) fn authentication_gateway_error(error: ClientAuthenticationError) ->
pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> GatewayError {
match error {
crate::validation::RoutingError::GroupModelDenied => GatewayError::new(
GatewayErrorKind::PolicyDenied,
crate::validation::GROUP_MODEL_DENIED_MESSAGE,
)
.with_client_code(crate::validation::GROUP_MODEL_DENIED_CODE),
crate::validation::RoutingError::ModelNotFound {
model,
mapped_model,
@@ -478,9 +478,10 @@ impl DefaultExecutionService {
let budget_key_id = request.client.policy.key_id().clone();
let mut entered_execution = false;
let result = async {
crate::engine::image_generation::check_image_generation(
authorization.account_scope.allows_image_generation(),
crate::engine::group_permissions::check_group_permissions(
&authorization.account_scope,
&request.operation,
&[],
)?;
if authorization.cancellation.is_cancelled() {
return Err(GatewayError::new(
@@ -0,0 +1,36 @@
//! Key 绑定分组的功能权限在请求入口与上游发送前生效
use crate::{
account::scope::FrozenAccountScope, engine::middleware::MiddlewareHeader,
error::DeniedGroupFeature, operation::Operation,
};
pub(super) fn check_group_permissions(
scope: &FrozenAccountScope,
operation: &Operation,
headers: &[MiddlewareHeader],
) -> Result<(), DeniedGroupFeature> {
if !scope.allows_image_generation() && operation.image_generation_requested() {
return Err(DeniedGroupFeature::ImageGeneration);
}
if !scope.allows_subagents()
&& let Operation::Generate(request) = operation
&& request.protocol_payload().protocol() == gateway_protocol::openai::OPENAI_PROTOCOL
{
let payload = request.protocol_payload();
let header = |name: &str| {
headers
.iter()
.find(|header| header.name().eq_ignore_ascii_case(name))
.and_then(|header| std::str::from_utf8(header.value()).ok())
};
if gateway_protocol::openai::codex::collaboration_subagent_requested(
payload.body(),
payload.context(),
header,
) {
return Err(DeniedGroupFeature::CollaborativeSubagents);
}
}
Ok(())
}
@@ -1,20 +0,0 @@
//! 冻结分组生图权限的请求与发送前门禁
use crate::{
error::{GatewayError, GatewayErrorKind},
operation::Operation,
};
pub(super) fn check_image_generation(
allowed: bool,
operation: &Operation,
) -> Result<(), GatewayError> {
if !allowed && operation.image_generation_requested() {
return Err(GatewayError::new(
GatewayErrorKind::PolicyDenied,
"Image generation is not allowed by the API key's account groups.",
)
.with_client_code("image_generation_disabled"));
}
Ok(())
}
+6 -10
View File
@@ -10,7 +10,7 @@ pub mod continuation;
pub mod coordinator;
pub mod execution;
pub mod extensions;
mod image_generation;
mod group_permissions;
pub mod middleware;
pub mod nested;
pub mod observation;
@@ -777,19 +777,15 @@ impl AttemptContext {
terminal: provider::ProviderMiddlewareTerminal,
) -> Result<provider::ProviderStream, ProviderError> {
// 入口已校验原请求,此处复查中间件最终提交的 operation,每次重试均生效
let terminal: provider::ProviderMiddlewareTerminal = if self
let terminal: provider::ProviderMiddlewareTerminal = if let Some(scope) = self
.account_scope()
.is_some_and(|scope| !scope.allows_image_generation())
.filter(|scope| !scope.allows_image_generation() || !scope.allows_subagents())
{
let scope = Arc::clone(scope);
Box::new(move |operation, headers| {
Box::pin(async move {
image_generation::check_image_generation(false, &operation).map_err(|_| {
ProviderError::new(
ProviderErrorKind::RequestPolicyDenied,
UpstreamSendState::NotSent,
)
.with_retry_prohibited()
})?;
group_permissions::check_group_permissions(&scope, &operation, &headers)
.map_err(ProviderError::group_feature_denied)?;
terminal(operation, headers).await
})
})
+39 -3
View File
@@ -508,6 +508,7 @@ impl fmt::Debug for ClientVisibleUpstreamResponse {
/// Core 会在任何持久化或日志记录前取走
/// 这些事件,不能把它们当作诊断上下文使用
pub struct ProviderError {
denied_group_feature: Option<DeniedGroupFeature>,
kind: ProviderErrorKind,
send_state: UpstreamSendState,
upstream_status: Option<u16>,
@@ -556,6 +557,7 @@ impl ProviderError {
Self {
kind,
send_state,
denied_group_feature: None,
upstream_status: None,
upstream_values: None,
retry_after: None,
@@ -579,6 +581,16 @@ impl ProviderError {
}
}
pub(crate) fn group_feature_denied(feature: DeniedGroupFeature) -> Self {
let mut error = Self::new(
ProviderErrorKind::RequestPolicyDenied,
UpstreamSendState::NotSent,
)
.with_retry_prohibited();
error.denied_group_feature = Some(feature);
error
}
/// 附加合法上游状态码
#[must_use]
pub fn with_status(mut self, status: u16) -> Self {
@@ -1057,6 +1069,7 @@ impl ProviderError {
pub fn stable_snapshot(&self) -> Self {
Self {
kind: self.kind,
denied_group_feature: self.denied_group_feature,
send_state: self.send_state,
upstream_status: self.upstream_status,
upstream_values: self.upstream_values.clone(),
@@ -1241,6 +1254,28 @@ impl GatewayErrorKind {
}
}
#[derive(Clone, Copy)]
pub(crate) enum DeniedGroupFeature {
ImageGeneration,
CollaborativeSubagents,
}
impl From<DeniedGroupFeature> for GatewayError {
fn from(feature: DeniedGroupFeature) -> Self {
let (code, message) = match feature {
DeniedGroupFeature::ImageGeneration => (
"image_generation_disabled",
"Image generation is not allowed by the API key's account groups.",
),
DeniedGroupFeature::CollaborativeSubagents => (
"subagents_disabled",
"Collaborative subagents are not allowed by the API key's account groups.",
),
};
Self::new(GatewayErrorKind::PolicyDenied, message).with_client_code(code)
}
}
/// 协议无关、可安全暴露的网关错误
#[derive(Clone, Error)]
#[error("{message}")]
@@ -1342,9 +1377,10 @@ impl GatewayError {
GatewayErrorKind::UpstreamUnavailable,
"The upstream account cannot access the service.",
),
ProviderErrorKind::RequestPolicyDenied => {
Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy.")
}
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
Self::from,
),
ProviderErrorKind::RateLimited | ProviderErrorKind::QuotaExhausted => Self::new(
GatewayErrorKind::RateLimited,
"Upstream capacity is temporarily unavailable.",
@@ -1,6 +1,6 @@
//! 下游 Client API Key 的准入策略
//!
//! Client API Key 冻结账号分组权限;模型名称不参与权限判断
//! Client API Key 在请求开始时冻结分组成员范围及其模型策略
mod client_version;
mod peer_sharing;
@@ -537,18 +537,11 @@ pub struct RoutingContext {
pub struct ProviderCandidate {
provider: ProviderKind,
upstream_model: Option<UpstreamModelId>,
model_presentation: Option<ModelPresentation>,
emulated_features: BTreeSet<Feature>,
account_scope: Arc<FrozenAccountScope>,
}
impl ProviderCandidate {
/// 与路由计划冻结的上游模型目录,重试时不读取新的目录代次
#[must_use]
pub const fn model_presentation(&self) -> Option<&ModelPresentation> {
self.model_presentation.as_ref()
}
#[must_use]
pub const fn provider(&self) -> &ProviderKind {
&self.provider
@@ -83,7 +83,9 @@ impl SnapshotClientPolicyFacts {
/// Store 读取到的账号分组事实
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotAccountGroupFacts {
model_access: crate::account::AccountModelAccess,
allow_image_generation: bool,
allow_subagents: bool,
fast_mode: FastMode,
id: AccountGroupId,
name: String,
@@ -91,12 +93,24 @@ pub struct SnapshotAccountGroupFacts {
}
impl SnapshotAccountGroupFacts {
#[must_use]
pub fn with_model_access(mut self, model_access: crate::account::AccountModelAccess) -> Self {
self.model_access = model_access;
self
}
#[must_use]
pub const fn with_image_generation(mut self, allowed: bool) -> Self {
self.allow_image_generation = allowed;
self
}
#[must_use]
pub const fn with_subagents(mut self, allowed: bool) -> Self {
self.allow_subagents = allowed;
self
}
#[must_use]
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
self.fast_mode = fast_mode;
@@ -106,10 +120,12 @@ impl SnapshotAccountGroupFacts {
#[must_use]
pub fn new(id: AccountGroupId, name: String, enabled: bool) -> Self {
Self {
model_access: crate::account::AccountModelAccess::all(),
id,
name,
enabled,
allow_image_generation: true,
allow_subagents: true,
fast_mode: FastMode::Default,
}
}
@@ -549,12 +565,24 @@ async fn compile_runtime_snapshot(
account.direct_authentication_kind().map(str::to_owned),
);
}
let account_directory = Arc::new(RuntimeAccountDirectory::new(accounts));
// 整份快照共享分组模型政策;默认规则无需为每个 Key 或成员复制
let group_model_access = groups
.values_mut()
.filter(|group| {
group.enabled
&& group.model_access.mode() != crate::account::AccountModelAccessMode::All
})
.map(|group| (group.id.clone(), std::mem::take(&mut group.model_access)))
.collect();
let account_directory = Arc::new(
RuntimeAccountDirectory::new(accounts).with_group_model_access(group_model_access),
);
let mut client_policies = Vec::with_capacity(facts.client_policies.len());
for policy in facts.client_policies {
let mut fast_mode = FastMode::Default;
let mut allow_image_generation = true;
let mut allow_subagents = true;
let account_scope = if policy.group_ids.is_empty() {
FrozenAccountScope::new(
Arc::clone(&account_directory),
@@ -574,6 +602,7 @@ async fn compile_runtime_snapshot(
// 停用只影响选号,仍绑定的分组继续贡献请求策略
fast_mode = fast_mode.merge(group.fast_mode);
allow_image_generation &= group.allow_image_generation;
allow_subagents &= group.allow_subagents;
bound_groups.push(RoutingGroupSnapshot::new(
group.id.clone(),
group.name.clone(),
@@ -597,6 +626,7 @@ async fn compile_runtime_snapshot(
Arc::new(
account_scope
.with_image_generation(allow_image_generation)
.with_subagents(allow_subagents)
.with_fast_mode(fast_mode)
.with_request_profiles(policy.request_profiles),
),
@@ -967,6 +997,54 @@ impl RuntimeSnapshot {
.collect()
}
/// 分组编辑器使用成员账号的实际模型,可编辑已停用或已限制模型的分组
#[must_use]
pub fn upstream_models_for_group(&self, group: &AccountGroupId) -> Vec<UpstreamModelId> {
let mut models = BTreeSet::new();
for (account_id, account) in self.account_directory.accounts_in_group(group) {
let provider = account.provider_kind();
if !self.providers.contains(provider) {
continue;
}
let access = account.model_access();
if access.mode() == crate::account::AccountModelAccessMode::Allowlist {
// 原生图片、Search 和透传模型可能只有账号白名单明确声明了 ID
models.extend(
access
.models()
.iter()
.filter_map(|id| UpstreamModelId::new(id.clone()).ok()),
);
}
let sources = self.model_catalog_accounts.get(provider);
if let Some(catalog) = self.provider_models.get(provider) {
models.extend(
catalog
.keys()
.filter(|model| {
access.allows(model.as_str())
&& sources
.and_then(|sources| sources.get(model.as_str()))
.is_none_or(|sources| sources.contains(account_id))
})
.cloned(),
);
}
for contribution in self.contributed_models() {
if &contribution.provider == provider && contribution.accounts.contains(account_id)
{
let target = self.mapped_model(contribution.id.as_str());
if access.allows(&target)
&& let Ok(model) = UpstreamModelId::new(target)
{
models.insert(model);
}
}
}
}
models.into_iter().collect()
}
/// 合并冻结账号范围内实际存在 Provider 的公开模型
#[must_use]
pub fn public_models_for_scope(&self, scope: &FrozenAccountScope) -> Vec<PublicModelId> {
@@ -1285,6 +1363,11 @@ impl RuntimeSnapshot {
UpstreamModelId::from_client_wire(mapped_model)
}
.map_err(|_| RoutingError::InvalidIdentifier)?;
if enforce_account_model_policy
&& account_scope.groups_deny_model(Some(upstream_model.as_str()))
{
return Err(RoutingError::GroupModelDenied);
}
// 归属先于账号范围、能力与路由约束判定,原 Provider 被排除不能变成跨平台透传
let known_model = self.is_known_upstream_model(&upstream_model)
|| self
@@ -1385,16 +1468,6 @@ impl RuntimeSnapshot {
};
candidates.push(ProviderCandidate {
provider: provider.clone(),
model_presentation: self
.provider_model_presentations
.get(provider)
.and_then(|models| models.get(&upstream_model))
.cloned()
.or_else(|| {
contributions
.first()
.map(|model| model.presentation.clone())
}),
upstream_model: Some(upstream_model.clone()),
emulated_features,
account_scope: candidate_scope,
@@ -1471,6 +1544,12 @@ impl RuntimeSnapshot {
.as_ref()
.is_none_or(|required| required == provider)
&& !context.blocked_providers.contains(provider);
if available
&& upstream_model
.is_some_and(|model| account_scope.groups_deny_model(Some(model.as_str())))
{
return Err(RoutingError::GroupModelDenied);
}
if !available
|| upstream_model
.is_some_and(|model| !account_scope.allows_provider_model(provider, model.as_str()))
@@ -1506,13 +1585,6 @@ impl RuntimeSnapshot {
}
let candidate = ProviderCandidate {
provider: provider.clone(),
model_presentation: upstream_model
.and_then(|model| {
self.provider_model_presentations
.get(provider)
.and_then(|models| models.get(model))
})
.cloned(),
upstream_model: upstream_model.cloned(),
emulated_features: BTreeSet::new(),
account_scope: Arc::clone(&account_scope),
@@ -54,6 +54,12 @@ pub enum OperationError {
},
}
/// Core 路由和 Provider 原生端点共用的分组模型拒绝码
pub const GROUP_MODEL_DENIED_CODE: &str = "group_model_denied";
/// 拒绝原因不回显请求模型或分组名称
pub const GROUP_MODEL_DENIED_MESSAGE: &str =
"Model is not allowed by the API key's account groups.";
/// 路由快照或 Route Plan 不满足不变量
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum RoutingError {
@@ -72,6 +78,9 @@ pub enum RoutingError {
/// Key 的账号范围中当前没有任何可参与路由的账号
#[error("account routing scope is empty")]
EmptyAccountScope,
/// 已启用的绑定分组均明确禁止请求模型
#[error("{GROUP_MODEL_DENIED_MESSAGE}")]
GroupModelDenied,
/// 快照中存在重复实体
#[error("duplicate {entity} `{id}`")]
DuplicateEntity {
@@ -6268,7 +6268,12 @@ fn deadline_before_first_event_is_persisted_as_failed_attempt() {
#[test]
fn global_location_and_group_fast_policy_reach_every_account_retry() {
for mode in [FastMode::Default, FastMode::Enabled, FastMode::Disabled] {
for mode in [
FastMode::Default,
FastMode::Enabled,
FastMode::Ultrafast,
FastMode::Disabled,
] {
let operation = generate_operation();
let location = gateway_core::account::RequestLocation {
timezone: "Asia/Tokyo".parse().unwrap(),
@@ -736,31 +736,43 @@ impl MiddlewarePlan for AddingImageTool {
}
#[test]
fn attempt_middleware_cannot_add_image_generation_to_a_denied_scope() {
fn attempt_middleware_cannot_add_a_group_denied_feature() {
use gateway_core::account::{AccountSelectionPolicy, RotationStrategy};
use gateway_core::engine::{AccountAttemptContext, AttemptContext, RequestAttemptContext};
use gateway_core::error::ProviderErrorKind;
use gateway_core::routing::{ClientRoutingScope, FrozenAccountScope, RuntimeAccountDirectory};
use gateway_core::upstream::UpstreamSendState;
for allowed in [false, true] {
for (allowed, image) in [(true, true), (false, true), (true, false), (false, false)] {
let scope = FrozenAccountScope::new(
Arc::new(RuntimeAccountDirectory::new(Default::default())),
ClientRoutingScope::all_accounts(),
)
.with_image_generation(allowed);
let request = RequestAttemptContext::new(
ModelRequestId::new("req_image_policy").unwrap(),
ClientApiKeyId::new("key_image_policy").unwrap(),
)
.with_middleware(
Some(FrozenMiddlewarePlan::new(
.with_image_generation(!image || allowed)
.with_subagents(image || allowed);
let plan = if image {
FrozenMiddlewarePlan::new(
Arc::new(AddingImageTool),
ExtensionSetReference::new(
ExtensionSetId::new("image-policy-test".to_owned()).unwrap(),
Arc::new(ReadyGeneration),
),
)),
)
} else {
header_plan(
"subagent-policy-test",
vec![MiddlewareHeader::new(
"x-openai-subagent",
Bytes::from_static(b"collab_spawn"),
)],
)
};
let request = RequestAttemptContext::new(
ModelRequestId::new("req_group_permissions").unwrap(),
ClientApiKeyId::new("key_group_permissions").unwrap(),
)
.with_middleware(
Some(plan),
Arc::from([]),
"/v1/responses".into(),
ClientTransport::HttpJson,
@@ -782,9 +794,17 @@ fn attempt_middleware_cannot_add_image_generation_to_a_denied_scope() {
ProviderKind::new("openai").unwrap(),
Some("gpt-test".into()),
ProviderAccountId::new("acct_middleware").unwrap(),
Box::new(move |operation, _| {
Box::new(move |operation, headers| {
Box::pin(async move {
assert!(operation.image_generation_requested());
if image {
assert!(operation.image_generation_requested());
} else {
assert!(
headers
.iter()
.any(|header| header.name() == "x-openai-subagent")
);
}
count.fetch_add(1, Ordering::SeqCst);
Ok(empty_provider_stream())
})
@@ -796,10 +816,19 @@ fn attempt_middleware_cannot_add_image_generation_to_a_denied_scope() {
} else {
let error = match result {
Err(error) => error,
Ok(_) => panic!("image tool must be denied"),
Ok(_) => panic!("group feature must be denied"),
};
assert_eq!(error.kind(), ProviderErrorKind::RequestPolicyDenied);
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
let gateway = gateway_core::error::GatewayError::from_provider(&error);
assert_eq!(
gateway.client_error_code(),
Some(if image {
"image_generation_disabled"
} else {
"subagents_disabled"
})
);
assert!(error.retry_is_prohibited());
}
}
@@ -728,6 +728,161 @@ impl ProviderCatalogPort for PublishingCatalog {
}
}
#[test]
fn group_model_access_requires_a_common_group_for_account_and_mapped_model() {
use gateway_core::{
account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId},
routing::AccountGroupId,
validation::RoutingError,
};
let group = |n| AccountGroupId::new(format!("grp_{n:032x}")).unwrap();
let account = |id| ProviderAccountId::new(id).unwrap();
let policy = |mode, models: &[&str]| {
AccountModelAccess::new(mode, models.iter().map(|id| (*id).to_owned()).collect()).unwrap()
};
let (a, b, shared) = (account("acct_a"), account("acct_b"), account("acct_shared"));
let (first, second, disabled) = (group(1), group(2), group(3));
let key = ClientApiKeyId::new("key_groups").unwrap();
let facts = SnapshotFacts::new(
revision(1),
revision(1),
SettingsValues::new(
3,
"smart",
[("alias".into(), "listed-model".into())].into(),
None,
None,
),
vec![SnapshotClientPolicyFacts::new(
key.clone(),
PlaintextClientApiKey::new("sk_groups").unwrap(),
vec![first.clone(), second.clone(), disabled.clone()],
RateLimits::unlimited(),
)],
vec![
SnapshotAccountGroupFacts::new(first.clone(), "First".into(), true)
.with_model_access(policy(AccountModelAccessMode::Allowlist, &["listed-model"])),
SnapshotAccountGroupFacts::new(second.clone(), "Second".into(), true)
.with_model_access(policy(
AccountModelAccessMode::Denylist,
&["listed-model", "blocked"],
)),
SnapshotAccountGroupFacts::new(disabled.clone(), "Disabled".into(), false),
],
vec![
SnapshotProviderAccountFacts::new(a.clone(), "alpha"),
SnapshotProviderAccountFacts::new(b.clone(), "alpha"),
SnapshotProviderAccountFacts::new(shared.clone(), "alpha").with_model_access(policy(
AccountModelAccessMode::Allowlist,
&["listed-model", "image-model"],
)),
],
vec![
SnapshotAccountGroupMemberFacts::new(first.clone(), a.clone()),
SnapshotAccountGroupMemberFacts::new(second.clone(), b.clone()),
SnapshotAccountGroupMemberFacts::new(first.clone(), shared.clone()),
SnapshotAccountGroupMemberFacts::new(second.clone(), shared.clone()),
SnapshotAccountGroupMemberFacts::new(disabled.clone(), b.clone()),
],
);
let snapshot = block_on(
RuntimeSnapshotCompiler::new(
Arc::new(TestSnapshotStore::new(Ok(facts))),
Arc::new(TestCatalog::Discovery),
)
.compile(),
)
.unwrap();
let scope = snapshot.client_policy(&key).unwrap().account_scope();
let alias = PublicModelId::new("alias").unwrap();
let plan = snapshot
.plan(
&alias,
&super::operation(),
Arc::clone(scope),
&Default::default(),
)
.unwrap();
let candidate = &plan.candidates()[0];
assert_eq!(candidate.upstream_model().unwrap().as_str(), "listed-model");
assert!(candidate.account_scope().allows_model(&a, "listed-model"));
assert!(!candidate.account_scope().allows_model(&b, "listed-model"));
assert!(scope.allows_model(&b, "other"));
assert!(scope.allows_model(&shared, "listed-model"));
assert!(scope.allows_model(&shared, "image-model"));
assert!(!scope.allows_model(&shared, "other"));
assert!(!scope.allows_unidentified_model(&b));
assert!(scope.groups_deny_model(None));
assert!(snapshot.contains_public_model_for_scope(&alias, scope));
let b_only = scope.restricted_to(&Default::default(), &[b.clone()].into());
assert!(!snapshot.public_models_for_scope(&b_only).contains(&alias));
assert!(!snapshot.contains_public_model_for_scope(&alias, &b_only));
assert!(!snapshot.allows_public_model_for_account(&alias, scope, &b));
let blocked = PublicModelId::new("blocked").unwrap();
assert!(matches!(
snapshot.plan(
&blocked,
&super::operation(),
Arc::clone(scope),
&Default::default()
),
Err(RoutingError::GroupModelDenied)
));
assert!(matches!(
snapshot.plan_provider_endpoint(
&ProviderKind::new("alpha").unwrap(),
Some(&UpstreamModelId::new("blocked").unwrap()),
&super::operation(),
Arc::clone(scope),
&Default::default()
),
Err(RoutingError::GroupModelDenied)
));
assert!(snapshot.all_account_scope().allows_model(&b, "blocked"));
assert!(snapshot.all_account_scope().allows_unidentified_model(&b));
assert_eq!(
snapshot.upstream_models_for_group(&second),
["image-model", "listed-model"].map(|id| UpstreamModelId::new(id).unwrap())
);
assert_eq!(
snapshot.upstream_models_for_group(&disabled),
vec![UpstreamModelId::new("listed-model").unwrap()]
);
assert!(snapshot.upstream_models_for_group(&group(4)).is_empty());
// 第二组允许此模型,但适配器只绑定到第一组的账号
let adapted = PublicModelId::new("adapter-only").unwrap();
let scope = Arc::clone(scope);
let snapshot = snapshot.with_extensions(Some(ExtensionSetReference::new(
ExtensionSetId::new("group-adapter".into()).unwrap(),
Arc::new(ModelLease(vec![gateway_core::routing::ContributedModel {
owner: "fixture".into(),
id: adapted.clone(),
provider: ProviderKind::new("alpha").unwrap(),
accounts: [a].into(),
capabilities: super::capabilities(),
presentation: ModelPresentation::new(Some("Adapter".into()), None),
}])),
)));
assert!(!snapshot.contains_public_model_for_scope(&adapted, &scope));
assert!(
snapshot
.plan(&adapted, &super::operation(), scope, &Default::default())
.is_err()
);
let upstream = UpstreamModelId::new("adapter-only").unwrap();
assert!(
snapshot
.upstream_models_for_group(&first)
.contains(&upstream)
);
assert!(
!snapshot
.upstream_models_for_group(&second)
.contains(&upstream)
);
}
#[test]
fn compiler_should_reject_revision_changed_during_consistent_read() {
let store = Arc::new(SequencedSnapshotStore {
@@ -1769,6 +1924,17 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
(FastMode::Disabled, FastMode::Default, FastMode::Disabled),
(FastMode::Disabled, FastMode::Enabled, FastMode::Disabled),
(FastMode::Disabled, FastMode::Disabled, FastMode::Disabled),
(FastMode::Default, FastMode::Ultrafast, FastMode::Ultrafast),
(FastMode::Ultrafast, FastMode::Default, FastMode::Ultrafast),
(
FastMode::Ultrafast,
FastMode::Ultrafast,
FastMode::Ultrafast,
),
(FastMode::Enabled, FastMode::Ultrafast, FastMode::Enabled),
(FastMode::Ultrafast, FastMode::Enabled, FastMode::Enabled),
(FastMode::Disabled, FastMode::Ultrafast, FastMode::Disabled),
(FastMode::Ultrafast, FastMode::Disabled, FastMode::Disabled),
] {
for group_enabled in [false, true] {
for bound in [false, true] {
@@ -1847,7 +2013,7 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
}
#[test]
fn image_generation_merges_bound_groups_with_deny_precedence() {
fn group_feature_permissions_merge_independently_with_deny_precedence() {
use gateway_core::account::ProviderAccountId;
use gateway_core::routing::AccountGroupId;
for (allowed, other_allowed) in [(true, true), (true, false), (false, true), (false, false)] {
@@ -1877,13 +2043,15 @@ fn image_generation_merges_bound_groups_with_deny_precedence() {
"Restricted".to_owned(),
group_enabled,
)
.with_image_generation(allowed),
.with_image_generation(allowed)
.with_subagents(!allowed),
SnapshotAccountGroupFacts::new(
open_group_id.clone(),
"Open".to_owned(),
true,
)
.with_image_generation(other_allowed),
.with_image_generation(other_allowed)
.with_subagents(!other_allowed),
],
vec![SnapshotProviderAccountFacts::new(
account_id.clone(),
@@ -1909,6 +2077,10 @@ fn image_generation_merges_bound_groups_with_deny_precedence() {
.account_scope()
.clone();
assert!(scope.allows(&account_id));
assert_eq!(
scope.allows_subagents(),
!bound || (!allowed && !other_allowed)
);
assert_eq!(
scope.allows_image_generation(),
!bound || (allowed && other_allowed),
@@ -74,6 +74,8 @@ impl PluginResources {
request.resource_key,
CreateAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: gateway_core::account::FastMode::Default,
name: request.name,
description: request.description,
@@ -25,6 +25,8 @@ use std::{path::Path, sync::Arc, time::Duration};
fn group(name: &str) -> CreateAccountGroup {
CreateAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
name: name.into(),
description: None,
fast_mode: FastMode::Default,
@@ -1,16 +1,18 @@
//! 验证中间件 Fast 三态设置与运行时故障隔离
//! 验证中间件 快速模式设置与运行时故障隔离
use super::*;
use gateway_core::{policy::ClientPolicy, routing::request_settings::RequestSettings};
use serde_json::{Value, json};
#[tokio::test]
async fn middleware_preserves_three_state_fast_and_sources() {
async fn middleware_preserves_fast_modes_and_sources() {
for (mode, expected) in [
(FastMode::Default, FastMode::Default),
(FastMode::Enabled, FastMode::Enabled),
(FastMode::Disabled, FastMode::Disabled),
(FastMode::Enabled, FastMode::Disabled),
(FastMode::Ultrafast, FastMode::Ultrafast),
(FastMode::Enabled, FastMode::Ultrafast),
(FastMode::Disabled, FastMode::Default),
] {
let snapshot = gateway_core::routing::RuntimeSnapshot::new(
@@ -382,9 +382,14 @@ async fn account_scoped_adapters_share_a_model_without_sharing_their_targets() {
}
#[tokio::test]
async fn adapter_preserves_three_state_fast_in_request_metadata() {
async fn adapter_preserves_group_fast_mode_in_request_metadata() {
use gateway_core::account::FastMode;
for mode in [FastMode::Default, FastMode::Enabled, FastMode::Disabled] {
for mode in [
FastMode::Default,
FastMode::Enabled,
FastMode::Ultrafast,
FastMode::Disabled,
] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/adapter/responses"))
@@ -188,6 +188,8 @@ impl Environment {
.create_account_group(
NewAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
id: id.clone(),
name: format!("fixture {}", id.as_str()),
@@ -493,7 +493,7 @@ OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。
`fast_mode` 使用 `default`、`enabled`、`disabled` 三态,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
`fast_mode` 使用 `default`、`enabled`、`ultrafast`、`disabled` 四个值,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
`runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。
SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。
线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。
@@ -41,7 +41,7 @@ Provider、业务协议和传输名称不能写入宿主兼容清单的 capabili
`TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影;
原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件
`fast_mode` 是本次模型执行的有效设置,取值为 `default`、`enabled` 或 `disabled`。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
`fast_mode` 是本次模型执行的有效设置,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。
其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt)
@@ -182,11 +182,7 @@ pub fn codex_responses_request_semantics_with_turn_metadata(
let reasoning_effort = reasoning_effort_override
.clone()
.or_else(|| reasoning_effort(body.get("reasoning")));
// 权威上下文与显式 turnMetadata 即使为空也不退回其他别名
let parsed_turn_metadata = turn_metadata
.or_else(|| body.get("turnMetadata").and_then(Value::as_str))
.or_else(|| request_turn_metadata(body))
.and_then(|value| serde_json::from_str::<Value>(value).ok());
let parsed_turn_metadata = parsed_turn_metadata(body, turn_metadata);
let mut request_kind = parsed_turn_metadata
.as_ref()
.and_then(|metadata| non_empty_string(metadata.get("request_kind")))
@@ -229,6 +225,34 @@ fn reasoning_effort(reasoning: Option<&Value>) -> Option<String> {
.or_else(|| effort.as_u64().map(|value| value.to_string()))
}
/// 只识别协作线程自己的生成请求,review、compact、guardian 和父线程的工具历史均不受限
#[must_use]
pub fn collaboration_subagent_requested<'a>(
body: &Map<String, Value>,
context: &Map<String, Value>,
header: impl Fn(&str) -> Option<&'a str>,
) -> bool {
let is_spawn = |kind: &str| matches!(kind.trim(), "thread_spawn" | "collab_spawn");
let subagent =
header("x-openai-subagent").or_else(|| non_empty_string(context.get("subagent")));
let turn_metadata =
header("x-codex-turn-metadata").or_else(|| context_turn_metadata(body, context));
subagent.is_some_and(is_spawn)
|| client_metadata_string(body, "x-openai-subagent").is_some_and(is_spawn)
|| parsed_turn_metadata(body, turn_metadata)
.as_ref()
.and_then(|metadata| non_empty_string(metadata.get("subagent_kind")))
.is_some_and(is_spawn)
}
fn parsed_turn_metadata(body: &Map<String, Value>, turn_metadata: Option<&str>) -> Option<Value> {
// 权威上下文与显式 turnMetadata 即使为空也不退回其他别名
turn_metadata
.or_else(|| body.get("turnMetadata").and_then(Value::as_str))
.or_else(|| request_turn_metadata(body))
.and_then(|value| serde_json::from_str(value).ok())
}
fn request_turn_metadata(body: &Map<String, Value>) -> Option<&str> {
non_empty_string(body.get("turnMetadata"))
.or_else(|| non_empty_string(body.get("turn_metadata")))
@@ -348,3 +348,38 @@ fn request_observation_classifies_prewarm_from_generate() {
assert_eq!(observation.subagent_kind.as_deref(), Some("worker"));
}
}
#[test]
fn only_collaboration_children_match_subagent_policy() {
use gateway_protocol::openai::codex::collaboration_subagent_requested;
let context = object(json!({}));
for (kind, expected) in [
("thread_spawn", true),
("collab_spawn", true),
("review", false),
("compact", false),
("guardian", false),
("future", false),
] {
let body = object(json!({"input": [{"type":"function_call", "name":"spawn_agent"}]}));
assert!(!collaboration_subagent_requested(&body, &context, |_| None));
let metadata = json!({"subagent_kind": kind}).to_string();
assert_eq!(
collaboration_subagent_requested(&body, &context, |name| (name
== "x-codex-turn-metadata")
.then_some(metadata.as_str())),
expected
);
assert_eq!(
collaboration_subagent_requested(&body, &context, |name| (name == "x-openai-subagent")
.then_some(kind)),
expected
);
let body = object(json!({"client_metadata": {"x-openai-subagent": kind}}));
assert_eq!(
collaboration_subagent_requested(&body, &context, |_| None),
expected
);
}
}
@@ -316,6 +316,9 @@ impl AccountGroupStore for PgAccountGroupRepository {
vec![
"name".to_owned(),
"description".to_owned(),
"color".to_owned(),
"allow_subagents".to_owned(),
"model_access".to_owned(),
"fast_mode".to_owned(),
"allow_image_generation".to_owned(),
],
@@ -342,23 +345,37 @@ impl AccountGroupStore for PgAccountGroupRepository {
) -> AdminStoreResult<AccountGroupMutation> {
validate_group_fields(&command.name, command.description.as_deref())?;
let id = command.id.clone();
let mut fields = vec![
"name".to_owned(),
"description".to_owned(),
"color".to_owned(),
];
for (field, supplied) in [
("allow_subagents", command.allow_subagents.is_some()),
("model_access", command.model_access.is_some()),
("fast_mode", command.fast_mode.is_some()),
(
"allow_image_generation",
command.allow_image_generation.is_some(),
),
] {
if supplied {
fields.push(field.to_owned());
}
}
let audit = mutation_audit(
context,
MutationAuditOperation::AccountGroupUpdate,
id.as_str(),
vec![
"name".to_owned(),
"description".to_owned(),
"fast_mode".to_owned(),
"allow_image_generation".to_owned(),
],
fields,
);
let revision = self
.mutate(audit, |transaction| {
Box::pin(async move {
let result = sqlx::query(
"update account_groups
set name = $2, description = $3, color = $4, fast_mode = coalesce($5, fast_mode), allow_image_generation = coalesce($6, allow_image_generation), updated_at = now()
set name = $2, description = $3, color = $4, fast_mode = coalesce($5, fast_mode), allow_image_generation = coalesce($6, allow_image_generation),
allow_subagents = coalesce($7, allow_subagents), model_access_json = coalesce($8, model_access_json), updated_at = now()
where id = $1",
)
.bind(command.id.as_str())
@@ -367,6 +384,8 @@ impl AccountGroupStore for PgAccountGroupRepository {
.bind(command.color.as_str())
.bind(command.fast_mode.map(FastMode::as_str))
.bind(command.allow_image_generation)
.bind(command.allow_subagents)
.bind(command.model_access.map(sqlx::types::Json))
.execute(&mut **transaction)
.await
.map_err(|error| map_group_write_error(error, command.id.as_str()))?;
@@ -474,7 +493,7 @@ impl AccountGroupStore for PgAccountGroupRepository {
fn group_select() -> QueryBuilder<Postgres> {
QueryBuilder::new(
"select g.id, g.name, g.description, g.color, g.enabled, g.fast_mode, g.allow_image_generation, g.created_at, g.updated_at,
"select g.id, g.name, g.description, g.color, g.enabled, g.fast_mode, g.allow_image_generation, g.allow_subagents, g.model_access_json, g.created_at, g.updated_at,
coalesce(members.member_count, 0)::bigint as member_count,
coalesce(keys.client_key_count, 0)::bigint as client_key_count,
coalesce(members.provider_counts, '{}'::jsonb) as provider_counts
@@ -552,6 +571,13 @@ fn group_record(row: &sqlx::postgres::PgRow) -> StoreResult<AccountGroupRecord>
let provider_counts = serde_json::from_value::<BTreeMap<String, u64>>(provider_counts)
.map_err(|source| invalid("invalid provider counts").with_source(source))?;
Ok(AccountGroupRecord {
allow_subagents: row
.try_get("allow_subagents")
.map_err(|source| invalid("invalid subagent policy").with_source(source))?,
model_access: row
.try_get::<sqlx::types::Json<_>, _>("model_access_json")
.map_err(|source| invalid("invalid model access policy").with_source(source))?
.0,
allow_image_generation: row
.try_get("allow_image_generation")
.map_err(|source| invalid("invalid image generation policy").with_source(source))?,
@@ -747,8 +773,8 @@ pub(crate) async fn insert_account_group_in_transaction(
.map_err(|source| invalid("invalid account group fields").with_source(source))?;
sqlx::query(
"insert into account_groups
(id, name, description, color, fast_mode, allow_image_generation, enabled, created_at, updated_at)
values ($1, $2, $3, $4, $5, $6, true, now(), now())",
(id, name, description, color, fast_mode, allow_image_generation, allow_subagents, model_access_json, enabled, created_at, updated_at)
values ($1, $2, $3, $4, $5, $6, $7, $8, true, now(), now())",
)
.bind(command.id.as_str())
.bind(&command.name)
@@ -756,6 +782,8 @@ pub(crate) async fn insert_account_group_in_transaction(
.bind(command.color.as_str())
.bind(command.fast_mode.as_str())
.bind(command.allow_image_generation)
.bind(command.allow_subagents)
.bind(sqlx::types::Json(&command.model_access))
.execute(&mut **transaction)
.await
.map_err(|error| map_group_write_error(error, command.id.as_str()))?;
@@ -16,16 +16,17 @@ use gateway_admin::{
MutationContext,
account_groups::AccountGroupRef as AdminAccountGroupRef,
client_keys::{
ClientKeyCursor as AdminClientKeyCursor,
BatchUpdateClientKeys, ClientKeyCursor as AdminClientKeyCursor,
ClientKeyCursorValue as AdminClientKeyCursorValue,
ClientKeyListQuery as AdminClientKeyListQuery, ClientKeyPage as AdminClientKeyPage,
ClientKeyRecord as AdminClientKeyRecord, ClientKeySecret as AdminClientKeySecret,
ClientKeySort as AdminClientKeySort, ClientKeySortField as AdminClientKeySortField,
DeleteClientKey, NewClientKey, ResetClientKeyBudget, SetClientKeyEnabled,
SortDirection as AdminSortDirection, UpdateClientKey as AdminUpdateClientKey,
DeleteClientKey, NewClientKey, ProviderRequestProfileOverrides, ResetClientKeyBudget,
SetClientKeyEnabled, SortDirection as AdminSortDirection,
UpdateClientKey as AdminUpdateClientKey,
},
},
ports::store::{AdminStoreResult, ClientKeyStore},
ports::store::{AdminStoreResult, BatchClientKeyProfileMerger, ClientKeyStore},
};
use gateway_core::{
account::OpaqueProviderData,
@@ -1006,6 +1007,55 @@ impl ClientKeyStore for PgAdminClientKeyStore {
Ok((admin_revision(revision)?, self.required_record(&id).await?))
}
async fn batch_update_client_keys(
&self,
command: BatchUpdateClientKeys,
merge_profiles: BatchClientKeyProfileMerger,
context: &MutationContext,
) -> AdminStoreResult<gateway_admin::model::Revision> {
let mut fields = Vec::new();
if let Some(groups) = &command.group_ids {
fields.push("group_ids".to_owned());
fields.push(
if groups.is_empty() {
"routing_scope:all"
} else {
"routing_scope:groups"
}
.to_owned(),
);
}
fields.extend(
[
(command.enabled.is_some(), "enabled"),
(command.max_concurrency.is_some(), "max_concurrency"),
(command.requests_per_minute.is_some(), "requests_per_minute"),
(command.daily_limit_usd.is_some(), "daily_limit_usd"),
(command.weekly_limit_usd.is_some(), "weekly_limit_usd"),
(!command.peer_sharing.is_empty(), "peer_sharing_json"),
(
!command.request_profile_override_updates.is_empty()
|| command.installation_seed.is_some(),
"provider_request_profiles_json",
),
]
.into_iter()
.filter(|(changed, _)| *changed)
.map(|(_, field)| field.to_owned()),
);
let audit = mutation_audit(
context,
MutationAuditOperation::ClientApiKeyBatchUpdate,
"client_api_keys",
fields,
);
self.control_plane
.batch_update_client_keys(command, merge_profiles, audit)
.await
.map_err(|error| admin_store_error(ENTITY, error))
.and_then(admin_revision)
}
async fn set_client_key_enabled(
&self,
command: SetClientKeyEnabled,
@@ -1208,7 +1258,12 @@ pub(crate) async fn insert_client_api_key_in_transaction(
postgres_unavailable("insert client API key in transaction", error)
}
})?;
replace_client_api_key_groups_in_transaction(transaction, &key.id, &key.group_ids).await?;
replace_client_api_key_groups_in_transaction(
transaction,
std::slice::from_ref(&key.id),
&key.group_ids,
)
.await?;
Ok(())
}
@@ -1282,7 +1337,12 @@ pub(crate) async fn update_client_api_key_in_transaction(
.await
.map_err(|source| postgres_unavailable("update client API key in transaction", source))?;
require_changed(result.rows_affected(), &key.id)?;
replace_client_api_key_groups_in_transaction(transaction, &key.id, &key.group_ids).await
replace_client_api_key_groups_in_transaction(
transaction,
std::slice::from_ref(&key.id),
&key.group_ids,
)
.await
}
async fn ensure_client_key_name_available(
@@ -1355,9 +1415,118 @@ fn require_changed(rows_affected: u64, id: &str) -> StoreResult<()> {
}
}
pub(super) async fn batch_update_client_keys_in_transaction(
transaction: &mut Transaction<'_, Postgres>,
command: &BatchUpdateClientKeys,
merge_profiles: &BatchClientKeyProfileMerger,
) -> StoreResult<()> {
let ids: Vec<_> = command
.ids
.iter()
.map(|id| id.as_str().to_owned())
.collect();
// 单个画像可包含多个 64 KiB 的 Provider 配置,分段合并以限制同一事务的内存占用
let update_profiles =
!command.request_profile_override_updates.is_empty() || command.installation_seed.is_some();
let chunk_size = if update_profiles {
16
} else {
ids.len().max(1)
};
for chunk in ids.chunks(chunk_size) {
update_client_key_chunk(transaction, chunk, command, update_profiles, merge_profiles)
.await?;
}
if let Some(groups) = &command.group_ids {
let groups = groups
.iter()
.map(|id| id.as_str().to_owned())
.collect::<Vec<_>>();
replace_client_api_key_groups_in_transaction(transaction, &ids, &groups).await?;
}
Ok(())
}
async fn update_client_key_chunk(
transaction: &mut Transaction<'_, Postgres>,
ids: &[String],
command: &BatchUpdateClientKeys,
update_profiles: bool,
merge_profiles: &BatchClientKeyProfileMerger,
) -> StoreResult<()> {
use sqlx::types::Json;
let mut profiles_by_id = BTreeMap::new();
let mut sharing_by_id = BTreeMap::new();
let update_sharing = !command.peer_sharing.is_empty();
let scope = command.group_ids.as_ref().map(|groups| !groups.is_empty());
if update_sharing || scope == Some(false) || update_profiles {
// 控制面版本锁串行化配置写入;用每把密钥的最终授权验证跨字段约束
let rows = sqlx::query_as::<_, (String, Json<ClientPeerSharing>, bool, Option<Json<ProviderRequestProfileOverrides>>)>(
"select k.id, k.peer_sharing_json,
coalesce($2, exists(select 1 from client_api_key_groups g where g.client_api_key_id = k.id)),
case when $3 then k.provider_request_profiles_json end
from client_api_keys k where k.id = any($1) order by k.id for update of k",
)
.bind(ids)
.bind(scope)
.bind(update_profiles)
.fetch_all(&mut **transaction)
.await
.map_err(|source| postgres_unavailable("read selected client key policies", source))?;
for (id, Json(sharing), has_groups, profiles) in rows {
if update_sharing || scope == Some(false) {
let sharing = command.peer_sharing.apply(sharing);
sharing
.validate(has_groups)
.map_err(|_| invalid("invalid peer sharing scope"))?;
if update_sharing {
sharing_by_id.insert(id.clone(), sharing);
}
}
if let Some(Json(mut profiles)) = profiles {
merge_profiles(&mut profiles).map_err(|source| {
invalid("invalid client key request profile").with_source(source)
})?;
validate_request_profiles(profiles.values())?;
profiles_by_id.insert(id, profiles);
}
}
}
let updated = sqlx::query(
"update client_api_keys set enabled = coalesce($2, enabled),
max_concurrency = coalesce($3, max_concurrency), requests_per_minute = coalesce($4, requests_per_minute),
daily_limit_usd = coalesce($5::text::numeric, daily_limit_usd),
weekly_limit_usd = coalesce($6::text::numeric, weekly_limit_usd),
peer_sharing_json = coalesce($7::jsonb -> id, peer_sharing_json),
provider_request_profiles_json = coalesce($8::jsonb -> id, provider_request_profiles_json),
updated_at = now()
where id = any($1)",
)
.bind(ids)
.bind(command.enabled)
.bind(command.max_concurrency.map(to_i64).transpose()?)
.bind(command.requests_per_minute.map(to_i64).transpose()?)
.bind(command.daily_limit_usd.map(Decimal::canonical))
.bind(command.weekly_limit_usd.map(Decimal::canonical))
.bind(Json(sharing_by_id))
.bind(Json(profiles_by_id))
.execute(&mut **transaction)
.await
.map_err(|source| postgres_unavailable("batch update client API keys", source))?;
if usize::try_from(updated.rows_affected()).ok() != Some(ids.len()) {
return Err(StoreError::NotFound {
source: None,
entity: ENTITY,
id: "selected client API keys".to_owned(),
});
}
Ok(())
}
async fn replace_client_api_key_groups_in_transaction(
transaction: &mut Transaction<'_, Postgres>,
key_id: &str,
key_ids: &[String],
group_ids: &[String],
) -> StoreResult<()> {
validate_group_ids(group_ids)?;
@@ -1377,8 +1546,8 @@ async fn replace_client_api_key_groups_in_transaction(
});
}
}
sqlx::query("delete from client_api_key_groups where client_api_key_id = $1")
.bind(key_id)
sqlx::query("delete from client_api_key_groups where client_api_key_id = any($1::text[])")
.bind(key_ids)
.execute(&mut **transaction)
.await
.map_err(|source| postgres_unavailable("delete client API key groups", source))?;
@@ -1386,9 +1555,9 @@ async fn replace_client_api_key_groups_in_transaction(
sqlx::query(
"insert into client_api_key_groups
(client_api_key_id, account_group_id, created_at)
select $1, group_id, now() from unnest($2::text[]) group_id",
select key_id, group_id, now() from unnest($1::text[]) key_id cross join unnest($2::text[]) group_id",
)
.bind(key_id)
.bind(key_ids)
.bind(group_ids)
.execute(&mut **transaction)
.await
@@ -1,6 +1,9 @@
//! 控制面设置与 Key 修改的 revision 锁、条件写入和同事务审计
use async_trait::async_trait;
use gateway_admin::{
model::client_keys::BatchUpdateClientKeys, ports::store::BatchClientKeyProfileMerger,
};
use sqlx::PgPool;
use crate::{Revision, StoreError, StoreResult, postgres_unavailable};
@@ -195,6 +198,7 @@ impl ControlPlaneRepository for PgControlPlaneRepository {
}
enum ControlPlaneMutation {
BatchUpdateClientKeys(BatchUpdateClientKeys, BatchClientKeyProfileMerger),
CreateClientApiKey(NewClientApiKey),
UpdateClientApiKey(UpdateClientApiKeyDetails),
SetClientApiKeyEnabled { id: String, enabled: bool },
@@ -203,6 +207,19 @@ enum ControlPlaneMutation {
}
impl PgControlPlaneRepository {
pub(super) async fn batch_update_client_keys(
&self,
command: BatchUpdateClientKeys,
merge_profiles: BatchClientKeyProfileMerger,
audit: AdminAuditEvent,
) -> StoreResult<Revision> {
self.apply_targeted_mutation(
ControlPlaneMutation::BatchUpdateClientKeys(command, merge_profiles),
audit,
)
.await
}
async fn apply_targeted_mutation(
&self,
mutation: ControlPlaneMutation,
@@ -214,6 +231,14 @@ impl PgControlPlaneRepository {
let result: StoreResult<_> = async {
let revision = bump_config_revision_in_transaction(&mut transaction).await?;
match mutation {
ControlPlaneMutation::BatchUpdateClientKeys(command, merge_profiles) => {
super::client_keys::batch_update_client_keys_in_transaction(
&mut transaction,
&command,
&merge_profiles,
)
.await?;
}
ControlPlaneMutation::CreateClientApiKey(key) => {
audit.changed_fields.push(if key.group_ids.is_empty() {
"routing_scope:all".to_owned()
@@ -3,7 +3,7 @@
use std::collections::BTreeMap;
use async_trait::async_trait;
use gateway_core::account::{FastMode, ProviderAccountId};
use gateway_core::account::{AccountModelAccess, FastMode, ProviderAccountId};
use gateway_core::routing::{
AccountGroupId, ConfigRevision,
snapshot::{
@@ -32,6 +32,8 @@ pub struct RuntimeSnapshotData {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotAccountGroupData {
pub allow_image_generation: bool,
pub allow_subagents: bool,
pub model_access: AccountModelAccess,
pub fast_mode: FastMode,
pub id: AccountGroupId,
pub name: String,
@@ -158,6 +160,8 @@ impl SnapshotStorePort for PgRuntimeSnapshotRepository {
SnapshotAccountGroupFacts::new(group.id, group.name, group.enabled)
.with_fast_mode(group.fast_mode)
.with_image_generation(group.allow_image_generation)
.with_subagents(group.allow_subagents)
.with_model_access(group.model_access)
})
.collect();
let provider_accounts = data
@@ -351,24 +355,37 @@ async fn load_client_keys(
async fn load_account_groups(
transaction: &mut Transaction<'_, Postgres>,
) -> StoreResult<Vec<SnapshotAccountGroupData>> {
let rows = sqlx::query_as::<_, (String, String, bool, String, bool)>(
"select id, name, enabled, fast_mode, allow_image_generation from account_groups order by id",
let rows = sqlx::query_as::<_, (String, String, bool, String, bool, bool, sqlx::types::Json<AccountModelAccess>)>(
"select id, name, enabled, fast_mode, allow_image_generation, allow_subagents, model_access_json from account_groups order by id",
)
.fetch_all(&mut **transaction)
.await
.map_err(|source| postgres_unavailable("load snapshot account groups", source))?;
rows.into_iter()
.map(|(id, name, enabled, fast_mode, allow_image_generation)| {
Ok(SnapshotAccountGroupData {
allow_image_generation,
fast_mode: FastMode::parse(&fast_mode)
.ok_or_else(|| invalid("invalid fast_mode"))?,
id: AccountGroupId::new(id)
.map_err(|source| invalid("invalid account group id").with_source(source))?,
.map(
|(
id,
name,
enabled,
})
})
fast_mode,
allow_image_generation,
allow_subagents,
model_access,
)| {
Ok(SnapshotAccountGroupData {
allow_image_generation,
allow_subagents,
model_access: model_access.0,
fast_mode: FastMode::parse(&fast_mode)
.ok_or_else(|| invalid("invalid fast_mode"))?,
id: AccountGroupId::new(id).map_err(|source| {
invalid("invalid account group id").with_source(source)
})?,
name,
enabled,
})
},
)
.collect()
}
@@ -64,6 +64,8 @@ async fn groups_aggregate_cross_provider_members_and_key_bindings_without_multip
.create_account_group(
NewAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
id: mixed_group.clone(),
name: "Mixed Production".to_owned(),
@@ -78,6 +80,8 @@ async fn groups_aggregate_cross_provider_members_and_key_bindings_without_multip
.create_account_group(
NewAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
id: empty_group.clone(),
name: "Empty Pool".to_owned(),
@@ -381,6 +385,8 @@ async fn group_costs_should_include_statusless_websocket_but_reject_statusless_h
.create_account_group(
NewAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
id: group_id(EMPTY_GROUP),
name: "Statusless Costs".to_owned(),
@@ -581,6 +587,8 @@ async fn fast_mode_group_updates_preserve_omitted_values_and_publish_snapshot_fa
.create_account_group(
NewAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
id: id.clone(),
name: "Fast policy".to_owned(),
description: None,
@@ -593,6 +601,8 @@ async fn fast_mode_group_updates_preserve_omitted_values_and_publish_snapshot_fa
.unwrap();
for (value, expected) in [
(None, FastMode::Disabled),
(Some(FastMode::Ultrafast), FastMode::Ultrafast),
(None, FastMode::Ultrafast),
(Some(FastMode::Enabled), FastMode::Enabled),
(None, FastMode::Enabled),
(Some(FastMode::Default), FastMode::Default),
@@ -602,6 +612,8 @@ async fn fast_mode_group_updates_preserve_omitted_values_and_publish_snapshot_fa
.update_account_group(
UpdateAccountGroup {
allow_image_generation: None,
allow_subagents: None,
model_access: None,
id: id.clone(),
name: "Renamed policy".to_owned(),
description: None,
@@ -655,6 +667,8 @@ async fn group_costs_follow_current_members_and_pending_source_replacements() {
.create_account_group(
NewAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
id: group_id(id),
name: id.to_owned(),
@@ -751,7 +765,7 @@ async fn load_retained_group_costs(groups: &PgAccountGroupRepository) -> BTreeMa
.collect()
}
#[tokio::test]
async fn image_generation_group_updates_preserve_omitted_values_and_publish_snapshot_facts() {
async fn group_policies_preserve_omitted_values_and_publish_snapshot_facts() {
use gateway_admin::model::account_groups::UpdateAccountGroup;
use gateway_store::postgres::{PgRuntimeSnapshotRepository, RuntimeSnapshotRepository};
let Some(database) = TestDatabase::create("image_generation_group").await else {
@@ -763,10 +777,17 @@ async fn image_generation_group_updates_preserve_omitted_values_and_publish_snap
.unwrap(),
);
let id = group_id(MIXED_GROUP);
let denylist = gateway_core::account::AccountModelAccess::new(
gateway_core::account::AccountModelAccessMode::Denylist,
vec!["model-a".to_owned()],
)
.unwrap();
repository
.create_account_group(
NewAccountGroup {
allow_image_generation: false,
allow_subagents: false,
model_access: denylist.clone(),
id: id.clone(),
name: "Fast policy".to_owned(),
description: None,
@@ -787,6 +808,14 @@ async fn image_generation_group_updates_preserve_omitted_values_and_publish_snap
.update_account_group(
UpdateAccountGroup {
allow_image_generation: value,
allow_subagents: value,
model_access: value.map(|allowed| {
if allowed {
Default::default()
} else {
denylist.clone()
}
}),
id: id.clone(),
name: "Renamed policy".to_owned(),
description: None,
@@ -797,7 +826,15 @@ async fn image_generation_group_updates_preserve_omitted_values_and_publish_snap
)
.await
.unwrap();
assert_eq!(mutation.record.unwrap().allow_image_generation, expected);
let record = mutation.record.unwrap();
assert_eq!(record.allow_image_generation, expected);
assert_eq!(record.allow_subagents, expected);
let expected_models = if expected {
Default::default()
} else {
denylist.clone()
};
assert_eq!(record.model_access, expected_models);
let snapshot = PgRuntimeSnapshotRepository::new(database.pool.clone())
.load_runtime_snapshot()
.await
@@ -806,34 +843,35 @@ async fn image_generation_group_updates_preserve_omitted_values_and_publish_snap
snapshot.config_revision.get(),
mutation.config_revision.get()
);
assert_eq!(
snapshot
.account_groups
.iter()
.find(|group| group.id == id)
.unwrap()
.allow_image_generation,
expected
);
let group = snapshot
.account_groups
.iter()
.find(|group| group.id == id)
.unwrap();
assert_eq!(group.allow_image_generation, expected);
assert_eq!(group.allow_subagents, expected);
assert_eq!(group.model_access, expected_models);
}
database.close().await;
}
#[tokio::test]
async fn image_generation_defaults_to_allowed_for_new_groups() {
async fn group_policy_defaults_apply_to_groups_created_without_explicit_policies() {
let Some(database) = TestDatabase::create("group_image_default").await else {
return;
};
sqlx::query("insert into account_groups (id, name, color, created_at, updated_at) values ($1, $1, '#2563EBFF', now(), now())")
.bind(EMPTY_GROUP).execute(&database.pool).await.unwrap();
let allowed = sqlx::query_scalar::<_, bool>(
"select allow_image_generation from account_groups where id = $1",
let (images, subagents, models) = sqlx::query_as::<_, (bool, bool, sqlx::types::Json<gateway_core::account::AccountModelAccess>)>(
"select allow_image_generation, allow_subagents, model_access_json from account_groups where id = $1",
)
.bind(EMPTY_GROUP)
.fetch_one(&database.pool)
.await
.unwrap();
assert!(allowed);
assert!(images);
assert!(subagents);
assert_eq!(models.0, gateway_core::account::AccountModelAccess::all());
database.close().await;
}
@@ -876,6 +914,8 @@ async fn committed_group_mutations_succeed_when_the_usage_query_budget_is_exhaus
color: AccountGroupColor::parse("#2563EBFF").unwrap(),
fast_mode: FastMode::Default,
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
},
&context("projection-create"),
)
@@ -891,6 +931,8 @@ async fn committed_group_mutations_succeed_when_the_usage_query_budget_is_exhaus
color: AccountGroupColor::parse("#2563EBFF").unwrap(),
fast_mode: None,
allow_image_generation: None,
allow_subagents: None,
model_access: None,
},
&context("projection-update"),
)
@@ -66,6 +66,8 @@ async fn peer_sharing_persists_across_reads_and_cannot_lose_its_group_scope() {
color: AccountGroupColor::parse("#2563EBFF").unwrap(),
fast_mode: FastMode::Default,
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
},
&context,
)
@@ -136,6 +138,21 @@ async fn peer_sharing_persists_across_reads_and_cannot_lose_its_group_scope() {
.len(),
1
);
let error = store
.batch_update_client_keys(
gateway_admin::model::client_keys::BatchUpdateClientKeys {
ids: vec![id.clone()],
group_ids: Some(vec![]),
enabled: Some(false),
..Default::default()
},
Box::new(|_| Ok(())),
&context,
)
.await
.unwrap_err();
assert_eq!(error.kind(), AdminStoreErrorKind::Invalid);
assert!(store.get_client_key(&id).await.unwrap().unwrap().enabled);
update.group_ids = vec![group];
let (_, updated) = store
.update_client_key(update.clone(), &context)
@@ -150,6 +167,209 @@ async fn peer_sharing_persists_across_reads_and_cannot_lose_its_group_scope() {
database.close().await;
}
#[tokio::test]
async fn batch_key_changes_preserve_unselected_fields_and_roll_back_the_whole_selection() {
use gateway_admin::model::{
MutationActor, MutationContext,
client_keys::{BatchUpdateClientKeys, ClientPeerSharingPatch},
};
use gateway_admin::ports::store::AdminStoreErrorKind;
use gateway_core::routing::AccountGroupId;
let Some(database) = TestDatabase::create("batch_keys").await else {
return;
};
let store = PgAdminClientKeyStore::new(database.pool.clone());
let ids = ["key_batch_a", "key_batch_b"].map(|id| ClientApiKeyId::new(id).unwrap());
sqlx::query(
"insert into client_api_keys (id, name, key, max_concurrency, peer_sharing_json, created_at, updated_at)
select id, id, id, 7, jsonb_build_object('sharePool', id = $2), now(), now() from unnest($1::text[]) id",
)
.bind(ids.iter().map(|id| id.as_str()).collect::<Vec<_>>())
.bind(ids[0].as_str())
.execute(&database.pool)
.await
.unwrap();
let group = AccountGroupId::new(format!("grp_{}", "a".repeat(32))).unwrap();
sqlx::query("insert into account_groups (id, name, color, created_at, updated_at) values ($1,'Batch','#000000FF',now(),now())")
.bind(group.as_str()).execute(&database.pool).await.unwrap();
let context = MutationContext {
actor: MutationActor::System,
request_id: "batch-keys".into(),
};
let mut command = BatchUpdateClientKeys {
ids: ids.to_vec(),
enabled: Some(false),
group_ids: Some(vec![group.clone()]),
peer_sharing: ClientPeerSharingPatch {
enabled: Some(true),
share_quota: Some(true),
..Default::default()
},
..Default::default()
};
let first_revision = store
.batch_update_client_keys(command.clone(), Box::new(|_| Ok(())), &context)
.await
.unwrap();
for id in &ids {
let record = store.get_client_key(id).await.unwrap().unwrap();
assert!(!record.enabled);
assert_eq!(record.groups[0].id, group);
assert_eq!(record.limits.max_concurrency, 7);
assert!(record.peer_sharing.enabled && record.peer_sharing.share_quota);
assert_eq!(record.peer_sharing.share_pool, *id == ids[0]);
}
command.enabled = Some(true);
command.group_ids = None;
command
.ids
.push(ClientApiKeyId::new("key_missing").unwrap());
assert_eq!(
store
.batch_update_client_keys(command.clone(), Box::new(|_| Ok(())), &context)
.await
.unwrap_err()
.kind(),
AdminStoreErrorKind::NotFound
);
command.ids = ids.to_vec();
command.group_ids = Some(vec![
AccountGroupId::new(format!("grp_{}", "b".repeat(32))).unwrap(),
]);
assert_eq!(
store
.batch_update_client_keys(command.clone(), Box::new(|_| Ok(())), &context)
.await
.unwrap_err()
.kind(),
AdminStoreErrorKind::NotFound
);
for id in &ids {
let record = store.get_client_key(id).await.unwrap().unwrap();
assert!(!record.enabled);
assert_eq!(record.groups[0].id, group);
}
command.group_ids = None;
command.peer_sharing.share_plans = Some(true);
assert_eq!(
store
.batch_update_client_keys(command.clone(), Box::new(|_| Ok(())), &context)
.await
.unwrap_err()
.kind(),
AdminStoreErrorKind::Invalid,
);
assert!(
!store
.get_client_key(&ids[0])
.await
.unwrap()
.unwrap()
.peer_sharing
.share_plans
);
command.peer_sharing.share_plans = None;
let second_revision = store
.batch_update_client_keys(command.clone(), Box::new(|_| Ok(())), &context)
.await
.unwrap();
assert_eq!(second_revision.get(), first_revision.get() + 1);
assert_eq!(
store
.get_client_key(&ids[0])
.await
.unwrap()
.unwrap()
.groups
.len(),
1
);
command.group_ids = Some(vec![]);
command.enabled = None;
command.peer_sharing.enabled = Some(false);
store
.batch_update_client_keys(command, Box::new(|_| Ok(())), &context)
.await
.unwrap();
for id in &ids {
let record = store.get_client_key(id).await.unwrap().unwrap();
assert!(record.enabled && record.groups.is_empty());
assert!(!record.peer_sharing.enabled);
assert!(record.peer_sharing.share_quota);
}
let audits: i64 = sqlx::query_scalar("select count(*) from admin_audit_events where action='batch_update' and entity_kind='client_api_key'")
.fetch_one(&database.pool).await.unwrap();
assert_eq!(audits, 3);
database.close().await;
}
#[tokio::test]
async fn batch_limits_and_profiles_keep_each_keys_budget_ledger_and_unselected_providers() {
use super::client_budgets::{charge, context, key_id, seed, status};
use gateway_admin::model::client_keys::BatchUpdateClientKeys;
use gateway_core::{
engine::budget::ClientBudgetPort as _, metering::Decimal, routing::ProviderKind,
};
use gateway_store::postgres::PgClientBudgetStore;
let Some(database) = TestDatabase::create("batch_key_limits_profiles").await else {
return;
};
let keys = ["key_bulk_a", "key_bulk_b"];
let budgets = PgClientBudgetStore::new(database.pool.clone());
let mut previous = Vec::new();
for (key, amount) in keys.into_iter().zip(["1", "2.5"]) {
seed(&database, key, "5", "20").await;
sqlx::query(
"update client_api_keys set requests_per_minute = 11,
provider_request_profiles_json = jsonb_build_object(
'other', jsonb_build_object('version', $1::text), 'removed', '{}'::jsonb)
where id = $1",
)
.bind(key)
.execute(&database.pool)
.await
.unwrap();
budgets.settle(charge(key, key, amount)).await.unwrap();
previous.push(status(&database, key).await);
}
let store = PgAdminClientKeyStore::new(database.pool.clone());
let removed = ProviderKind::new("removed").unwrap();
let command = BatchUpdateClientKeys {
ids: keys.map(key_id).to_vec(),
daily_limit_usd: Some(Decimal::ZERO),
max_concurrency: Some(9),
requests_per_minute: Some(0),
request_profile_override_updates: BTreeMap::from([(removed.clone(), None)]),
..Default::default()
};
let merge_profiles = Box::new(
move |profiles: &mut gateway_admin::model::client_keys::ProviderRequestProfileOverrides| {
assert!(profiles.remove(&removed).is_some());
Ok(())
},
);
store
.batch_update_client_keys(command, merge_profiles, &context())
.await
.unwrap();
for (key, mut expected) in keys.into_iter().zip(previous) {
let record = store.get_client_key(&key_id(key)).await.unwrap().unwrap();
expected.limits.daily_usd = Decimal::ZERO;
assert_eq!(record.budget, expected);
assert_eq!(record.name, key);
assert!(record.label.is_none());
assert_eq!(record.limits.max_concurrency, 9);
assert_eq!(record.limits.requests_per_minute, 0);
assert_eq!(record.request_profile_overrides.len(), 1);
let other = &record.request_profile_overrides[&ProviderKind::new("other").unwrap()];
assert_eq!(other.expose_to_provider()["version"], key);
}
database.close().await;
}
#[tokio::test]
async fn custom_keys_persist_exactly_and_keep_short_keys_masked() {
use gateway_admin::model::{MutationActor, MutationContext, client_keys::NewClientKey};
@@ -260,6 +260,20 @@ impl ProviderAdmin for OpenAiAdminProvider {
.map_err(map_client_profile_error)
}
fn merge_batch_key_profile(
&self,
current: Option<&gateway_core::account::OpaqueProviderData>,
update: Option<&Option<gateway_core::account::OpaqueProviderData>>,
installation_seed: Option<uuid::Uuid>,
) -> Result<Option<gateway_core::account::OpaqueProviderData>, ProviderAdminError> {
crate::transport::profile::identity::merge_batch_key_profile(
current,
update,
installation_seed,
)
.map_err(map_client_profile_error)
}
fn provider_kind(&self) -> &ProviderKind {
&self.provider_kind
}
@@ -222,6 +222,19 @@ impl CodexCredentialCatalogSnapshot {
.map(|e| e.content.ids.as_slice())
}
fn account_model(
&self,
account: &ProviderAccount,
model: &UpstreamModelId,
) -> Option<&CodexCatalogModel> {
self.entries
.get(&CodexCatalogScope::for_account(account))?
.content
.models
.iter()
.find(|entry| entry.request_model() == model)
}
#[must_use]
pub fn model_catalog_accounts(&self) -> BTreeMap<&str, BTreeSet<ProviderAccountId>> {
let mut accounts = BTreeMap::<&str, BTreeSet<ProviderAccountId>>::new();
@@ -437,6 +450,23 @@ impl CodexCredentialCatalogService {
.collect())
}
pub(crate) fn account_advertises_tier(
&self,
account: &ProviderAccount,
model: &UpstreamModelId,
tier: &str,
) -> bool {
self.cached().ok().flatten().is_some_and(|snapshot| {
snapshot.account_model(account, model).is_some_and(|entry| {
entry
.metadata()
.service_tiers()
.iter()
.any(|item| item.id() == tier)
})
})
}
pub(crate) fn messages_model_capabilities(
&self,
account: &ProviderAccount,
@@ -444,12 +474,7 @@ impl CodexCredentialCatalogService {
) -> Option<gateway_protocol::anthropic::MessagesModelCapabilities> {
let snapshot = self.cached().ok()??;
snapshot
.entries
.get(&CodexCatalogScope::for_account(account))?
.content
.models
.iter()
.find(|entry| entry.request_model() == model)?
.account_model(account, model)?
.messages_capabilities()
.cloned()
}
@@ -1,7 +1,7 @@
//! OpenAI 请求的账号认证、套餐与模型权限资格
use gateway_core::account::scope::FrozenAccountScope;
use gateway_core::account::{AccountModelAccessMode, ProviderAccount, ProviderAccountId};
use gateway_core::account::{ProviderAccount, ProviderAccountId};
use super::types::CODEX_AUTHENTICATION_KIND_OAUTH;
@@ -54,12 +54,7 @@ impl<'a> CodexSelectionModel<'a> {
| Self::Image(Some(model))
| Self::Search(Some(model)) => scope.allows_model(account, model),
// 缺失、重复或不可解析的模型不能绕过黑白名单;不猜上游默认值
Self::Image(None) | Self::Search(None) => {
scope.allows(account)
&& scope.directory().account(account).is_some_and(|account| {
account.model_access().mode() == AccountModelAccessMode::All
})
}
Self::Image(None) | Self::Search(None) => scope.allows_unidentified_model(account),
}
}
}
@@ -154,6 +154,22 @@ impl CodexProvider {
} else {
CodexSelectionModel::Search(requested_model.as_ref().map(|model| model.as_str()))
};
if !context.is_diagnostic_required_account()
&& context
.account_scope()
.is_some_and(|scope| scope.groups_deny_model(model.model()))
{
return Err(provider_error(
ProviderErrorKind::RequestPolicyDenied,
UpstreamSendState::NotSent,
)
.with_retry_prohibited()
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
gateway_core::validation::GROUP_MODEL_DENIED_MESSAGE,
Some(gateway_core::validation::GROUP_MODEL_DENIED_CODE.to_owned()),
None,
)));
}
let selection_started_at = Instant::now();
let lease = self
.selector
@@ -82,7 +82,8 @@ use crate::transport::profile::{
};
use crate::transport::protocol::responses::{
CodexResponsesRequest, PREVIOUS_RESPONSE_NOT_FOUND_CODE, PREVIOUS_RESPONSE_NOT_FOUND_MESSAGE,
PreviousResponseScope, ResponseEventSignals, TransportRequirement, transport_requirement,
PreviousResponseScope, ResponseEventSignals, TransportRequirement, fast_policy_tier,
transport_requirement,
};
use crate::transport::request::{
CodexRequestEncodeError, RequestAccountScope, align_structured_location_fields,
@@ -617,40 +618,6 @@ impl Provider for CodexProvider {
UpstreamSendState::NotSent,
));
};
// 请求设置先形成原生正文基线;attempt 的显式改写进入终端后不再次被覆盖
let mut operation = Operation::Generate(generate.clone());
if context.fast_mode() != gateway_core::account::FastMode::Default
&& let Operation::Generate(generate) = &operation
&& generate.protocol_payload().protocol() == OPENAI_PROTOCOL
{
let mut request =
CodexResponsesRequest::from_body(generate.protocol_payload().body().clone());
let supports_priority = candidate.model_presentation().is_some_and(|model| {
model
.service_tiers()
.iter()
.any(|tier| tier.id() == "priority")
});
if request.apply_fast_policy(context.fast_mode(), supports_priority) {
let body = serde_json::to_vec(request.body()).map_err(|_| {
provider_error(
ProviderErrorKind::InvalidRequest,
UpstreamSendState::NotSent,
)
})?;
operation = operation
.replace_middleware_wire(OPENAI_PROTOCOL, body.into())
.map_err(|_| {
provider_error(
ProviderErrorKind::InvalidRequest,
UpstreamSendState::NotSent,
)
})?;
}
}
let Operation::Generate(generate) = &operation else {
unreachable!("generate settings keep the operation kind")
};
let adapter = context.upstream_adapter(candidate.provider(), upstream_model)?;
let adapted = matches!(adapter, UpstreamAdapterSelection::Adapter(_));
if !adapted
@@ -786,13 +753,39 @@ impl Provider for CodexProvider {
let provider_kind = ProviderKind::new(PROVIDER_NAME)
.map_err(|_| provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent))?;
let account_id = lease.account_id().clone();
let frozen_requirements = Operation::Generate(generate.clone()).capability_requirements();
// 账号确定后再判断强制档位,避免借用其他账号的同名模型;attempt 可以继续改写正文
let payload = generate.protocol_payload();
let mut operation = Operation::Generate(generate.clone());
if payload.protocol() == OPENAI_PROTOCOL
&& let Some(tier) = fast_policy_tier(
context.fast_mode(),
payload.body().get("service_tier").and_then(Value::as_str),
|tier| {
self.catalog
.account_advertises_tier(lease.account(), upstream_model, tier)
},
)
{
let invalid = || {
provider_error(
ProviderErrorKind::InvalidRequest,
UpstreamSendState::NotSent,
)
};
let mut body = payload.body().clone();
body.insert("service_tier".into(), Value::String(tier.into()));
let wire = serde_json::to_vec(&body).map_err(|_| invalid())?;
operation = operation
.replace_middleware_wire(OPENAI_PROTOCOL, wire.into())
.map_err(|_| invalid())?;
}
let frozen_requirements = operation.capability_requirements();
let provider = Arc::clone(&self);
let terminal_context = context.clone();
let terminal_model = upstream_model.clone();
context
.execute_middleware(
Operation::Generate(generate.clone()),
operation,
provider_kind,
Some(upstream_model.as_str().to_owned()),
account_id,
@@ -98,6 +98,50 @@ pub(crate) fn inherited_identity_fields(
Ok(inherited)
}
/// 切换画像仅修改客户端选择,未指定的种子仍取自这一把 Key
pub fn merge_batch_key_profile(
current: Option<&OpaqueProviderData>,
update: Option<&Option<OpaqueProviderData>>,
installation_seed: Option<uuid::Uuid>,
) -> Result<Option<OpaqueProviderData>, ClientProfileError> {
if let Some(Some(profile)) = update {
let fields =
inherited_identity_fields(profile)?.unwrap_or_else(|| profile.expose_to_provider());
if fields.contains_key("installationSeed") {
return Err(ClientProfileError::Invalid);
}
}
let selection = update.map_or(current, Option::as_ref);
let seed = match installation_seed {
Some(seed) => Some(seed.to_string()),
None => current
.and_then(|profile| {
gateway_core::settings::request_profiles::inherited_fields(profile)
.unwrap_or_else(|| profile.expose_to_provider())
.get("installationSeed")
})
.and_then(Value::as_str)
.filter(|seed| !seed.is_empty())
.map(str::to_owned),
};
let Some(seed) = seed else {
return Ok(selection.cloned());
};
if let Some(selection) = selection
&& inherited_identity_fields(selection)?.is_none()
{
let mut fields = selection.expose_to_provider().clone();
fields.insert("installationSeed".into(), Value::String(seed));
return Ok(Some(OpaqueProviderData::new(fields)));
}
let mut document = serde_json::Map::new();
document.insert(
"inherit".into(),
serde_json::json!({ "installationSeed": seed }),
);
Ok(Some(OpaqueProviderData::new(document)))
}
impl RequestProfileSelection {
pub fn preset(&self) -> Option<&ClientProfileSelection> {
match &self.selection {
@@ -20,6 +20,29 @@ pub(crate) const PREVIOUS_RESPONSE_NOT_FOUND_MESSAGE: &str =
"Previous response was not found. Retrying the full request.";
/// Codex 自动审批(Guardian)请求声明的子代理类型
const GUARDIAN_SUBAGENT_KIND: &str = "guardian";
/// 分组显式覆盖后的档位;强制加速仅使用所选账号对该模型的目录声明
pub(crate) fn fast_policy_tier(
mode: FastMode,
current: Option<&str>,
advertises: impl Fn(&str) -> bool,
) -> Option<&'static str> {
let target = match mode {
FastMode::Enabled if advertises("priority") => "priority",
FastMode::Ultrafast if advertises("ultrafast") => "ultrafast",
FastMode::Disabled
if current.is_some_and(|tier| {
["priority", "fast", "ultrafast"]
.iter()
.any(|name| tier.trim().eq_ignore_ascii_case(name))
}) =>
{
"default"
}
_ => return None,
};
(current != Some(target)).then_some(target)
}
/// Codex Responses 上游请求体
///
/// 发往上游的 Responses 请求
@@ -705,31 +728,6 @@ impl CodexResponsesRequest {
self.body.get("service_tier").and_then(Value::as_str)
}
/// 只改写顶层档位;开启需要目录证据,其他显式档位保留客户端选择
pub(crate) fn apply_fast_policy(&mut self, mode: FastMode, supports_priority: bool) -> bool {
let tier = self.service_tier().map(str::trim);
let target = match mode {
FastMode::Disabled
if tier.is_some_and(|tier| {
tier.eq_ignore_ascii_case("priority") || tier.eq_ignore_ascii_case("fast")
}) =>
{
"default"
}
FastMode::Enabled
if supports_priority
&& (matches!(self.body.get("service_tier"), None | Some(Value::Null))
|| tier.is_some_and(|tier| tier.eq_ignore_ascii_case("default"))) =>
{
"priority"
}
_ => return false,
};
self.body
.insert("service_tier".to_owned(), Value::String(target.to_owned()));
true
}
/// 前一个 response ID
pub fn previous_response_id(&self) -> Option<&str> {
self.body
@@ -8151,13 +8151,45 @@ async fn completed_response_persists_session_affinity_before_stream_consumer_sto
assert_eq!(upstream_service_tier.as_deref(), Some("default"));
}
async fn seed_service_tiers(store: &MemoryAccountStore, id: &str, model: &str, tiers: &[&str]) {
use gateway_core::account::AccountCatalogObservation;
let account = store.account(id).unwrap();
let tiers: Vec<_> = tiers
.iter()
.map(|id| json!({"id":id,"name":id,"description":""}))
.collect();
let mut document = vec![0];
serde_json::to_writer(
&mut document,
&json!({"models":[{
"slug":model, "display_name":model, "service_tiers":tiers,
}]}),
)
.unwrap();
assert!(
store
.save_account_catalog(
&AccountCatalogObservation {
account_id: account.id().clone(),
revision: account.revision(),
plan: account.plan_type().map(str::to_owned),
etag: None,
observed_at: SystemTime::now(),
},
&document
)
.await
.unwrap()
);
}
#[tokio::test]
async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_transports() {
for use_websocket in [false, true] {
for (fast_mode, supports_priority, requested, reported, expected_tier, expected_cost) in [
for (fast_mode, advertised_tier, requested, reported, expected_tier, expected_cost) in [
(
FastMode::Default,
false,
None,
Some(json!("priority")),
Some("default"),
Some("priority"),
@@ -8165,7 +8197,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Default,
false,
None,
Some(json!("priority")),
None,
Some("priority"),
@@ -8173,7 +8205,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Default,
false,
None,
Some(json!("default")),
Some("priority"),
Some("default"),
@@ -8181,7 +8213,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Default,
false,
None,
None,
Some("priority"),
None,
@@ -8189,7 +8221,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Disabled,
false,
None,
Some(json!("priority")),
Some("priority"),
Some("default"),
@@ -8197,7 +8229,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Disabled,
false,
None,
Some(json!("fast")),
None,
Some("default"),
@@ -8205,16 +8237,16 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Disabled,
false,
None,
Some(json!("default")),
None,
Some("default"),
Some(3_437_500),
),
(FastMode::Disabled, false, None, None, None, Some(3_437_500)),
(FastMode::Disabled, None, None, None, None, Some(3_437_500)),
(
FastMode::Disabled,
false,
None,
Some(json!("flex")),
None,
Some("flex"),
@@ -8222,15 +8254,15 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Disabled,
false,
None,
Some(json!("ultrafast")),
None,
Some("ultrafast"),
None,
Some("default"),
Some(3_437_500),
),
(
FastMode::Enabled,
true,
Some("priority"),
None,
Some("default"),
Some("priority"),
@@ -8238,7 +8270,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Enabled,
true,
Some("priority"),
Some(Value::Null),
Some("default"),
Some("priority"),
@@ -8246,7 +8278,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Enabled,
true,
Some("priority"),
Some(json!("default")),
Some("default"),
Some("priority"),
@@ -8254,7 +8286,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Enabled,
true,
Some("priority"),
Some(json!("priority")),
None,
Some("priority"),
@@ -8262,40 +8294,102 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
),
(
FastMode::Enabled,
true,
Some("priority"),
Some(json!("flex")),
None,
Some("flex"),
Some(1_720_000),
Some("priority"),
Some(6_875_000),
),
(
FastMode::Enabled,
true,
Some("priority"),
Some(json!("ultrafast")),
None,
Some("priority"),
Some(6_875_000),
),
(
FastMode::Enabled,
Some("priority"),
Some(json!("auto")),
None,
Some("priority"),
Some(6_875_000),
),
(FastMode::Enabled, None, None, None, None, Some(3_437_500)),
(
FastMode::Enabled,
None,
Some(json!("default")),
None,
Some("default"),
Some(3_437_500),
),
(
FastMode::Default,
None,
Some(json!("ultrafast")),
None,
Some("ultrafast"),
None,
),
(
FastMode::Enabled,
true,
Some(json!("auto")),
None,
Some("auto"),
None,
),
(FastMode::Enabled, false, None, None, None, Some(3_437_500)),
(
FastMode::Enabled,
false,
Some(json!("default")),
FastMode::Ultrafast,
Some("ultrafast"),
None,
Some("default"),
Some(3_437_500),
Some("ultrafast"),
None,
),
(
FastMode::Ultrafast,
Some("ultrafast"),
Some(json!("priority")),
None,
Some("ultrafast"),
None,
),
(
FastMode::Ultrafast,
Some("ultrafast"),
Some(json!("flex")),
None,
Some("ultrafast"),
None,
),
(
FastMode::Ultrafast,
Some("priority"),
Some(json!("priority")),
None,
Some("priority"),
Some(6_875_000),
),
(FastMode::Ultrafast, None, None, None, None, Some(3_437_500)),
] {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_provider_contract").await;
// 同名模型的聚合画像来自另一个分组,故意与本次能选的账号声明相反
let other = "acct_other_tier_catalog";
create_account(&store, other).await;
seed_service_tiers(
&store,
"acct_provider_contract",
"gpt-5.4",
advertised_tier.as_slice(),
)
.await;
seed_service_tiers(
&store,
other,
"gpt-5.4",
if advertised_tier.is_some() {
&[]
} else {
&["priority", "ultrafast"]
},
)
.await;
let mut created =
json!({"type":"response.created","response":{"id":"resp_tier","model":"gpt-5.4"}});
let mut completed = json!({
@@ -8378,20 +8472,15 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
)]));
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(payload));
let original = operation.clone();
let mut stream = provider_with_base_url(&store, base_url)
let provider = provider_with_catalog_and_base_url(&store, base_url).await;
let catalog = provider.query_model_capabilities().await.unwrap();
let mut stream = provider
.execute(
planned_request_with_presentation(
"openai",
operation.clone(),
"gpt-5.4",
supports_priority.then(|| {
gateway_core::routing::ModelPresentation::new(None, None)
.with_service_tiers(vec![
gateway_core::routing::ModelServiceTier::new(
"priority", "fast", "Fast",
),
])
}),
catalog[0].presentation().cloned(),
),
context_with_fast_policy(
"req_service_tier",
@@ -12623,6 +12712,7 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
const ACCOUNT: &str = "acct_provider_contract";
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, ACCOUNT).await;
seed_service_tiers(&store, ACCOUNT, "gpt-6.1-sol", &["priority", "ultrafast"]).await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
@@ -12632,7 +12722,7 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
// 提示头只在首次握手发送;后续档位由各自 response.create 正文指定
assert_eq!(
request.headers()["x-codex-routing-hint"],
"model=gpt-5.4;tier=default"
"model=gpt-6.1-sol;tier=default"
);
response.headers_mut().insert(
"sec-websocket-extensions",
@@ -12640,7 +12730,7 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
);
})
.await;
for (index, tier) in ["default", "priority", "default", "default"]
for (index, tier) in ["default", "priority", "ultrafast", "default"]
.into_iter()
.enumerate()
{
@@ -12658,11 +12748,11 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
.map(|previous| json!(format!("resp_fast_turn_{previous}")))
);
websocket.send(Message::Text(json!({
"type":"response.created", "response":{"id":format!("resp_fast_turn_{index}"),"model":"gpt-5.4"}
"type":"response.created", "response":{"id":format!("resp_fast_turn_{index}"),"model":"gpt-6.1-sol"}
}).to_string().into())).await.unwrap();
websocket.send(Message::Text(json!({
"type":"response.completed", "response":{
"id":format!("resp_fast_turn_{index}"), "model":"gpt-5.4", "status":"completed", "output":[],
"id":format!("resp_fast_turn_{index}"), "model":"gpt-6.1-sol", "status":"completed", "output":[],
"service_tier":"priority", "usage":{"input_tokens":100,"output_tokens":10,"input_tokens_details":{"cached_tokens":25,"cache_write_tokens":0},"total_tokens":110}
}
}).to_string().into())).await.unwrap();
@@ -12674,7 +12764,7 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
"all four turns must use the same upstream connection"
);
});
let provider = provider_with_base_url(&store, base_url);
let provider = provider_with_catalog_and_base_url(&store, base_url).await;
let mut session_state = ProviderSessionState::new(
"openai",
Map::from_iter([
@@ -12687,11 +12777,11 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
]),
)
.unwrap();
for (index, fast_mode) in [
FastMode::Default,
FastMode::Enabled,
FastMode::Disabled,
FastMode::Default,
for (index, (fast_mode, tier, cost)) in [
(FastMode::Default, "default", 2_525_000),
(FastMode::Enabled, "priority", 5_050_000),
(FastMode::Ultrafast, "ultrafast", 15_150_000),
(FastMode::Disabled, "default", 2_525_000),
]
.into_iter()
.enumerate()
@@ -12699,8 +12789,7 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
let previous = index
.checked_sub(1)
.map(|index| format!("resp_fast_turn_{index}"));
let mut body =
json!({"model":"gpt-5.4","input":"next turn","service_tier":"default","store":false});
let mut body = json!({"model":"gpt-6.1-sol","input":"next turn","service_tier":"default","store":false});
if let Some(previous) = &previous {
body["previous_response_id"] = json!(previous);
}
@@ -12756,19 +12845,7 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
});
let mut stream = Arc::clone(&provider)
.execute(
planned_request_with_presentation(
"openai",
operation,
"gpt-5.4",
Some(
gateway_core::routing::ModelPresentation::new(None, None)
.with_service_tiers(vec![
gateway_core::routing::ModelServiceTier::new(
"priority", "fast", "Fast",
),
]),
),
),
planned_request_for_model("openai", operation, "gpt-6.1-sol"),
context,
)
.await
@@ -12805,22 +12882,8 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
WebSocketPoolKind::Reuse
})
);
assert_eq!(
observed_tier.as_deref(),
Some(if fast_mode == FastMode::Enabled {
"priority"
} else {
"default"
})
);
assert_eq!(
costs,
vec![if fast_mode == FastMode::Enabled {
6_875_000
} else {
3_437_500
}]
);
assert_eq!(observed_tier.as_deref(), Some(tier));
assert_eq!(costs, vec![cost]);
}
server.await.unwrap();
}
@@ -74,6 +74,81 @@ fn attempt(
)
}
#[tokio::test]
async fn search_respects_group_models_during_selection_and_retry() {
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};
let group = |n| AccountGroupId::new(format!("grp_{n:032x}")).unwrap();
let first = group(1);
let second = group(2);
let provider_kind = ProviderKind::new("openai").unwrap();
let accounts = [(FIRST, first.clone()), (SECOND, second.clone())].map(|(id, group)| {
(
ProviderAccountId::new(id).unwrap(),
RuntimeAccount::new(provider_kind.clone(), [group].into()),
)
});
let directory = RuntimeAccountDirectory::new(accounts.into()).with_group_model_access(
[
(
first.clone(),
policy(AccountModelAccessMode::Denylist, MODEL),
),
(
second.clone(),
policy(AccountModelAccessMode::Allowlist, MODEL),
),
]
.into(),
);
let scope = Arc::new(FrozenAccountScope::new(
Arc::new(directory),
ClientRoutingScope::restricted(
vec![
RoutingGroupSnapshot::new(first.clone(), "First".into()),
RoutingGroupSnapshot::new(second.clone(), "Second".into()),
],
[first, second].into(),
[provider_kind].into(),
)
.unwrap(),
));
let server = MockServer::start().await;
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, FIRST).await;
create_account(&store, SECOND).await;
let provider = provider_with_base_url(&store, server.uri());
let execute = |body: &[u8], excluded: BTreeSet<ProviderAccountId>, index| {
provider.clone().execute(
search(body),
attempt(
AccountAttemptContext::new(excluded, None, None)
.with_account_scope(Arc::clone(&scope)),
AccountAffinity::Strict,
index,
None,
),
)
};
let stream = execute(BODY, BTreeSet::new(), 1).await.unwrap();
assert_eq!(stream.metadata().provider_account_id().as_str(), SECOND);
drop(stream);
let retry = execute(BODY, [ProviderAccountId::new(SECOND).unwrap()].into(), 2)
.await
.err()
.unwrap();
assert_eq!(retry.kind(), ProviderErrorKind::NoEligibleAccount);
let unknown = execute(br#"{"commands":{}}"#, BTreeSet::new(), 1)
.await
.err()
.unwrap();
assert_eq!(unknown.kind(), ProviderErrorKind::RequestPolicyDenied);
assert_eq!(
unknown.client_visible_upstream_error().unwrap().code(),
Some("group_model_denied")
);
assert!(server.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn search_filters_oauth_and_api_key_accounts_before_weight_and_preserves_wire() {
let api = MockServer::start().await;
@@ -11,6 +11,74 @@ fn document(value: Value) -> OpaqueProviderData {
OpaqueProviderData::new(value.as_object().unwrap().clone())
}
#[test]
fn batch_identity_changes_keep_each_keys_seed_and_independent_selection() {
use provider_openai::transport::profile::identity::merge_batch_key_profile;
let preset = json!({"client": "cli", "platform":"linux", "versionMode":"latest"});
let custom = json!({"mode":"custom","userAgent":"codex-tui/0.156.1"});
let replacement = "d3228d4e-7c6f-4d77-a245-89baf5f3959c";
for seed in [
"5d774376-8481-43d1-8b0c-b739ef937b05",
"6da3531b-628d-4e9b-b8a8-5c582c7721bd",
] {
let inherited = json!({"inherit":{"installationSeed":seed}});
let mut previous = custom.clone();
previous["installationSeed"] = json!(seed);
let mut expected = preset.clone();
expected["installationSeed"] = json!(seed);
for current in [&previous, &inherited] {
let current = document(current.clone());
assert_eq!(
merge_batch_key_profile(
Some(&current),
Some(&Some(document(preset.clone()))),
None
)
.unwrap(),
Some(document(expected.clone()))
);
assert_eq!(
merge_batch_key_profile(Some(&current), Some(&None), None).unwrap(),
Some(document(inherited.clone()))
);
}
let next = merge_batch_key_profile(
Some(&document(previous)),
None,
Some(replacement.parse().unwrap()),
)
.unwrap()
.unwrap();
let mut expected = custom.clone();
expected["installationSeed"] = json!(replacement);
assert_eq!(next, document(expected));
}
assert_eq!(
merge_batch_key_profile(None, None, Some(replacement.parse().unwrap())).unwrap(),
Some(document(
json!({"inherit":{"installationSeed":replacement}})
))
);
assert_eq!(
merge_batch_key_profile(Some(&document(preset)), Some(&None), None).unwrap(),
None
);
for embedded in [
json!({"installationSeed":replacement}),
json!({"inherit":{"installationSeed":replacement}}),
] {
assert!(
merge_batch_key_profile(
None,
Some(&Some(document(embedded))),
Some(replacement.parse().unwrap())
)
.is_err()
);
}
}
#[test]
fn complete_custom_identities_send_exact_user_agent_and_matching_companion_headers() {
let state = CodexWireProfileState::new(CodexWireProfile {
@@ -1,6 +1,6 @@
//! xAI OAuth account 的实时模型目录与可重建 TTL cache 边界
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet, btree_map::Entry};
use std::fmt;
use std::sync::{Arc, RwLock};
use std::time::SystemTime;
@@ -361,10 +361,13 @@ pub struct GrokCredentialCatalogService {
wire_profile: XaiWireProfileState,
}
/// 同一目录模型可由多个套餐的成员账号发现
pub(crate) type SourcedCatalogModel = (GrokCatalogModel, BTreeSet<ProviderAccountId>);
#[derive(Default)]
struct PublishedCatalogState {
generation: u64,
models: Vec<GrokCatalogModel>,
models: Vec<SourcedCatalogModel>,
}
impl GrokCredentialCatalogService {
@@ -496,27 +499,26 @@ impl GrokCredentialCatalogService {
.map_err(|_| GrokCredentialCatalogError::Cache)
}
/// Provider Registry 构建 RuntimeSnapshot 时使用的实时能力目录
pub async fn query_models(&self) -> Result<Vec<GrokCatalogModel>, GrokCredentialCatalogError> {
self.fetch_and_cache().await
}
async fn fetch_and_cache(&self) -> Result<Vec<GrokCatalogModel>, GrokCredentialCatalogError> {
/// 快照同时冻结套餐目录及其成员;来源变化也要求重新发布
pub async fn query_models(
&self,
) -> Result<Vec<SourcedCatalogModel>, GrokCredentialCatalogError> {
let candidates = self
.repository
.list_loaded_for_provider()
.await
.map_err(|_| GrokCredentialCatalogError::Store)?
.into_iter()
.filter(eligible_catalog_candidate)
.collect::<Vec<_>>();
.map_err(|_| GrokCredentialCatalogError::Store)?;
let groups = catalog_candidates_by_scope(candidates)?;
// 单个套餐失败只跳过该套餐,不阻断其他套餐的目录同步
let mut fetched = Vec::with_capacity(groups.len());
let mut last_error = None;
for (scope, candidates) in groups {
let accounts = candidates
.iter()
.map(|candidate| candidate.account.id().clone())
.collect();
match self.fetch_scope_catalog(scope.clone(), candidates).await {
Ok(catalog) => fetched.push(catalog),
Ok(catalog) => fetched.push((catalog, accounts)),
Err(error) => {
tracing::warn!(
scope = scope.as_str(),
@@ -530,10 +532,9 @@ impl GrokCredentialCatalogService {
if fetched.is_empty() {
return Err(last_error.unwrap_or(GrokCredentialCatalogError::NoEligibleCredential));
}
fetched.sort_by(|left, right| left.scope.cmp(&right.scope));
let models = strict_model_union(&fetched)?;
let observed_at = Utc::now();
for fetched in fetched {
for (fetched, _) in fetched {
let scope = fetched.scope.clone();
if self
.cache
@@ -593,7 +594,7 @@ impl GrokCredentialCatalogService {
Err(last_error.unwrap_or(GrokCredentialCatalogError::NoEligibleCredential))
}
fn publish_models(&self, models: &[GrokCatalogModel]) {
fn publish_models(&self, models: &[SourcedCatalogModel]) {
let mut published = self
.published
.write()
@@ -691,18 +692,23 @@ async fn fetch_candidate_catalog(
}
fn strict_model_union(
fetched: &[FetchedCredentialCatalog],
) -> Result<Vec<GrokCatalogModel>, GrokCredentialCatalogError> {
let mut union = BTreeMap::<String, GrokCatalogModel>::new();
for credential in fetched {
fetched: &[(FetchedCredentialCatalog, BTreeSet<ProviderAccountId>)],
) -> Result<Vec<SourcedCatalogModel>, GrokCredentialCatalogError> {
let mut union = BTreeMap::<String, SourcedCatalogModel>::new();
for (credential, accounts) in fetched {
for model in credential.snapshot.models() {
let slug = model.request_model().as_str().to_owned();
if let Some(existing) = union.get(&slug) {
if existing != model {
return Err(GrokCredentialCatalogError::ConflictingModelFacts);
match union.entry(slug) {
Entry::Vacant(entry) => {
entry.insert((model.clone(), accounts.clone()));
}
Entry::Occupied(mut entry) => {
let (existing, sources) = entry.get_mut();
if existing != model {
return Err(GrokCredentialCatalogError::ConflictingModelFacts);
}
sources.extend(accounts.iter().cloned());
}
} else {
union.insert(slug, model.clone());
}
}
}
@@ -190,7 +190,9 @@ impl Provider for GrokBuildProvider {
})?;
Ok(models
.into_iter()
.map(compile_grok_model_capabilities)
.map(|(model, accounts)| {
compile_grok_model_capabilities(model).with_catalog_accounts(accounts)
})
.collect())
}
@@ -140,9 +140,23 @@ async fn catalog_query_caches_each_plan_and_returns_strict_union() {
assert_eq!(service.catalog_generation().get(), 1);
service.query_models().await.expect("same catalog sync");
assert_eq!(service.catalog_generation().get(), 1);
store
.set_enabled(&account_id("catalog-b"), false)
.await
.unwrap();
let remaining = service
.query_models()
.await
.expect("same model, one remaining source");
assert_eq!(service.catalog_generation().get(), 2);
assert_eq!(remaining[0].1, [account_id("catalog-a")].into());
assert_eq!(
models[0].1,
[account_id("catalog-a"), account_id("catalog-b")].into()
);
assert_eq!(models.len(), 1);
assert_eq!(models[0].request_model().as_str(), "grok-4.5");
assert_eq!(models[0].0.request_model().as_str(), "grok-4.5");
let account = store
.account(&account_id("catalog-a"))
.expect("created account");
@@ -467,7 +481,7 @@ async fn failed_plan_scope_is_skipped_and_surviving_plans_still_cache() {
.expect("surviving plan still refreshes the catalog");
assert_eq!(models.len(), 1);
assert_eq!(models[0].request_model().as_str(), "grok-4.5");
assert_eq!(models[0].0.request_model().as_str(), "grok-4.5");
assert_eq!(transport.calls(), 2);
let standard = store
.account(&account_id("plan-standard"))
@@ -4153,6 +4153,10 @@ async fn provider_compiles_realtime_catalog_capabilities() {
.expect("capabilities");
assert_eq!(capabilities.len(), 1);
assert_eq!(capabilities[0].upstream_model().as_str(), MODEL);
assert_eq!(
capabilities[0].catalog_accounts(),
Some(&BTreeSet::from([account_id("catalog-provider")]))
);
assert!(
capabilities[0]
.capabilities()
+1
View File
@@ -42,3 +42,4 @@ aeff99fee7cef5a553ae49ffe27a48f49e31ccfb3fbc61a2482c9b109478202d 0041_account_m
19eba6b493647da51996831f72d7bc83e95416c06f207ea685f8f5e2edea7c64 0042_usage_retention_days.sql
223589308df852154004385b13c91a03714114fb9472f00472099bcf2c131cb3 0043_quota_reset_window_weights.sql
23eeb6ef99de2315cf4a198638e9c73b364fb1cb40b7e571a3f15d3e9d15f67c 0044_account_quota_settings.sql
4e4415d21e951f4ce6cddebfd485032dd33d241dd7d9e9ed9b45b3a10f8e3878 0045_account_group_policies.sql
@@ -0,0 +1,21 @@
-- 分组策略沿用账号模型规则,既有分组允许所有模型及子代理
alter table account_groups
drop constraint account_groups_fast_mode_check,
add constraint account_groups_fast_mode_check check (fast_mode in ('default', 'enabled', 'disabled', 'ultrafast')),
add column allow_subagents boolean not null default true,
add column model_access_json jsonb not null default '{"mode":"all","models":[]}'::jsonb,
add constraint account_groups_model_access_ck check (
jsonb_typeof(model_access_json) = 'object'
and model_access_json ?& array['mode', 'models']
and model_access_json - 'mode' - 'models' = '{}'::jsonb
and octet_length(model_access_json::text) <= 131072
and case when jsonb_typeof(model_access_json -> 'models') = 'array' then
case model_access_json ->> 'mode'
when 'all' then jsonb_array_length(model_access_json -> 'models') = 0
when 'allowlist' then jsonb_array_length(model_access_json -> 'models') between 1 and 256
when 'denylist' then jsonb_array_length(model_access_json -> 'models') between 1 and 256
else false
end
and not jsonb_path_exists(model_access_json, '$.models[*] ? (@.type() != "string")')
else false end
);
+33 -14
View File
@@ -38,7 +38,7 @@ Codex 原生生图配置还会携带 `X-OpenAI-Actor-Authorization: proxy-manage
上游账号身份只由服务端选中的账号提供;不要把真实账号 token 放进该标记
Client Key 通过账号分组限定路由范围:未绑定分组时可使用全部账号,绑定一个或多个分组时只能使用
已启用分组成员的并集。分组可以混合 `openai` 与 `xai` 账号;同一请求只会在模型能力明确匹配且满足
至少一个已启用绑定分组中允许该模型的成员账号。分组可以混合 `openai` 与 `xai` 账号;同一请求只会在模型能力明确匹配且满足
重放安全边界时跨 Provider fallback
运行设置可以分别配置 `minCodexDesktopVersion` 与 `minCodexCliVersion`。两者只接受 SemVer,`null`
@@ -1412,10 +1412,10 @@ Pro 使用 `all` 时也能参与 luna 调度。套餐名称不自动生成或修
限制适用于 Responses(含 WebSocket 和上下文压缩)、Chat Completions、Messages 生成与输入计数,以及 Images 生图、编辑与独立 Search。
重试、亲和和换号同样遵守限制;没有合规账号时返回无可用账号错误。已开始请求使用冻结的政策,新请求使用已发布的新配置。
Images 和 Search 按原始请求正文的模型 ID 检查,不依赖模型目录或全局模型映射;可手动添加目录未列出的模型 ID。
模型缺失、重复或无法识别时,仅使用模型政策为 `all` 的账号,不推测上游默认模型。
模型缺失、重复或无法识别时,账号模型政策须为 `all`。对于绑定分组的 Key,还须有至少一个包含该账号的启用分组允许全部模型。
Search 的选号限制不约束插件在选号后主动改写正文。
管理员连接测试的选项包含上游目录和账号白名单中的 ID。连接测试跳过普通选号的模型政策、目录资格筛选与模型拒绝冷却,成功表示指定账号可调用测试使用的端点与模型。
普通 `/v1/models` 和单模型查询将已发现的 OpenAI 模型关联到来源账号,至少一个来源账号在当前 Key 范围内且政策允许时才展示;
普通 `/v1/models` 和单模型查询将已发现的 OpenAI 和 xAI 模型关联到来源账号,至少一个来源账号在当前 Key 范围内且政策允许时才展示;
同 Provider 中未发现该模型的 `all` 账号不会使它进入列表。原生目录保留已有来源选择和完整模型对象
### 独立代理管理 / Managed Proxies
@@ -1969,35 +1969,46 @@ GET 和 POST 均返回 `enabled`、`leadMinutes`、`weeklyTriggerRemainingPercen
## 6. 账号分组
分组是 Provider-neutral 的账号集合;一个组可包含任意 Provider 账号,一个账号也可属于多个组。
分组详情和列表返回 `fastMode`,取值为 `default`(默认)、`enabled`(开启)、`disabled`(关闭)。
创建时省略默认为 `default`,更新时省略或 `null` 保留现值。
策略取自 Client Key 绑定的分组,包括已禁用分组;多分组冲突时关闭优先,其次开启,最后默认。
未绑定分组的 Key 跟随客户端,不按最终所选账号的分组判断
分组详情和完整列表返回 `modelAccess`、`fastMode`、`allowImageGeneration` 和 `allowSubagents`。创建时省略这些字段使用默认值,更新时省略或传 `null` 保留现值。
- 默认:保留客户端的 `service_tier`
- 开启:所选上游模型的目录声明 `priority` 时,将缺失、`null` 或显式 `default` 改为 `priority`;目录未声明则保留原值
- 关闭:将 `priority`(含 `fast` 别名)改为显式 `default`,继续处理请求
`modelAccess` 复用账号的模型规则。默认 `{"mode":"all","models":[]}` 允许成员账号原本可以使用的模型。
`allowlist` 和 `denylist` 使用区分大小写的完整模型 ID。编辑器候选取自该组成员账号,账号自身的限制继续生效。
Key 绑定多个组时,按模型分别合并启用组中的合格账号。例如两个组分别允许 X 和 Y,X 请求只能使用允许 X 的组内账号。
策略只作用于 OpenAI Responses 的顶层 `service_tier`,不改变 `flex`、`ultrafast` 等其他显式档位、嵌套字段或其他 Provider。
`fastMode` 默认跟随客户端。策略合并包括 Key 绑定的禁用分组,优先级依次为 `disabled`、`enabled`、`ultrafast`、`default`。未绑定分组的 Key 跟随客户端
| 值 | OpenAI Responses 顶层 `service_tier` |
| --- | --- |
| `default` | 保留客户端档位 |
| `disabled` | 将 `priority`、`fast`、`ultrafast` 降至 `default`,保留其他档位 |
| `enabled` | 强制 Fast,所选上游模型的目录声明支持时覆盖为 `priority` |
| `ultrafast` | 强制 Ultrafast,所选上游模型的目录声明支持时覆盖为 `ultrafast` |
目标档位缺少目录支持时保留原请求。
OAuth 和 Responses API Key 共用上述档位规则,出站兼容层不额外删除原生 Responses 的 `auto/default`。
宿主策略在 request 中间件之后应用,形成 attempt 输入基线;attempt 中间件继续改写档位时,以改写后的实际发送值为准。
HTTP 和每个 WebSocket `response.create` 均使用请求开始时的分组策略,同一请求重试保持该策略;
HTTP 请求头及新建 WS 的握手提示按当时的最终出站档位构造;复用 WS 时不重发握手头,
每个 `response.create` 仍独立应用档位策略,请求档位统计与本地费用估算使用各帧的最终出站档位
分组详情和完整列表还返回 `allowImageGeneration`。创建时省略默认为 `true`,更新时省略或 `null` 保留现值。
`allowImageGeneration` 默认为 `true`。
Client Key 任一绑定分组(包括已禁用分组)为 `false` 时,禁止生图;未绑定分组的 Key 允许生图。
限制覆盖 Images 生成与编辑,以及 Responses 中的原生 `image_generation` 工具声明或显式工具选择,
HTTP 返回 `403` 和 `image_generation_disabled`,WebSocket 每个 `response.create` 独立校验并返回对应错误事件。
普通图片输入和 Codex 被动声明的 `image_gen` namespace 不触发拒绝;实际 Images 调用仍受限制。
请求采用开始时冻结的权限,重试期间保持不变;attempt 中间件添加生图工具也会在发送前被策略拒绝
`allowSubagents` 默认为 `true`,客户端可以按自身配置启动协作子代理。任一绑定分组设为 `false` 时,Codex 模型目录呈现 `multi_agent_version: "disabled"`。
网关按协作子代理元数据识别独立请求,HTTP 或 WebSocket 的 `response.create` 在转发前返回 `403` 和 `subagents_disabled`。
主会话、审查和上下文压缩请求仍可使用
| 方法 | 路由 | 主要 query/body | 说明 |
| --- | --- | --- | --- |
| `GET` | `/api/admin/account-groups` | `page`、`pageSize`、`search`、`enabled` | 分页查询分组;返回账号可用性、并发槽位(Redis 不可用时 `usedSlots=null`)及成功请求 USD 用量 |
| `GET` | `/api/admin/account-groups/options` | `page`、`pageSize`、`search`、`enabled` | 分页查询分组选择项;item 仅返回 `id`、`name`、`color`、`enabled` |
| `POST` | `/api/admin/account-groups/create` | `{ name, description, color, fastMode?, allowImageGeneration? }` | 创建空分组;`color` 严格为 `#RRGGBBAA`,返回时统一大写 |
| `POST` | `/api/admin/account-groups/update` | `{ id, name, description, color, fastMode?, allowImageGeneration? }` | 更新分组信息、Fast 模式和生图权限 |
| `GET` | `/api/admin/account-groups/models` | `id` | 返回成员账号候选模型 `{ models: [{ id, label }] }`,按模型 ID 去重 |
| `POST` | `/api/admin/account-groups/create` | `{ name, description, color, modelAccess?, fastMode?, allowImageGeneration?, allowSubagents? }` | 创建空分组;`color` 严格为 `#RRGGBBAA`,返回时统一大写 |
| `POST` | `/api/admin/account-groups/update` | `{ id, name, description, color, modelAccess?, fastMode?, allowImageGeneration?, allowSubagents? }` | 更新分组信息和请求权限 |
| `POST` | `/api/admin/account-groups/enable` | `{ id }` | 启用 |
| `POST` | `/api/admin/account-groups/disable` | `{ id }` | 禁用;已绑定 Key 保持受限,不回退到全部账号 |
| `POST` | `/api/admin/account-groups/delete` | `{ id }` | 删除未被 Client Key 引用的组 |
@@ -2022,11 +2033,19 @@ HTTP 返回 `403` 和 `image_generation_disabled`,WebSocket 每个 `response.c
| `POST` | `/api/admin/client-keys/create` | 创建字段 | 创建带账号范围的 Client Key |
| `GET` | `/api/admin/client-keys/reveal` | `id` | 显式读取完整明文 Key |
| `POST` | `/api/admin/client-keys/update` | 更新字段 | 原子更新名称、分组范围和限额 |
| `POST` | `/api/admin/client-keys/batch-update` | `ids` 和至少一个更新字段 | 原子更新 1 至 1000 个不同密钥,返回 `{ updated, configRevision }` |
| `POST` | `/api/admin/client-keys/reset-budget` | `{ id, period }` | 管理员清零日/周已用金额;`period` 为 `daily`、`weekly` 或 `all` |
| `POST` | `/api/admin/client-keys/enable` | `{ id }` | 启用 |
| `POST` | `/api/admin/client-keys/disable` | `{ id }` | 禁用 |
| `POST` | `/api/admin/client-keys/delete` | `{ id }` | 删除 |
批量更新只提交要修改的字段,各密钥保留其余配置。任一密钥或分组不存在、任一密钥的最终配置无效时,整批回滚
- `enabled` 设置启用状态。`groupIds` 替换全部分组,显式传空数组授权全部当前及未来账号
- `dailyLimitUsd`、`weeklyLimitUsd`、`maxConcurrency`、`requestsPerMinute` 可独立修改,零表示不限。修改限额保留已用金额及重置时间
- `peerSharing` 可单独修改 `enabled`、`sharePool`、`shareQuota`、`sharePlans`。开启互联需要绑定分组,共享套餐构成需要开启账号池概览
- `providerRequestProfileOverrides` 按 Provider 更新,显式传入某个 Provider 为 `null` 时恢复其全局配置。`installationSeed` 单独接受 UUID;仅修改身份配置时保留各密钥原有种子,仅修改种子时保留各自的身份配置
创建字段为 `name`、可选 `label`、`groupIds`、`maxConcurrency`、`requestsPerMinute`、可选
`dailyLimitUsd`、`weeklyLimitUsd`、`customKey`、`providerRequestProfileOverrides` 和 `peerSharing`。更新请求携带 `id`,不接受 `customKey`。
`groupIds` 必须显式提交:空数组派生 `routingScope: "all"`,非空数组派生
+4 -2
View File
@@ -505,12 +505,14 @@ Store 将策略与设置 revision 原子持久化;编译结果随快照、计
关闭策略不进入改写管线。字段与执行限制见[隐私策略 API](api.md#隐私策略)
Fast 策略由 Core 合并 Client Key 的全部绑定分组并随同一快照链路冻结,禁用分组也参与合并;
不按所选账号的分组重新解释。三态覆盖顺序与字段合同见[账号分组 API](api.md#6-账号分组)。
不按所选账号的分组重新解释。档位优先级与字段合同见[账号分组 API](api.md#6-账号分组)。
OpenAI Provider 在独立编码请求上、生成上游头与观测前统一应用顶层档位覆盖,HTTP、WS 与重试共用。
该策略不改变选号、会话亲和或共享原始请求;每个新 WS 请求重新取得当前策略。
WS 路由提示属于握手,连接复用时不重发;档位变化不重建连接或打断 `previous_response_id` 续写,
各帧正文及计费仍使用本次请求的最终档位
协作子代理权限随同一快照冻结。API 识别 Codex 协作请求,并按 Key 投影原生模型目录的协作能力。
生图权限由 Core 随 Client Key 的账号范围冻结,绑定分组中禁止优先,禁用分组仍贡献限制。
执行入口在路由与准入前拒绝生图 operation,attempt 中间件提交最终 operation 时再次校验;
拒绝使用统一 `PolicyDenied`,发送前失败标记为 `NotSent` 且禁止重试,不改写原始工具声明。
@@ -636,7 +638,7 @@ xAI Provider 负责 Codex custom 工具与 Grok function 工具的双向转换
Client Key 与账号分组形成授权范围:
- 普通 Client Key 没有分组关联表示 `AllAccounts`
- 有关联时只允许已启用分组成员的并集
- 有关联时冻结各启用绑定分组的成员和模型规则。每个模型分别取允许它的组内账号并集,再叠加账号自身模型限制。选号、重试和目录展示共用这一范围
- 已绑定分组为空或全部禁用时得到空池,绝不回退为全部账号
- 分组可以包含多个 Provider,账号也可以属于多个分组
+17 -1
View File
@@ -1,7 +1,8 @@
import type { RequestOptions } from '../request'
import type { AccountModelAccess } from './accounts'
import request from '../request'
export type FastMode = 'default' | 'enabled' | 'disabled'
export type FastMode = 'default' | 'enabled' | 'disabled' | 'ultrafast'
export interface AccountGroupRef {
id: string
@@ -29,6 +30,8 @@ export interface AccountGroupUsage {
export interface AccountGroup extends AccountGroupRef {
fastMode: FastMode
allowImageGeneration: boolean
allowSubagents: boolean
modelAccess: AccountModelAccess
description: string | null
memberCount: number
providerCounts: Record<string, number>
@@ -77,6 +80,8 @@ interface AccountGroupListParams {
interface AccountGroupCreateParam {
fastMode?: FastMode
allowImageGeneration?: boolean
allowSubagents?: boolean
modelAccess?: AccountModelAccess
name: string
description: string | null
color: string
@@ -85,6 +90,8 @@ interface AccountGroupCreateParam {
interface AccountGroupUpdateParam {
fastMode?: FastMode
allowImageGeneration?: boolean
allowSubagents?: boolean
modelAccess?: AccountModelAccess
id: string
name: string
description: string | null
@@ -113,6 +120,15 @@ export function getAccountGroupOptions(data: AccountGroupListParams, options: Re
})
}
export function getAccountGroupModels(id: string, options: RequestOptions = {}) {
return request<{ models: Array<{ id: string, label: string }> }>({
url: '/api/admin/account-groups/models',
method: 'GET',
params: { id },
...options,
})
}
export function createAccountGroup(data: AccountGroupCreateParam) {
return request<AccountGroupMutationResponse>({
url: '/api/admin/account-groups/create',
+16 -1
View File
@@ -1,6 +1,6 @@
import type { RequestOptions } from '../request'
import type { AccountGroupRef } from './groups'
import type { ClientProfileSelection, ProviderRequestProfile, ProviderRequestProfiles, XaiClientProfileSelection } from './settings/profiles'
import type { ClientProfileSelection, ProviderRequestProfile, ProviderRequestProfiles, ProviderRequestProfileUpdates, XaiClientProfileSelection } from './settings/profiles'
import request from '../request'
export type ApiKeyRoutingScope = 'all' | 'groups'
@@ -122,6 +122,21 @@ export function createApiKey(data: ApiKeyCreateParam) {
})
}
export interface ApiKeyBatchChanges extends Partial<Omit<ApiKeyWriteParam, 'name' | 'label' | 'peerSharing'>> {
enabled?: boolean
peerSharing?: Partial<ApiKeyPeerSharing>
providerRequestProfileOverrides?: ProviderRequestProfileUpdates
installationSeed?: string
}
export function batchUpdateApiKeys(data: ApiKeyBatchChanges & { ids: string[] }) {
return request<{ updated: number, configRevision: number }>({
url: '/api/admin/client-keys/batch-update',
method: 'POST',
data,
})
}
export function updateApiKey(data: ApiKeyUpdateParam) {
return request<ApiKeyMutationResponse>({
url: '/api/admin/client-keys/update',
@@ -14,15 +14,16 @@ import { errorMessage } from '@/utils/operation'
import ClientProfilePresetFields from './ClientProfilePresetFields.vue'
import ClientProfilePreviewPanel from './ClientProfilePreviewPanel.vue'
const props = withDefaults(defineProps<{ active?: boolean, disabled?: boolean, allowInherit?: boolean }>(), {
const props = withDefaults(defineProps<{ active?: boolean, disabled?: boolean, allowInherit?: boolean, allowPreserve?: boolean }>(), {
active: true,
disabled: false,
allowInherit: false,
allowPreserve: false,
})
const { t } = useI18n({ useScope: 'global' })
const model = defineModel<ClientProfileSelection | null>({ required: true })
const model = defineModel<ClientProfileSelection | null | undefined>({ required: true })
const options = shallowRef<ClientProfileOptions>()
const preview = shallowRef<ClientProfilePreview>()
const loading = shallowRef(true)
@@ -40,10 +41,16 @@ const needsInput = computed(() => effective.value?.mode === 'custom'
: preset.value?.versionMode === 'fixed'
&& (!preset.value.codexVersion || (preset.value.client === 'desktop' && (!preset.value.desktopVersion || !preset.value.desktopBuild))))
const profileSource = computed({
get: () => model.value === null
? 'global'
: 'independent',
get: () => model.value === undefined
? 'keep'
: model.value === null
? 'global'
: 'independent',
set: (value: string) => {
if (value === 'keep') {
model.value = undefined
return
}
if (value === 'global') {
if (model.value)
independentDraft.value = { ...model.value }
@@ -74,7 +81,7 @@ watch([
model,
() => props.active,
], ([configuration, active], _, onCleanup) => {
if (!active)
if (!active || configuration === undefined)
return
let cancelled = false
preview.value = undefined
@@ -117,6 +124,7 @@ onMounted(() => load())
:aria-label="t('settings.clientProfile.clientIdentitySource')"
class="shrink-0"
:options="[
...(allowPreserve ? [{ label: t('accounts.modelAccess.reserve'), value: 'keep' }] : []),
{ label: t('settings.clientProfile.globalConfiguration'), value: 'global' },
{ label: t('settings.clientProfile.customConfiguration'), value: 'independent' },
]"
@@ -125,7 +133,7 @@ onMounted(() => load())
<slot name="source-extra" />
</div>
<ClientProfilePresetFields
v-if="!loadError && !inherited"
v-if="model !== undefined && !loadError && !inherited"
:model-value="effective ?? null"
:presets="options?.presets ?? []"
:preview="preview"
@@ -136,7 +144,7 @@ onMounted(() => load())
@update:model-value="model = $event"
/>
<ClientProfilePreviewPanel
v-if="!loadError && (inherited || !custom)"
v-if="model !== undefined && !loadError && (inherited || !custom)"
:preview="preview"
:previewing="previewing"
:needs-version-input="!!needsInput"
@@ -1,16 +1,18 @@
<script setup lang="ts">
import type { ClientProfileSelection, ProviderRequestProfile, ProviderRequestProfiles, XaiClientProfileSelection } from '@/api/modules/settings/profiles'
import type { ClientProfileSelection, ProviderRequestProfile, ProviderRequestProfiles, ProviderRequestProfileUpdates, XaiClientProfileSelection } from '@/api/modules/settings/profiles'
import { ZSegmented } from '@codex-proxy/ui'
import { isEqual } from 'es-toolkit'
import { computed, shallowRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/utils/providers'
import ClientProfileEditor from './ClientProfileEditor.vue'
import XaiClientProfileEditor from './XaiClientProfileEditor.vue'
withDefaults(defineProps<{
const props = withDefaults(defineProps<{
active?: boolean
disabled?: boolean
initialProfiles?: ProviderRequestProfileUpdates
allowInherit?: boolean
}>(), {
active: true,
@@ -20,7 +22,10 @@ withDefaults(defineProps<{
const { t } = useI18n({ useScope: 'global' })
const model = defineModel<ProviderRequestProfiles>({ required: true })
const model = defineModel<ProviderRequestProfiles>({
default: () => ({}),
})
const updates = defineModel<ProviderRequestProfileUpdates>('updates')
const provider = shallowRef<(typeof PROVIDER_IDS)[number]>('openai')
const providerOptions = PROVIDER_IDS.map(value => ({
value,
@@ -32,20 +37,35 @@ const openai = profileModel<ClientProfileSelection>('openai')
const xai = profileModel<XaiClientProfileSelection>('xai')
function profileModel<T extends object>(providerId: string) {
return computed<T | null>({
get: () => (model.value[providerId] as T | undefined) ?? null,
set: value => updateProfile(providerId, value as ProviderRequestProfile | null),
return computed<T | null | undefined>({
get: () => {
if (updates.value === undefined)
return (model.value[providerId] as T | undefined) ?? null
const source = Object.hasOwn(updates.value, providerId)
? updates.value
: props.initialProfiles
return source?.[providerId] as T | null | undefined
},
set: (value) => {
if (updates.value !== undefined) {
const next = { ...updates.value }
if (value === undefined || isEqual(value, props.initialProfiles?.[providerId]))
delete next[providerId]
else
next[providerId] = value as ProviderRequestProfile | null
updates.value = next
}
else {
const next = { ...model.value }
if (value == null)
delete next[providerId]
else
next[providerId] = value as ProviderRequestProfile
model.value = next
}
},
})
}
function updateProfile(providerId: string, value: ProviderRequestProfile | null) {
const profiles = { ...model.value }
if (value === null)
delete profiles[providerId]
else
profiles[providerId] = value
model.value = profiles
}
</script>
<template>
@@ -66,6 +86,7 @@ function updateProfile(providerId: string, value: ProviderRequestProfile | null)
v-if="provider === 'openai'"
v-model="openai"
:allow-inherit="allowInherit"
:allow-preserve="updates !== undefined && initialProfiles?.[provider] === undefined"
:active="active"
:disabled="disabled"
>
@@ -85,6 +106,7 @@ function updateProfile(providerId: string, value: ProviderRequestProfile | null)
v-else
v-model="xai"
:allow-inherit="allowInherit"
:allow-preserve="updates !== undefined && initialProfiles?.[provider] === undefined"
:active="active"
:disabled="disabled"
>
@@ -9,15 +9,16 @@ import { notification as ZNotification } from '@/utils/notification'
import { errorMessage } from '@/utils/operation'
import ClientProfilePreviewPanel from './ClientProfilePreviewPanel.vue'
const props = withDefaults(defineProps<{ active?: boolean, disabled?: boolean, allowInherit?: boolean }>(), {
const props = withDefaults(defineProps<{ active?: boolean, disabled?: boolean, allowInherit?: boolean, allowPreserve?: boolean }>(), {
active: true,
disabled: false,
allowInherit: false,
allowPreserve: false,
})
const { t } = useI18n({ useScope: 'global' })
const model = defineModel<XaiClientProfileSelection | null>({ required: true })
const model = defineModel<XaiClientProfileSelection | null | undefined>({ required: true })
const globalConfiguration = shallowRef<XaiClientProfileSelection>()
const preview = shallowRef<XaiClientProfilePreview>()
const loadError = shallowRef('')
@@ -43,10 +44,16 @@ const fields = computed(() => ([
] as const))
const source = computed({
get: () => model.value === null
? 'global'
: 'independent',
get: () => model.value === undefined
? 'keep'
: model.value === null
? 'global'
: 'independent',
set: (value: string) => {
if (value === 'keep') {
model.value = undefined
return
}
if (value === 'global')
model.value = null
else if (globalConfiguration.value)
@@ -95,7 +102,7 @@ watch([
model,
() => props.active,
], ([configuration, active], _, onCleanup) => {
if (!active)
if (!active || configuration === undefined)
return
let cancelled = false
preview.value = undefined
@@ -137,7 +144,11 @@ onMounted(() => props.allowInherit && void load())
v-model="source"
:aria-label="t('settings.clientProfile.xaiClientIdentitySource')"
class="shrink-0"
:options="[{ label: t('settings.clientProfile.globalConfiguration'), value: 'global' }, { label: t('settings.clientProfile.customConfiguration'), value: 'independent' }]"
:options="[
...(allowPreserve ? [{ label: t('accounts.modelAccess.reserve'), value: 'keep' }] : []),
{ label: t('settings.clientProfile.globalConfiguration'), value: 'global' },
{ label: t('settings.clientProfile.customConfiguration'), value: 'independent' },
]"
:disabled="disabled || !globalConfiguration"
/>
<slot name="source-extra" />
@@ -160,6 +171,6 @@ onMounted(() => props.allowInherit && void load())
</ZFormItem>
</div>
</template>
<ClientProfilePreviewPanel v-if="!loadError" :preview="preview" :previewing="previewing" :needs-version-input="needsVersionInput" />
<ClientProfilePreviewPanel v-if="model !== undefined && !loadError" :preview="preview" :previewing="previewing" :needs-version-input="needsVersionInput" />
</div>
</template>
+2 -1
View File
@@ -62,7 +62,8 @@
"next": "Next",
"confirm": "Confirm",
"refresh": "Refresh",
"save": "Save"
"save": "Save",
"disable": "Disable"
},
"providers": {
"all": "All platforms",
+10 -3
View File
@@ -35,10 +35,18 @@
"selectGroupColor": "Select group color",
"fastMode": "Fast mode",
"imageGeneration": "Image generation",
"descriptionOptional": "Description (optional)",
"description": "Description",
"groupDescription": "Group description",
"describePurposeOfThisGroup": "Describe the purpose of this group",
"saveGroup": "Save"
"saveGroup": "Save",
"forceFast": "Force Fast",
"forceUltrafast": "Force Ultrafast",
"subagents": "Collaborative subagents",
"memberModels": "Member account models",
"searchModels": "Search member models",
"emptyCatalog": "Add an account with available models to this group first",
"fastModeHelp": "Default follows the client. Disable downgrades both accelerated tiers to standard. A forced tier overrides the client selection when the model supports it.",
"subagentsHelp": "Enable lets the client decide when to start a collaborative subagent. Disable rejects requests identified as coming from a collaborative subagent."
},
"metrics": {
"restricted": "Restricted",
@@ -56,7 +64,6 @@
"empty": "No groups yet",
"selectCurrentPageGroup": "Select current page group",
"selectGroup": "Select group",
"fastModeIsOn": "Fast mode is on",
"fastModeIsOff": "Fast mode is off",
"imageGenerationDisabled": "Image generation disabled",
"colorLabel": "Group color: {color}",
+8
View File
@@ -110,6 +110,14 @@
"confirm": "Allow access",
"description": "After saving, this includes ungrouped and future accounts"
}
},
"batch": {
"edit": "Bulk edit",
"updated": "Updated {count} API keys",
"description": "{count} key selected | {count} keys selected",
"partiallyEnabled": "Some keys are enabled",
"mixed": "Multiple values",
"clearLimit": "Set unlimited"
}
}
}
@@ -62,7 +62,8 @@
"next": "下一步",
"confirm": "确定",
"refresh": "刷新",
"save": "保存"
"save": "保存",
"disable": "禁用"
},
"providers": {
"all": "全部平台",
+11 -4
View File
@@ -35,10 +35,18 @@
"selectGroupColor": "选择分组颜色",
"fastMode": "快速模式",
"imageGeneration": "图像生成",
"descriptionOptional": "描述(可选)",
"description": "描述",
"groupDescription": "分组描述",
"describePurposeOfThisGroup": "说明这个分组的用途",
"saveGroup": "保存分组"
"saveGroup": "保存分组",
"forceFast": "快速",
"forceUltrafast": "超快速",
"subagents": "协作子代理",
"memberModels": "成员账号模型",
"searchModels": "搜索成员账号模型",
"emptyCatalog": "暂无成员模型,请先将有模型的账号加入分组",
"fastModeHelp": "默认跟随客户端。禁用会将加速请求降为标准档。选择快速或超快速时,若模型支持该档位,分组设置会覆盖客户端选择",
"subagentsHelp": "启用后由客户端决定是否启动协作子代理。禁用会拒绝可识别的协作子代理请求"
},
"metrics": {
"restricted": "受限",
@@ -56,8 +64,7 @@
"empty": "暂无分组",
"selectCurrentPageGroup": "选择当前页分组",
"selectGroup": "选择分组",
"fastModeIsOn": "Fast 已开启",
"fastModeIsOff": "Fast 已关闭",
"fastModeIsOff": "快速模式已关闭",
"imageGenerationDisabled": "生图已关闭",
"colorLabel": "分组颜色 {color}",
"batchDeleteWarning": "删除后这些分组将立即失效,此操作不可撤销",
@@ -110,6 +110,14 @@
"confirm": "允许访问",
"description": "保存后也可访问未分组和以后新增的账号"
}
},
"batch": {
"edit": "批量编辑",
"updated": "已更新 {count} 个密钥",
"description": "已选 {count} 个密钥",
"partiallyEnabled": "部分密钥已启用",
"mixed": "多个值",
"clearLimit": "设为不限"
}
}
}
@@ -62,7 +62,8 @@
"next": "下一步",
"confirm": "確定",
"refresh": "刷新",
"save": "保存"
"save": "保存",
"disable": "禁用"
},
"providers": {
"all": "全部平臺",
+11 -4
View File
@@ -35,10 +35,18 @@
"selectGroupColor": "選擇分組顏色",
"fastMode": "快速模式",
"imageGeneration": "圖像生成",
"descriptionOptional": "描述(可選)",
"description": "描述",
"groupDescription": "分組描述",
"describePurposeOfThisGroup": "說明這個分組的用途",
"saveGroup": "保存分組"
"saveGroup": "保存分組",
"forceFast": "快速",
"forceUltrafast": "超快速",
"subagents": "協作子代理",
"memberModels": "成員帳號模型",
"searchModels": "搜尋成員帳號模型",
"emptyCatalog": "暫無成員模型,請先將有模型的帳號加入分組",
"fastModeHelp": "預設跟隨用戶端。禁用會將加速請求降為標準檔。選擇快速或超快速時,若模型支援該檔位,分組設定會覆寫用戶端選擇",
"subagentsHelp": "啟用後由用戶端決定是否啟動協作子代理。禁用會拒絕可識別的協作子代理請求"
},
"metrics": {
"restricted": "受限",
@@ -56,8 +64,7 @@
"empty": "暫無分組",
"selectCurrentPageGroup": "選擇當前頁分組",
"selectGroup": "選擇分組",
"fastModeIsOn": "Fast 已開啓",
"fastModeIsOff": "Fast 已關閉",
"fastModeIsOff": "快速模式已關閉",
"imageGenerationDisabled": "生圖已關閉",
"colorLabel": "分組顏色 {color}",
"batchDeleteWarning": "刪除後這些分組將立即失效,此操作不可撤銷",
@@ -110,6 +110,14 @@
"confirm": "允許訪問",
"description": "保存後也可訪問未分組和以後新增的賬號"
}
},
"batch": {
"edit": "批次編輯",
"updated": "已更新 {count} 個金鑰",
"description": "已選 {count} 個密鑰",
"partiallyEnabled": "部分密鑰已啟用",
"mixed": "多個值",
"clearLimit": "設為不限"
}
}
}
@@ -6,7 +6,7 @@ import { ZButton, ZEmpty, ZFormItem, ZIconButton, ZInput, ZPopover, ZSegmented }
import { CircleAlert, ListChecks, ListMinus, Plus, RefreshCw, Search } from '@lucide/vue'
import { computed, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { getAccountModels, refreshAccountModels } from '@/api'
import { getAccountGroupModels, getAccountModels, refreshAccountModels } from '@/api'
import { useRequestState } from '@/composables/useRequestState'
import { accountModelAccessError, accountModelIdError } from '../utils/modelAccess'
import AccountModelCleanupPopover from './AccountModelCleanupPopover.vue'
@@ -14,6 +14,7 @@ import AccountModelOption from './AccountModelOption.vue'
const props = withDefaults(defineProps<{
accountId?: string
groupId?: string | null
disabled?: boolean
allowPreserve?: boolean
formProp: string
@@ -33,6 +34,8 @@ const searchInput = useTemplateRef<InstanceType<typeof ZInput>>('searchInput')
const selectionError = ref('')
const request = useRequestState()
const { loading, error } = request
const groupCatalog = computed(() => props.groupId !== undefined)
const catalogOwner = computed(() => props.groupId ?? props.accountId)
const modes = computed(() => [
...(props.allowPreserve
? [
@@ -44,14 +47,18 @@ const modes = computed(() => [
: []),
{
value: 'all',
label: t('common.values.unlimited'),
label: groupCatalog.value
? t('common.values.default')
: t('common.values.unlimited'),
},
{
value: 'allowlist',
disabled: props.groupId === null,
label: t('accounts.modelAccess.allowlist'),
},
{
value: 'denylist',
disabled: props.groupId === null,
label: t('accounts.modelAccess.blocklist'),
},
])
@@ -101,11 +108,13 @@ const groups = computed(() => [
},
{
key: 'catalog',
label: t('accounts.modelAccess.upstreamCatalog'),
label: groupCatalog.value
? t('groups.editor.memberModels')
: t('accounts.modelAccess.upstreamCatalog'),
ids: catalogResults.value,
},
].filter(group => group.ids.length))
const newModelId = computed(() => groups.value.length
const newModelId = computed(() => groupCatalog.value || groups.value.length
? ''
: search.value.trim())
const inputError = computed(() => selectionError.value || (newModelId.value && accountModelIdError(newModelId.value)))
@@ -182,18 +191,23 @@ function handleCatalogHelpKeydown(event: KeyboardEvent, open: boolean, close: ()
}
async function load(refresh = false) {
const accountId = props.accountId
if (!accountId || !restricted.value)
const id = catalogOwner.value
if (!id || !restricted.value)
return
const requestId = request.start()
const options = { signal: request.signal }
try {
const result = await (refresh ? refreshAccountModels : getAccountModels)(
{ accountId },
{ signal: request.signal },
)
if (request.isCurrent(requestId)) {
catalog.value = result.models
catalogObservedAtDisplay.value = result.observedAt ? result.observedAtDisplay : undefined
if (groupCatalog.value) {
const result = await getAccountGroupModels(id, options)
if (request.isCurrent(requestId))
catalog.value = result.models
}
else {
const result = await (refresh ? refreshAccountModels : getAccountModels)({ accountId: id }, options)
if (request.isCurrent(requestId)) {
catalog.value = result.models
catalogObservedAtDisplay.value = result.observedAt ? result.observedAtDisplay : undefined
}
}
}
catch (cause) {
@@ -205,7 +219,7 @@ async function load(refresh = false) {
}
watch([
() => props.accountId,
catalogOwner,
() => model.value?.models,
], ([accountId, ids], [previousAccountId]) => {
const retained = accountId === previousAccountId
@@ -220,7 +234,7 @@ watch([
}, { immediate: true })
watch([
() => props.accountId,
catalogOwner,
restricted,
], () => {
request.invalidate()
@@ -248,7 +262,7 @@ watch(search, () => {
</span>
</span>
</template>
<template v-if="restricted" #label-extra>
<template v-if="restricted && !groupCatalog" #label-extra>
<ZPopover class="-my-1 -ml-1.5 shrink-0" trigger="hover-click" placement="top-start" role="tooltip">
<template #reference="{ open, id, close }">
<ZIconButton
@@ -273,8 +287,8 @@ watch(search, () => {
</ZPopover>
</template>
<div class="flex min-w-0 items-center justify-between gap-2">
<ZSegmented v-model="mode" class="w-80 min-w-0 max-w-full" :aria-label="t('accounts.modelAccess.modelRestrictionMode')" :options="modes" :disabled="disabled" />
<div v-if="restricted && accountId" class="flex shrink-0 items-center gap-1">
<ZSegmented v-model="mode" :class="{ 'w-80': !groupCatalog }" :aria-label="t('accounts.modelAccess.modelRestrictionMode')" :options="modes" :disabled="disabled" />
<div v-if="restricted && catalogOwner" class="flex shrink-0 items-center gap-1">
<AccountModelCleanupPopover v-if="mode === 'allowlist'" :models="missingModels" :model-count="model?.models.length ?? 0" :disabled="disabled || !missingModels.length" @remove="removeMissingModels" @closed="restoreCleanupFocus" />
<ZIconButton ref="refreshButton" :aria-label="t('accounts.modelAccess.refreshModel')" variant="plain" :loading="loading" :disabled="disabled" @click="load(true)">
<template #loading>
@@ -287,12 +301,12 @@ watch(search, () => {
</ZFormItem>
<template v-if="restricted">
<div class="flex min-w-0 items-center gap-2">
<ZInput ref="searchInput" v-model="search" class="min-w-0 flex-1" :aria-label="t('accounts.modelAccess.searchOrAddModels')" :placeholder="t('accounts.modelAccess.searchOrEnterId')" :disabled="disabled" :aria-invalid="Boolean(inputError)" @keydown.enter="handleSearchEnter">
<ZInput ref="searchInput" v-model="search" class="min-w-0 flex-1" :aria-label="groupCatalog ? t('groups.editor.searchModels') : t('accounts.modelAccess.searchOrAddModels')" :placeholder="groupCatalog ? t('groups.editor.searchModels') : t('accounts.modelAccess.searchOrEnterId')" :disabled="disabled" :aria-invalid="Boolean(inputError)" @keydown.enter="handleSearchEnter">
<template #prefix>
<Search class="size-4" aria-hidden="true" />
</template>
</ZInput>
<ZButton class="shrink-0" :disabled="disabled || !canAdd" @click="addModel">
<ZButton v-if="!groupCatalog" class="shrink-0" :disabled="disabled || !canAdd" @click="addModel">
<Plus class="size-4" aria-hidden="true" />
{{ t('accounts.modelAccess.addModel') }}
</ZButton>
@@ -336,7 +350,7 @@ watch(search, () => {
<p v-else-if="mode === 'denylist' && canAdd" class="m-0 text-z-xs text-z-text-secondary">
{{ t('accounts.modelAccess.addToDenylistHint') }}
</p>
<ZEmpty v-else-if="!error && !search" :title="t('accounts.modelAccess.noModels')" size="small" surface="none" />
<ZEmpty v-else-if="!error && !search" :title="groupCatalog ? t('groups.editor.emptyCatalog') : t('accounts.modelAccess.noModels')" size="small" surface="none" />
</template>
</div>
</template>
@@ -7,6 +7,9 @@ import { normalizeRgbaHexColor, ZButton, ZColorPicker, ZDialog, ZForm, ZFormItem
import { computed, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import HelpPopover from '@/components/HelpPopover.vue'
import AccountModelAccessField from '@/views/accounts/components/AccountModelAccessField.vue'
import { accountModelAccessError } from '@/views/accounts/utils/modelAccess'
import { ACCOUNT_GROUP_COLOR_PRESETS } from '../constants'
const props = defineProps<{
@@ -30,6 +33,15 @@ const rules = computed<FormRules<AccountGroupFormValue>>(() => ({
trigger: ['blur', 'change'],
message: t('groups.actions.enterGroupName'),
},
modelAccess: {
trigger: [],
validator: () => {
const error = accountModelAccessError(form.value.modelAccess)
return error
? new Error(error)
: true
},
},
color: {
validator: (_rule, value) => !!normalizeRgbaHexColor(value),
trigger: 'change',
@@ -43,6 +55,16 @@ async function requestSave() {
return
emit('save')
}
const toggleOptions = computed(() => [
{
value: 'enabled',
label: t('common.actions.enable'),
},
{
value: 'disabled',
label: t('common.actions.disable'),
},
])
const title = computed(() => props.group
? t('groups.actions.editGroup')
: t('groups.filters.createGroup'))
@@ -56,10 +78,10 @@ const description = computed(() => props.group
v-model="open"
:title="title"
:description="description"
width="36rem"
width="42rem"
:show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving"
>
<ZForm ref="formElement" :model="form" :rules="rules" scroll-to-error focus-on-error novalidate @submit="requestSave">
<ZForm ref="formElement" :model="form" :rules="rules" class="sm:grid-cols-[minmax(0,1fr)_fit-content(10rem)] sm:gap-x-6" scroll-to-error focus-on-error novalidate @submit="requestSave">
<ZFormItem prop="name" :show-message="false" :label="t('groups.editor.groupName')" required>
<ZInput
v-model="form.name"
@@ -71,44 +93,62 @@ const description = computed(() => props.group
<ZFormItem prop="color" :show-message="Boolean(form.color.trim())" :label="t('groups.editor.groupColor')" required>
<ZColorPicker
v-model="form.color"
class="sm:pl-0"
:aria-label="t('groups.editor.selectGroupColor')"
:presets="ACCOUNT_GROUP_COLOR_PRESETS"
:disabled="saving"
/>
</ZFormItem>
<div class="flex flex-wrap items-start gap-x-6 gap-y-3">
<ZFormItem :label="t('groups.editor.fastMode')" class="min-w-0">
<div class="col-span-full grid grid-cols-2 items-start gap-x-6 gap-y-4.5 sm:grid-cols-subgrid **:[[role=radio]]:px-3.5">
<div class="contents sm:flex sm:min-w-0 sm:flex-wrap sm:items-start sm:gap-x-6 sm:gap-y-4.5">
<ZFormItem :label="t('groups.editor.fastMode')" class="col-span-full sm:flex-auto">
<template #label-extra>
<HelpPopover :label="t('groups.editor.fastMode')" :content="t('groups.editor.fastModeHelp')" />
</template>
<ZSegmented
v-model="form.fastMode"
:aria-label="t('groups.editor.fastMode')"
:options="[
{ label: t('common.values.default'), value: 'default' },
{ label: t('common.actions.disable'), value: 'disabled' },
{ label: t('groups.editor.forceFast'), value: 'enabled' },
{ label: t('groups.editor.forceUltrafast'), value: 'ultrafast' },
]"
:disabled="saving"
/>
</ZFormItem>
<ZFormItem :label="t('groups.editor.imageGeneration')" class="sm:flex-auto">
<ZSegmented
:model-value="form.allowImageGeneration ? 'enabled' : 'disabled'"
:aria-label="t('groups.editor.imageGeneration')"
:options="toggleOptions"
:disabled="saving"
@update:model-value="form.allowImageGeneration = $event === 'enabled'"
/>
</ZFormItem>
</div>
<ZFormItem :label="t('groups.editor.subagents')">
<template #label-extra>
<HelpPopover :label="t('groups.editor.subagents')" :content="t('groups.editor.subagentsHelp')" />
</template>
<ZSegmented
v-model="form.fastMode"
class="w-64 max-w-full"
:aria-label="t('groups.editor.fastMode')"
:options="[
{ label: t('common.values.default'), value: 'default' },
{ label: t('common.status.enabled'), value: 'enabled' },
{ label: t('common.status.disabled'), value: 'disabled' },
]"
:model-value="form.allowSubagents ? 'enabled' : 'disabled'"
:aria-label="t('groups.editor.subagents')"
:options="toggleOptions"
:disabled="saving"
/>
</ZFormItem>
<ZFormItem :label="t('groups.editor.imageGeneration')" class="min-w-0">
<ZSegmented
:model-value="form.allowImageGeneration ? 'enabled' : 'disabled'"
class="w-40 max-w-full"
:aria-label="t('groups.editor.imageGeneration')"
:options="[
{ label: t('common.status.enabled'), value: 'enabled' },
{ label: t('common.status.disabled'), value: 'disabled' },
]"
:disabled="saving"
@update:model-value="form.allowImageGeneration = $event === 'enabled'"
@update:model-value="form.allowSubagents = $event === 'enabled'"
/>
</ZFormItem>
</div>
<ZFormItem :label="t('groups.editor.descriptionOptional')">
<AccountModelAccessField
class="col-span-full" :group-id="group?.id ?? null" :model-value="form.modelAccess" form-prop="modelAccess" :disabled="saving"
@update:model-value="value => { if (value) form.modelAccess = value }"
/>
<ZFormItem :label="t('groups.editor.description')" class="col-span-full">
<ZTextarea
v-model="form.description"
:aria-label="t('groups.editor.groupDescription')"
:rows="4"
:rows="2"
:placeholder="t('groups.editor.describePurposeOfThisGroup')"
:disabled="saving"
/>
@@ -1,4 +1,4 @@
import type { AccountGroup, ApiKey, FastMode } from '@/api'
import type { AccountGroup, AccountModelAccess, ApiKey, FastMode } from '@/api'
import { normalizeRgbaHexColor } from '@codex-proxy/ui'
import { computed, onMounted, ref, shallowRef, watch } from 'vue'
import {
@@ -23,6 +23,8 @@ import { DEFAULT_ACCOUNT_GROUP_COLOR } from '../constants'
export interface AccountGroupFormValue {
fastMode: FastMode
allowImageGeneration: boolean
allowSubagents: boolean
modelAccess: AccountModelAccess
name: string
description: string
color: string
@@ -124,6 +126,11 @@ export function useAccountGroups() {
color: group.color,
fastMode: group.fastMode,
allowImageGeneration: group.allowImageGeneration,
allowSubagents: group.allowSubagents,
modelAccess: {
...group.modelAccess,
models: [...group.modelAccess.models],
},
}
showFormModal.value = true
}
@@ -138,28 +145,16 @@ export function useAccountGroups() {
await savingAction.run(async () => {
const updating = Boolean(editingGroup.value)
const description = form.value.description.trim() || null
const fastMode = form.value.fastMode
const allowImageGeneration = form.value.allowImageGeneration
if (editingGroup.value) {
await updateAccountGroup({
id: editingGroup.value.id,
name,
description,
color,
fastMode,
allowImageGeneration,
})
}
else {
await createAccountGroup({
name,
description,
color,
fastMode,
allowImageGeneration,
})
const payload = {
...form.value,
name,
color,
description: form.value.description.trim() || null,
}
if (editingGroup.value)
await updateAccountGroup({ ...payload, id: editingGroup.value.id })
else
await createAccountGroup(payload)
showFormModal.value = false
await Promise.all([
query.execute(),
@@ -342,5 +337,7 @@ function emptyForm(): AccountGroupFormValue {
color: DEFAULT_ACCOUNT_GROUP_COLOR,
fastMode: 'default',
allowImageGeneration: true,
allowSubagents: true,
modelAccess: { mode: 'all', models: [] },
}
}
+15 -5
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import type { FastMode } from '@/api'
import { ZCard, ZCheckbox, ZConfirmDialog, ZPageHeader, ZPagination, ZTable } from '@codex-proxy/ui'
import { ImageOff, Zap, ZapOff } from '@lucide/vue'
@@ -13,6 +14,14 @@ import { accountGroupColumns } from './constants'
const { t } = useI18n({ useScope: 'global' })
function fastModeLabel(mode: FastMode) {
if (mode === 'disabled')
return t('groups.page.fastModeIsOff')
return mode === 'ultrafast'
? t('groups.editor.forceUltrafast')
: t('groups.editor.forceFast')
}
const {
groups,
loading,
@@ -103,16 +112,17 @@ const { allSelected, indeterminate, selectedRowKeys, toggleSelection, toggleAll
</strong>
<span
v-if="row.fastMode !== 'default'"
class="inline-flex size-4 shrink-0 items-center justify-center rounded-full"
:class="row.fastMode === 'enabled'
class="inline-flex h-4 shrink-0 items-center rounded-full px-0.5"
:class="row.fastMode !== 'disabled'
? 'bg-z-warning-container text-z-warning-on-container'
: 'bg-z-fill-tertiary text-z-text-tertiary'"
:title="row.fastMode === 'enabled' ? t('groups.page.fastModeIsOn') : t('groups.page.fastModeIsOff')"
:title="fastModeLabel(row.fastMode)"
role="img"
:aria-label="row.fastMode === 'enabled' ? t('groups.page.fastModeIsOn') : t('groups.page.fastModeIsOff')"
:aria-label="fastModeLabel(row.fastMode)"
>
<Zap v-if="row.fastMode === 'enabled'" class="size-3" stroke-width="2.2" aria-hidden="true" />
<Zap v-if="row.fastMode !== 'disabled'" class="size-3" stroke-width="2.2" aria-hidden="true" />
<ZapOff v-else class="size-3" stroke-width="2.2" aria-hidden="true" />
<Zap v-if="row.fastMode === 'ultrafast'" class="size-3" stroke-width="2.2" aria-hidden="true" />
</span>
<span
v-if="!row.allowImageGeneration"
@@ -0,0 +1,231 @@
<script setup lang="ts">
import type { ApiKeyLimitField } from '../composables/useApiKeyFormRules'
import type { AccountGroupRef, ApiKey, ApiKeyBatchChanges, ApiKeyPeerSharing } from '@/api'
import type { ProviderRequestProfileUpdates } from '@/api/modules/settings/profiles'
import { ZButton, ZConfirmDialog, ZDialog, ZForm, ZFormItem } from '@codex-proxy/ui'
import { KeyRound } from '@lucide/vue'
import { isEqual } from 'es-toolkit'
import { computed, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { batchUpdateApiKeys } from '@/api'
import { isValidInstallationSeed } from '@/api/modules/settings/profiles'
import AccountGroupCheckboxGrid from '@/components/AccountGroupCheckboxGrid.vue'
import ProviderRequestProfilesEditor from '@/components/client-profile/ProviderRequestProfilesEditor.vue'
import { useAsyncAction } from '@/composables/useAsyncAction'
import { notification as ZNotification } from '@/utils/notification'
import { PROVIDER_IDS } from '@/utils/providers'
import { apiKeyFormValue } from '../composables/useApiKeyEditor'
import { apiKeyLimitFields, useApiKeyLimitRules } from '../composables/useApiKeyFormRules'
import ApiKeyInstallationSeedField from './ApiKeyInstallationSeedField.vue'
import ApiKeyLimitFields from './ApiKeyLimitFields.vue'
import ApiKeyPeerSharingField from './ApiKeyPeerSharingField.vue'
const props = defineProps<{
keys: ApiKey[]
groups: AccountGroupRef[]
groupLoading: boolean
}>()
const emit = defineEmits<{ saved: [ids: string[]] }>()
const open = defineModel<boolean>({ required: true })
const { t } = useI18n({ useScope: 'global' })
const { loading, run } = useAsyncAction()
const formRef = useTemplateRef<InstanceType<typeof ZForm>>('formElement')
const rules = useApiKeyLimitRules()
const confirmAll = ref(false)
function emptyForm() {
return {
groupIds: undefined as string[] | undefined,
peerSharing: {} as Partial<ApiKeyPeerSharing>,
profiles: {} as ProviderRequestProfileUpdates,
installationSeed: '',
dailyLimitUsd: '',
weeklyLimitUsd: '',
maxConcurrency: '',
requestsPerMinute: '',
}
}
const form = ref(emptyForm())
const originals = computed(() => props.keys.map(apiKeyFormValue))
const initialProfiles = computed(() => {
const result: ProviderRequestProfileUpdates = {}
for (const id of PROVIDER_IDS) {
const first = originals.value[0]?.providerRequestProfileOverrides[id] ?? null
if (originals.value.every(row => isEqual(first, row.providerRequestProfileOverrides[id] ?? null)))
result[id] = first
}
return result
})
const hasExistingSeed = computed(() => originals.value.some(row => row.installationSeed))
const touchedLimits = ref(new Set<ApiKeyLimitField>())
function commonLimit(field: ApiKeyLimitField) {
const first = originals.value[0]?.[field]
return originals.value.every(row => row[field] === first)
? first
: undefined
}
const mixedLimits = computed(() => apiKeyLimitFields.filter(field => commonLimit(field) === undefined && !touchedLimits.value.has(field)))
const initialSharing = computed(() => {
const common: Partial<ApiKeyPeerSharing> = {}
const first = props.keys[0]?.peerSharing
if (first) {
for (const field of [
'enabled',
'sharePool',
'shareQuota',
'sharePlans',
] as const) {
if (props.keys.every(key => key.peerSharing[field] === first[field]))
common[field] = first[field]
}
}
return common
})
const sharingPatch = computed<Partial<ApiKeyPeerSharing>>(() => {
const patch = form.value.peerSharing
return patch.sharePool === false
? { ...patch, sharePlans: false }
: patch
})
const sharing = computed(() => ({
...initialSharing.value,
...sharingPatch.value,
}))
function updateSharing(field: keyof ApiKeyPeerSharing, enabled: boolean) {
const patch = form.value.peerSharing
if (initialSharing.value[field] === enabled)
delete patch[field]
else
patch[field] = enabled
if (field === 'enabled' && !enabled) {
form.value.peerSharing = patch.enabled === undefined
? {}
: { enabled: false }
}
}
function sameGroups(left: string[], right: string[]) {
const ids = new Set(left)
return ids.size === right.length && right.every(id => ids.has(id))
}
const initialGroups = computed(() => {
const first = props.keys[0]?.groups.map(group => group.id) ?? []
return props.keys.every(key => sameGroups(first, key.groups.map(group => group.id)))
? first
: undefined
})
function updateGroups(ids: string[]) {
form.value.groupIds = initialGroups.value && sameGroups(ids, initialGroups.value)
? undefined
: ids
}
const seedError = computed(() => isValidInstallationSeed(form.value.installationSeed.trim())
? ''
: t('settings.clientProfile.invalidInstallationSeed'))
const invalidScope = computed(() => props.keys.some(key =>
(form.value.peerSharing.enabled ?? key.peerSharing.enabled)
&& (form.value.groupIds?.length ?? key.groups.length) === 0))
const changes = computed<ApiKeyBatchChanges>(() => {
const draft = form.value
const patch: ApiKeyBatchChanges = {}
if (draft.groupIds !== undefined)
patch.groupIds = draft.groupIds
if (Object.keys(sharingPatch.value).length)
patch.peerSharing = sharingPatch.value
if (Object.keys(draft.profiles).length)
patch.providerRequestProfileOverrides = draft.profiles
if (draft.installationSeed.trim())
patch.installationSeed = draft.installationSeed.trim()
for (const field of touchedLimits.value) {
const value = draft[field].trim()
if (value === commonLimit(field))
continue
if (field === 'dailyLimitUsd' || field === 'weeklyLimitUsd')
patch[field] = value || '0'
else
patch[field] = Number(value)
}
return patch
})
const canSave = computed(() => props.keys.length > 0 && Object.keys(changes.value).length > 0 && !invalidScope.value && !seedError.value)
watch(open, (visible) => {
if (visible) {
form.value = emptyForm()
touchedLimits.value.clear()
for (const field of apiKeyLimitFields)
form.value[field] = commonLimit(field) ?? ''
}
})
async function save() {
if (!canSave.value || loading.value || !await formRef.value?.validate().catch(() => false))
return
if (form.value.groupIds?.length === 0) {
confirmAll.value = true
return
}
await applyChanges()
}
async function applyChanges() {
confirmAll.value = false
await run(async () => {
const ids = props.keys.map(key => key.id)
const result = await batchUpdateApiKeys({ ids, ...changes.value })
open.value = false
emit('saved', ids)
ZNotification.success({
message: t('keys.batch.updated', { count: result.updated }),
})
})
}
</script>
<template>
<ZDialog
v-model="open" :title="t('keys.batch.edit')" :description="t('keys.batch.description', { count: keys.length })" width="48rem" type="info"
:show-close="!loading" :close-on-click-modal="!loading" :close-on-press-escape="!loading"
>
<template #icon>
<KeyRound class="text-z-text" :size="20" aria-hidden="true" />
</template>
<ZForm ref="formElement" :model="form" :rules="rules" scroll-to-error focus-on-error novalidate class="grid gap-6" @submit="save">
<ZFormItem :label="t('groups.group')" :error="invalidScope ? t('keys.editor.peerGroupRequired') : undefined">
<AccountGroupCheckboxGrid
:model-value="form.groupIds ?? initialGroups ?? []" :groups="groups" :loading="groupLoading" :disabled="loading"
@update:model-value="updateGroups"
/>
<p v-if="form.groupIds?.length === 0" class="mt-2 mb-0 text-z-sm text-z-text-secondary">
{{ t('keys.scope.allAccounts.description') }}
</p>
</ZFormItem>
<ApiKeyPeerSharingField :sharing="sharing" :disabled="loading" @change="updateSharing" />
<div class="grid gap-4">
<ZFormItem :label="t('keys.editor.upstreamIdentity')">
<ProviderRequestProfilesEditor v-model:updates="form.profiles" :initial-profiles="initialProfiles" allow-inherit :active="open" :disabled="loading" />
</ZFormItem>
<ApiKeyInstallationSeedField v-model="form.installationSeed" :disabled="loading" :error="seedError" :placeholder="hasExistingSeed ? t('accounts.modelAccess.reserve') : t('settings.clientProfile.installationSeedPlaceholder')" />
</div>
<ApiKeyLimitFields
v-model:daily-limit-usd="form.dailyLimitUsd" v-model:weekly-limit-usd="form.weeklyLimitUsd"
v-model:max-concurrency="form.maxConcurrency" v-model:requests-per-minute="form.requestsPerMinute"
:mixed="mixedLimits" :disabled="loading" @edit="touchedLimits.add($event)"
/>
</ZForm>
<template #footer>
<ZButton :disabled="loading" @click="open = false">
{{ t('common.actions.cancel') }}
</ZButton>
<ZButton type="primary" :disabled="!canSave" :loading="loading" @click="save">
{{ t('common.actions.save') }}
</ZButton>
</template>
</ZDialog>
<ZConfirmDialog
v-model="confirmAll" :title="t('keys.scope.allAccounts.title')" :description="t('keys.scope.allAccounts.description')"
:confirm-text="t('keys.scope.allAccounts.confirm')" :loading="loading" @confirm="applyChanges"
/>
</template>
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { ZButton, ZInput } from '@codex-proxy/ui'
import { Plus, Search, Trash2 } from '@lucide/vue'
import { Pencil, Plus, Search, Trash2 } from '@lucide/vue'
import { useI18n } from 'vue-i18n'
@@ -13,6 +13,7 @@ defineProps<{
const emit = defineEmits<{
create: []
deleteSelected: []
editSelected: []
}>()
const { t } = useI18n({ useScope: 'global' })
@@ -35,6 +36,12 @@ const search = defineModel<string>('search', { required: true })
</div>
<div class="flex max-w-full shrink-0 flex-wrap items-center justify-end gap-2 md:ml-auto">
<ZButton v-if="selectedCount > 0" :disabled="batchDeleting" @click="emit('editSelected')">
<template #icon>
<Pencil class="size-4" />
</template>
{{ t('accounts.filters.editSelected', { count: selectedCount }) }}
</ZButton>
<ZButton
v-if="selectedCount > 0"
type="danger" variant="plain"
@@ -2,18 +2,20 @@
import type { ApiKeyFormValue } from '../composables/useApiKeyEditor'
import type { AccountGroupRef, ApiKeyPeerSharing } from '@/api'
import { ZButton, ZCheckbox, ZDialog, ZForm, ZFormItem, ZIconButton, ZInput, ZSwitch } from '@codex-proxy/ui'
import { Dices, DollarSign, KeyRound } from '@lucide/vue'
import { ZButton, ZDialog, ZForm, ZFormItem, ZInput } from '@codex-proxy/ui'
import { KeyRound } from '@lucide/vue'
import { computed, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
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'
import { generateRequestId as generateUuid } from '@/utils/operation'
import { useApiKeyFormRules } from '../composables/useApiKeyFormRules'
import ApiKeyInstallationSeedField from './ApiKeyInstallationSeedField.vue'
import ApiKeyLimitFields from './ApiKeyLimitFields.vue'
import ApiKeyPeerSharingField from './ApiKeyPeerSharingField.vue'
const props = defineProps<{
groups: AccountGroupRef[]
groupLoading: boolean
@@ -119,24 +121,7 @@ function updatePeerSharing(key: keyof ApiKeyPeerSharing, value: boolean) {
/>
</ZFormItem>
<ZFormItem :label="t('keys.editor.peerSharing')">
<template #label-extra>
<HelpPopover :label="t('keys.editor.peerSharing')" :content="t('keys.editor.peerSharingHelp')" />
</template>
<div class="flex flex-wrap items-center gap-x-5 gap-y-3">
<ZSwitch
:model-value="form.peerSharing.enabled"
:aria-label="t('keys.editor.peerSharing')"
:disabled="saving"
@update:model-value="updatePeerSharing('enabled', $event)"
/>
<template v-if="form.peerSharing.enabled">
<ZCheckbox :model-value="form.peerSharing.sharePool" :label="t('keys.editor.sharePool')" :disabled="saving" @update:model-value="updatePeerSharing('sharePool', $event)" />
<ZCheckbox :model-value="form.peerSharing.shareQuota" :label="t('keys.editor.shareQuota')" :disabled="saving" @update:model-value="updatePeerSharing('shareQuota', $event)" />
<ZCheckbox :model-value="form.peerSharing.sharePlans" :label="t('keys.editor.sharePlans')" :disabled="saving || !form.peerSharing.sharePool" @update:model-value="updatePeerSharing('sharePlans', $event)" />
</template>
</div>
</ZFormItem>
<ApiKeyPeerSharingField :sharing="form.peerSharing" :disabled="saving" @change="updatePeerSharing" />
<div class="grid gap-4">
<ZFormItem :label="t('keys.editor.upstreamIdentity')">
@@ -148,91 +133,17 @@ function updatePeerSharing(key: keyof ApiKeyPeerSharing, value: boolean) {
/>
</ZFormItem>
<ZFormItem :label="t('settings.clientProfile.installationSeed')" :error="installationSeedError">
<template #label-extra>
<HelpPopover :label="t('settings.clientProfile.installationSeed')" :content="t('settings.clientProfile.installationSeedHelp')" />
</template>
<template #extra>
<ZIconButton
variant="link" size="small" class="-my-2"
:aria-label="t('settings.clientProfile.generateInstallationSeed')"
:disabled="saving"
@click="updateForm('installationSeed', generateUuid())"
>
<Dices class="size-4" aria-hidden="true" />
</ZIconButton>
</template>
<ZInput
:model-value="form.installationSeed"
:aria-label="t('settings.clientProfile.installationSeed')"
:aria-invalid="!!installationSeedError"
:placeholder="t('settings.clientProfile.installationSeedPlaceholder')"
:disabled="saving"
:spellcheck="false"
autocomplete="off"
class="font-mono"
@update:model-value="updateForm('installationSeed', $event)"
/>
</ZFormItem>
<ApiKeyInstallationSeedField
v-model="form.installationSeed" :error="installationSeedError" :disabled="saving"
:placeholder="t('settings.clientProfile.installationSeedPlaceholder')"
/>
</div>
<div class="grid gap-6 sm:grid-cols-2">
<ZFormItem prop="dailyLimitUsd" :label="t('keys.editor.dailyLimit')">
<ZInput
:model-value="form.dailyLimitUsd" type="number"
min="0"
step="any"
:aria-label="t('keys.editor.dailyLimitUsd')"
:placeholder="t('common.values.unlimited')"
:disabled="saving"
@update:model-value="updateForm('dailyLimitUsd', $event)"
>
<template #prefix>
<DollarSign class="size-4" aria-hidden="true" />
</template>
</ZInput>
</ZFormItem>
<ZFormItem prop="weeklyLimitUsd" :label="t('keys.editor.weeklyLimit')">
<ZInput
:model-value="form.weeklyLimitUsd" type="number"
min="0"
step="any"
:aria-label="t('keys.editor.weeklyLimitUsd')"
:placeholder="t('common.values.unlimited')"
:disabled="saving"
@update:model-value="updateForm('weeklyLimitUsd', $event)"
>
<template #prefix>
<DollarSign class="size-4" aria-hidden="true" />
</template>
</ZInput>
</ZFormItem>
</div>
<div class="grid gap-6 sm:grid-cols-2">
<ZFormItem prop="maxConcurrency" :label="t('keys.editor.maximumConcurrency')">
<ZInput
:model-value="form.maxConcurrency" type="number"
:aria-label="t('keys.editor.maximumConcurrency')"
min="0"
step="1"
:placeholder="t('common.values.unlimited')"
:disabled="saving"
@update:model-value="updateForm('maxConcurrency', $event)"
/>
</ZFormItem>
<ZFormItem prop="requestsPerMinute" :label="t('keys.editor.requestsPerMinuteRpm')">
<ZInput
:model-value="form.requestsPerMinute" type="number"
:aria-label="t('keys.editor.requestsPerMinute')"
min="0"
step="1"
:placeholder="t('common.values.unlimited')"
:disabled="saving"
@update:model-value="updateForm('requestsPerMinute', $event)"
/>
</ZFormItem>
</div>
<ApiKeyLimitFields
v-model:daily-limit-usd="form.dailyLimitUsd" v-model:weekly-limit-usd="form.weeklyLimitUsd"
v-model:max-concurrency="form.maxConcurrency" v-model:requests-per-minute="form.requestsPerMinute"
:disabled="saving"
/>
</ZForm>
<template #footer>
@@ -8,9 +8,9 @@ defineProps<{
<template>
<div class="grid min-w-0 gap-1">
<span class="truncate text-z text-z-text" :title="apiKey.name">
<strong class="truncate text-z text-z-text" :title="apiKey.name">
{{ apiKey.name }}
</span>
</strong>
<span v-if="apiKey.label" class="truncate text-z-xs font-emphasis text-z-text-quaternary" :title="apiKey.label">
{{ apiKey.label }}
</span>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { ZFormItem, ZIconButton, ZInput } from '@codex-proxy/ui'
import { Dices } from '@lucide/vue'
import { useI18n } from 'vue-i18n'
import HelpPopover from '@/components/HelpPopover.vue'
import { generateRequestId as generateUuid } from '@/utils/operation'
defineProps<{ disabled: boolean, placeholder: string, error: string }>()
const seed = defineModel<string>({ required: true })
const { t } = useI18n({ useScope: 'global' })
</script>
<template>
<ZFormItem :label="t('settings.clientProfile.installationSeed')" :error="error">
<template #label-extra>
<HelpPopover :label="t('settings.clientProfile.installationSeed')" :content="t('settings.clientProfile.installationSeedHelp')" />
</template>
<template #extra>
<ZIconButton
variant="link" size="small" class="-my-2"
:aria-label="t('settings.clientProfile.generateInstallationSeed')"
:disabled="disabled"
@click="seed = generateUuid()"
>
<Dices class="size-4" aria-hidden="true" />
</ZIconButton>
</template>
<ZInput
v-model="seed"
:aria-label="t('settings.clientProfile.installationSeed')"
:aria-invalid="!!error"
:placeholder="placeholder"
:disabled="disabled"
:spellcheck="false"
autocomplete="off"
class="font-mono"
/>
</ZFormItem>
</template>
@@ -0,0 +1,73 @@
<script setup lang="ts">
import type { ApiKeyLimitField } from '../composables/useApiKeyFormRules'
import { ZButton, ZFormItem, ZInput } from '@codex-proxy/ui'
import { DollarSign } from '@lucide/vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{ disabled: boolean, mixed?: ApiKeyLimitField[] }>()
const emit = defineEmits<{ edit: [field: ApiKeyLimitField] }>()
const dailyLimitUsd = defineModel<string>('dailyLimitUsd', { required: true })
const weeklyLimitUsd = defineModel<string>('weeklyLimitUsd', { required: true })
const maxConcurrency = defineModel<string>('maxConcurrency', { required: true })
const requestsPerMinute = defineModel<string>('requestsPerMinute', { required: true })
const { t } = useI18n({ useScope: 'global' })
const fields = computed(() => [
{
key: 'dailyLimitUsd',
model: dailyLimitUsd,
label: t('keys.editor.dailyLimit'),
accessible: t('keys.editor.dailyLimitUsd'),
money: true,
},
{
key: 'weeklyLimitUsd',
model: weeklyLimitUsd,
label: t('keys.editor.weeklyLimit'),
accessible: t('keys.editor.weeklyLimitUsd'),
money: true,
},
{
key: 'maxConcurrency',
model: maxConcurrency,
label: t('keys.editor.maximumConcurrency'),
accessible: t('keys.editor.maximumConcurrency'),
money: false,
},
{
key: 'requestsPerMinute',
model: requestsPerMinute,
label: t('keys.editor.requestsPerMinuteRpm'),
accessible: t('keys.editor.requestsPerMinute'),
money: false,
},
] as const)
function update(field: typeof fields.value[number], value: string) {
field.model.value = value
emit('edit', field.key)
}
</script>
<template>
<div class="grid gap-6 sm:grid-cols-2">
<ZFormItem v-for="field in fields" :key="field.key" :prop="field.key" :label="field.label">
<template v-if="mixed?.includes(field.key)" #label-extra>
<span class="text-z-xs text-z-text-secondary">{{ t('keys.batch.mixed') }}</span>
</template>
<template v-if="mixed?.includes(field.key)" #extra>
<ZButton variant="link" size="small" :disabled="disabled" @click="update(field, '')">
{{ t('keys.batch.clearLimit') }}
</ZButton>
</template>
<ZInput
:model-value="field.model.value" type="number" min="0" :step="field.money ? 'any' : '1'"
:aria-label="field.accessible" :placeholder="t('common.values.unlimited')" :disabled="disabled"
@update:model-value="update(field, $event)"
>
<template v-if="field.money" #prefix>
<DollarSign class="size-4" aria-hidden="true" />
</template>
</ZInput>
</ZFormItem>
</div>
</template>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import type { ApiKeyPeerSharing } from '@/api'
import { ZCheckbox, ZFormItem, ZSwitch } from '@codex-proxy/ui'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import HelpPopover from '@/components/HelpPopover.vue'
defineProps<{ sharing: Partial<ApiKeyPeerSharing>, disabled: boolean }>()
const emit = defineEmits<{ change: [field: keyof ApiKeyPeerSharing, value: boolean] }>()
const { t } = useI18n({ useScope: 'global' })
const permissions = computed(() => ({
sharePool: t('keys.editor.sharePool'),
shareQuota: t('keys.editor.shareQuota'),
sharePlans: t('keys.editor.sharePlans'),
}))
</script>
<template>
<ZFormItem :label="t('keys.editor.peerSharing')">
<template #label-extra>
<HelpPopover :label="t('keys.editor.peerSharing')" :content="t('keys.editor.peerSharingHelp')" />
</template>
<div class="flex flex-wrap items-center gap-x-5 gap-y-3">
<ZSwitch
:model-value="sharing.enabled === true" :aria-label="t('keys.editor.peerSharing')" :disabled="disabled"
@update:model-value="emit('change', 'enabled', $event)"
/>
<span v-if="sharing.enabled === undefined" class="text-z-sm text-z-text-secondary">{{ t('keys.batch.partiallyEnabled') }}</span>
<template v-if="sharing.enabled">
<ZCheckbox
v-for="(label, field) in permissions" :key="field"
:model-value="sharing[field] === true" :indeterminate="sharing[field] === undefined"
:label="label" :disabled="disabled || (field === 'sharePlans' && !sharing.sharePool)"
@update:model-value="emit('change', field, $event)"
/>
</template>
</div>
</ZFormItem>
</template>
@@ -40,29 +40,7 @@ export function useApiKeyEditor(options: {
function openEdit(key: ApiKey) {
editingKey.value = key
const profiles = cloneDeep(key.providerRequestProfileOverrides)
const openai = profiles.openai
const identity = (openai?.inherit as Record<string, unknown> | undefined) ?? openai
const installationSeed = typeof identity?.installationSeed === 'string'
? identity.installationSeed
: ''
if (openai?.inherit)
delete profiles.openai
else if (openai)
delete openai.installationSeed
form.value = {
peerSharing: { ...key.peerSharing },
providerRequestProfileOverrides: profiles,
installationSeed,
customKey: '',
name: key.name,
label: key.label ?? '',
groupIds: key.groups.map(group => group.id),
maxConcurrency: limitInputValue(key.maxConcurrency),
requestsPerMinute: limitInputValue(key.requestsPerMinute),
dailyLimitUsd: limitInputValue(key.dailyLimitUsd),
weeklyLimitUsd: limitInputValue(key.weeklyLimitUsd),
}
form.value = apiKeyFormValue(key)
showFormModal.value = true
}
@@ -203,3 +181,29 @@ function limitInputValue(limit: string | number) {
? ''
: String(limit)
}
export function apiKeyFormValue(key: ApiKey): ApiKeyFormValue {
const profiles = cloneDeep(key.providerRequestProfileOverrides)
const openai = profiles.openai
const identity = (openai?.inherit as Record<string, unknown> | undefined) ?? openai
const installationSeed = typeof identity?.installationSeed === 'string'
? identity.installationSeed
: ''
if (openai?.inherit)
delete profiles.openai
else if (openai)
delete openai.installationSeed
return {
peerSharing: { ...key.peerSharing },
providerRequestProfileOverrides: profiles,
installationSeed,
customKey: '',
name: key.name,
label: key.label ?? '',
groupIds: key.groups.map(group => group.id),
maxConcurrency: limitInputValue(key.maxConcurrency),
requestsPerMinute: limitInputValue(key.requestsPerMinute),
dailyLimitUsd: limitInputValue(key.dailyLimitUsd),
weeklyLimitUsd: limitInputValue(key.weeklyLimitUsd),
}
}
@@ -3,7 +3,15 @@ import type { ApiKeyFormValue } from './useApiKeyEditor'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
export function useApiKeyFormRules(form: () => ApiKeyFormValue) {
export const apiKeyLimitFields = [
'dailyLimitUsd',
'weeklyLimitUsd',
'maxConcurrency',
'requestsPerMinute',
] as const
export type ApiKeyLimitField = typeof apiKeyLimitFields[number]
export function useApiKeyLimitRules() {
const { t } = useI18n({ useScope: 'global' })
function amountRule(label: string): FormRule {
@@ -28,6 +36,17 @@ export function useApiKeyFormRules(form: () => ApiKeyFormValue) {
}
}
return computed(() => ({
dailyLimitUsd: amountRule(t('keys.editor.dailyLimit')),
weeklyLimitUsd: amountRule(t('keys.editor.weeklyLimit')),
maxConcurrency: integerRule(t('keys.editor.maximumConcurrency')),
requestsPerMinute: integerRule(t('keys.editor.requestsPerMinute')),
}))
}
export function useApiKeyFormRules(form: () => ApiKeyFormValue) {
const { t } = useI18n({ useScope: 'global' })
const limitRules = useApiKeyLimitRules()
return computed<FormRules<ApiKeyFormValue>>(() => ({
groupIds: {
type: 'array',
@@ -46,9 +65,6 @@ export function useApiKeyFormRules(form: () => ApiKeyFormValue) {
pattern: /^[\x21-\x7E]+$/,
message: t('keys.editor.invalidKey'),
},
dailyLimitUsd: amountRule(t('keys.editor.dailyLimit')),
weeklyLimitUsd: amountRule(t('keys.editor.weeklyLimit')),
maxConcurrency: integerRule(t('keys.editor.maximumConcurrency')),
requestsPerMinute: integerRule(t('keys.editor.requestsPerMinute')),
...limitRules.value,
}))
}

Some files were not shown because too many files have changed in this diff Show More