From 6cfe7ce2fcd5e9066ca100b4ab3e08842b1bffe8 Mon Sep 17 00:00:00 2001 From: Zyy <0x@ainz.cc> Date: Fri, 20 Nov 2026 14:39:30 +0800 Subject: [PATCH] feat(admin): add account group policies and bulk API key editing (#751) Co-authored-by: Codex --- backend/crates/gateway-admin/src/bootstrap.rs | 3 +- .../gateway-admin/src/model/account_groups.rs | 10 +- .../crates/gateway-admin/src/model/audit.rs | 2 + .../gateway-admin/src/model/client_keys.rs | 60 +++++ .../gateway-admin/src/ports/provider.rs | 13 + .../crates/gateway-admin/src/ports/store.rs | 23 +- .../src/use_case/account_groups.rs | 18 +- .../gateway-admin/src/use_case/client_keys.rs | 133 ++++++++-- .../src/use_case/plugin_resources.rs | 2 + .../tests/use_case/account_groups.rs | 6 + .../tests/use_case/client_keys.rs | 37 +++ .../gateway-admin/tests/use_case/mod.rs | 9 + .../gateway-api/src/admin/account_groups.rs | 52 +++- .../src/admin/accounts/presenter.rs | 8 +- .../gateway-api/src/admin/accounts/wire.rs | 10 + .../gateway-api/src/admin/client_keys.rs | 106 +++++++- .../crates/gateway-api/src/openai/models.rs | 7 +- .../src/openai/responses/request.rs | 1 + .../gateway-api/tests/admin/account_groups.rs | 112 +++++++++ .../gateway-api/tests/admin/client_keys.rs | 57 +++++ backend/crates/gateway-api/tests/admin/mod.rs | 25 ++ .../{image_policy.rs => group_permissions.rs} | 76 ++++-- .../crates/gateway-api/tests/openai/mod.rs | 17 +- .../crates/gateway-api/tests/openai/models.rs | 76 +++--- .../gateway-core/src/account/fast_mode.rs | 8 +- .../gateway-core/src/account/model_access.rs | 6 + .../crates/gateway-core/src/account/scope.rs | 83 ++++++- .../src/engine/execution/failure.rs | 5 + .../src/engine/execution/service.rs | 5 +- .../src/engine/group_permissions.rs | 36 +++ .../src/engine/image_generation.rs | 20 -- backend/crates/gateway-core/src/engine/mod.rs | 16 +- backend/crates/gateway-core/src/error/mod.rs | 42 +++- backend/crates/gateway-core/src/policy/mod.rs | 2 +- .../crates/gateway-core/src/routing/mod.rs | 7 - .../gateway-core/src/routing/snapshot.rs | 108 ++++++-- backend/crates/gateway-core/src/validation.rs | 9 + .../gateway-core/tests/engine/coordinator.rs | 7 +- .../tests/engine/middleware/mod.rs | 55 ++++- .../gateway-core/tests/routing/snapshot.rs | 178 +++++++++++++- .../runtime/src/callback/resources.rs | 2 + .../runtime/tests/generation/maintenance.rs | 2 + .../tests/generation/policy/compatibility.rs | 6 +- .../tests/generation/upstream_adapter.rs | 9 +- .../runtime/tests/support/environment.rs | 2 + .../gateway-plugin/sdk/docs/capabilities.md | 2 +- .../sdk/docs/upstream-adapters.md | 2 +- .../gateway-protocol/src/openai/codex.rs | 34 ++- .../gateway-protocol/tests/openai/codex.rs | 35 +++ .../src/postgres/account_groups.rs | 48 +++- .../gateway-store/src/postgres/client_keys.rs | 191 ++++++++++++++- .../src/postgres/control_plane.rs | 25 ++ .../gateway-store/src/postgres/snapshot.rs | 41 +++- .../tests/postgres/account_groups.rs | 72 ++++-- .../tests/postgres/client_keys.rs | 220 +++++++++++++++++ .../crates/providers/openai/src/admin/mod.rs | 14 ++ .../openai/src/credential/catalog/mod.rs | 37 ++- .../openai/src/credential/eligibility.rs | 9 +- .../openai/src/provider/execution.rs | 16 ++ .../providers/openai/src/provider/mod.rs | 67 +++-- .../openai/src/transport/profile/identity.rs | 44 ++++ .../src/transport/protocol/responses.rs | 48 ++-- .../openai/tests/provider/contract/mod.rs | 231 +++++++++++------- .../provider/contract/search_model_access.rs | 75 ++++++ .../tests/transport/profile/identity.rs | 68 ++++++ .../providers/xai/src/credential/catalog.rs | 56 +++-- .../crates/providers/xai/src/provider/mod.rs | 4 +- .../providers/xai/tests/credential/catalog.rs | 18 +- .../xai/tests/provider/contract/mod.rs | 4 + backend/migrations/.frozen-sha256 | 1 + .../0045_account_group_policies.sql | 21 ++ docs/api.md | 47 ++-- docs/architecture.md | 6 +- frontend/src/api/modules/groups.ts | 18 +- frontend/src/api/modules/keys.ts | 17 +- .../client-profile/ClientProfileEditor.vue | 24 +- .../ProviderRequestProfilesEditor.vue | 52 ++-- .../client-profile/XaiClientProfileEditor.vue | 27 +- frontend/src/i18n/locales/en/common.json | 3 +- frontend/src/i18n/locales/en/groups.json | 13 +- frontend/src/i18n/locales/en/keys.json | 8 + frontend/src/i18n/locales/zh-Hans/common.json | 3 +- frontend/src/i18n/locales/zh-Hans/groups.json | 15 +- frontend/src/i18n/locales/zh-Hans/keys.json | 8 + frontend/src/i18n/locales/zh-Hant/common.json | 3 +- frontend/src/i18n/locales/zh-Hant/groups.json | 15 +- frontend/src/i18n/locales/zh-Hant/keys.json | 8 + .../components/AccountModelAccessField.vue | 56 +++-- .../components/AccountGroupFormModal.vue | 94 +++++-- .../groups/composables/useAccountGroups.ts | 41 ++-- frontend/src/views/groups/index.vue | 20 +- .../keys/components/ApiKeyBatchEditModal.vue | 231 ++++++++++++++++++ .../views/keys/components/ApiKeyFilters.vue | 9 +- .../views/keys/components/ApiKeyFormModal.vue | 121 ++------- .../keys/components/ApiKeyIdentityCell.vue | 4 +- .../ApiKeyInstallationSeedField.vue | 39 +++ .../keys/components/ApiKeyLimitFields.vue | 73 ++++++ .../components/ApiKeyPeerSharingField.vue | 39 +++ .../views/keys/composables/useApiKeyEditor.ts | 50 ++-- .../keys/composables/useApiKeyFormRules.ts | 26 +- frontend/src/views/keys/index.vue | 50 +++- frontend/src/views/proxies/index.vue | 2 +- 102 files changed, 3273 insertions(+), 703 deletions(-) rename backend/crates/gateway-api/tests/openai/{image_policy.rs => group_permissions.rs} (58%) create mode 100644 backend/crates/gateway-core/src/engine/group_permissions.rs delete mode 100644 backend/crates/gateway-core/src/engine/image_generation.rs create mode 100644 backend/migrations/0045_account_group_policies.sql create mode 100644 frontend/src/views/keys/components/ApiKeyBatchEditModal.vue create mode 100644 frontend/src/views/keys/components/ApiKeyInstallationSeedField.vue create mode 100644 frontend/src/views/keys/components/ApiKeyLimitFields.vue create mode 100644 frontend/src/views/keys/components/ApiKeyPeerSharingField.vue diff --git a/backend/crates/gateway-admin/src/bootstrap.rs b/backend/crates/gateway-admin/src/bootstrap.rs index 541b7c060..b977eb9f7 100644 --- a/backend/crates/gateway-admin/src/bootstrap.rs +++ b/backend/crates/gateway-admin/src/bootstrap.rs @@ -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(), diff --git a/backend/crates/gateway-admin/src/model/account_groups.rs b/backend/crates/gateway-admin/src/model/account_groups.rs index d1d63894f..fa64bfe65 100644 --- a/backend/crates/gateway-admin/src/model/account_groups.rs +++ b/backend/crates/gateway-admin/src/model/account_groups.rs @@ -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, @@ -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, + pub allow_subagents: Option, + pub model_access: Option, pub fast_mode: Option, pub id: AccountGroupId, pub name: String, diff --git a/backend/crates/gateway-admin/src/model/audit.rs b/backend/crates/gateway-admin/src/model/audit.rs index 2aa3d0094..ea47372c4 100644 --- a/backend/crates/gateway-admin/src/model/audit.rs +++ b/backend/crates/gateway-admin/src/model/audit.rs @@ -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 } => { diff --git a/backend/crates/gateway-admin/src/model/client_keys.rs b/backend/crates/gateway-admin/src/model/client_keys.rs index c984aff33..67c0a6872 100644 --- a/backend/crates/gateway-admin/src/model/client_keys.rs +++ b/backend/crates/gateway-admin/src/model/client_keys.rs @@ -218,6 +218,66 @@ pub struct UpdateClientKey { pub weekly_limit_usd: Option, } +/// 批量编辑只覆盖明确选择的互联选项 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ClientPeerSharingPatch { + pub enabled: Option, + pub share_pool: Option, + pub share_quota: Option, + pub share_plans: Option, +} + +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, + pub group_ids: Option>, + pub enabled: Option, + pub max_concurrency: Option, + pub requests_per_minute: Option, + pub daily_limit_usd: Option, + pub weekly_limit_usd: Option, + pub peer_sharing: ClientPeerSharingPatch, + pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates, + pub installation_seed: Option, +} + +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 { diff --git a/backend/crates/gateway-admin/src/ports/provider.rs b/backend/crates/gateway-admin/src/ports/provider.rs index 126decde4..ea107753b 100644 --- a/backend/crates/gateway-admin/src/ports/provider.rs +++ b/backend/crates/gateway-admin/src/ports/provider.rs @@ -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>, + installation_seed: Option, + ) -> Result, 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) diff --git a/backend/crates/gateway-admin/src/ports/store.rs b/backend/crates/gateway-admin/src/ports/store.rs index 887338762..dfc43227d 100644 --- a/backend/crates/gateway-admin/src/ports/store.rs +++ b/backend/crates/gateway-admin/src/ports/store.rs @@ -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 = Result; +/// 在持有密钥行锁时用 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; + async fn set_client_key_enabled( &self, command: SetClientKeyEnabled, diff --git a/backend/crates/gateway-admin/src/use_case/account_groups.rs b/backend/crates/gateway-admin/src/use_case/account_groups.rs index cdad47a2d..469415cf2 100644 --- a/backend/crates/gateway-admin/src/use_case/account_groups.rs +++ b/backend/crates/gateway-admin/src/use_case/account_groups.rs @@ -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, AdminError>; async fn list(&self, query: AccountGroupListQuery) -> Result; async fn list_options( &self, @@ -64,6 +65,7 @@ pub(crate) struct DefaultAccountGroupService { store: Arc, runtime: Arc, snapshot: Arc, + published_snapshot: RuntimeSnapshotHandle, } impl DefaultAccountGroupService { @@ -73,12 +75,14 @@ impl DefaultAccountGroupService { store: Arc, runtime: Arc, snapshot: Arc, + 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, 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 { 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, diff --git a/backend/crates/gateway-admin/src/use_case/client_keys.rs b/backend/crates/gateway-admin/src/use_case/client_keys.rs index b4ba55844..10773e405 100644 --- a/backend/crates/gateway-admin/src/use_case/client_keys.rs +++ b/backend/crates/gateway-admin/src/use_case/client_keys.rs @@ -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; + async fn batch_update( + &self, + context: &MutationContext, + command: BatchUpdateClientKeys, + ) -> Result; 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 { + let mut kinds = command + .request_profile_override_updates + .keys() + .cloned() + .collect::>(); + 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 { + if command.ids.is_empty() + || command.ids.len() > 1000 + || command + .ids + .iter() + .collect::>() + .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 { diff --git a/backend/crates/gateway-admin/src/use_case/plugin_resources.rs b/backend/crates/gateway-admin/src/use_case/plugin_resources.rs index 753194040..99be94233 100644 --- a/backend/crates/gateway-admin/src/use_case/plugin_resources.rs +++ b/backend/crates/gateway-admin/src/use_case/plugin_resources.rs @@ -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, diff --git a/backend/crates/gateway-admin/tests/use_case/account_groups.rs b/backend/crates/gateway-admin/tests/use_case/account_groups.rs index 087894176..f795d5996 100644 --- a/backend/crates/gateway-admin/tests/use_case/account_groups.rs +++ b/backend/crates/gateway-admin/tests/use_case/account_groups.rs @@ -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(), diff --git a/backend/crates/gateway-admin/tests/use_case/client_keys.rs b/backend/crates/gateway-admin/tests/use_case/client_keys.rs index 6b7c18011..ed56aac8f 100644 --- a/backend/crates/gateway-admin/tests/use_case/client_keys.rs +++ b/backend/crates/gateway-admin/tests/use_case/client_keys.rs @@ -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 { + 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}; diff --git a/backend/crates/gateway-admin/tests/use_case/mod.rs b/backend/crates/gateway-admin/tests/use_case/mod.rs index cd72811b2..2d3a93d4b 100644 --- a/backend/crates/gateway-admin/tests/use_case/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/mod.rs @@ -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 { + Err(unavailable("client key batch update")) + } + async fn client_key_budget_window( &self, _: &gateway_core::policy::ClientApiKeyId, diff --git a/backend/crates/gateway-api/src/admin/account_groups.rs b/backend/crates/gateway-api/src/admin/account_groups.rs index 8562f9661..22485a5fd 100644 --- a/backend/crates/gateway-api/src/admin/account_groups.rs +++ b/backend/crates/gateway-api/src/admin/account_groups.rs @@ -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, + allow_subagents: Option, + model_access: Option, fast_mode: Option, 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::)) + .route("/api/admin/account-groups/models", get(models::)) .route("/api/admin/account-groups/options", get(list_options::)) .route("/api/admin/account-groups/create", post(create::)) .route("/api/admin/account-groups/update", post(update::)) @@ -332,6 +346,32 @@ where )) } +#[derive(Serialize)] +struct AccountGroupModelsData { + models: Vec, +} + +async fn models( + _auth: AdminAuth, + State(state): State, + AdminQuery(query): AdminQuery, +) -> Result +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( _auth: AdminAuth, State(state): State, @@ -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, diff --git a/backend/crates/gateway-api/src/admin/accounts/presenter.rs b/backend/crates/gateway-api/src/admin/accounts/presenter.rs index 3027d7bfa..c149e46e1 100644 --- a/backend/crates/gateway-api/src/admin/accounts/presenter.rs +++ b/backend/crates/gateway-api/src/admin/accounts/presenter.rs @@ -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 diff --git a/backend/crates/gateway-api/src/admin/accounts/wire.rs b/backend/crates/gateway-api/src/admin/accounts/wire.rs index 9d6e17092..9fd01690c 100644 --- a/backend/crates/gateway-api/src/admin/accounts/wire.rs +++ b/backend/crates/gateway-api/src/admin/accounts/wire.rs @@ -743,6 +743,16 @@ pub struct AccountModelView { pub label: String, } +impl From 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 { diff --git a/backend/crates/gateway-api/src/admin/client_keys.rs b/backend/crates/gateway-api/src/admin/client_keys.rs index 3ad31b26e..22f0fd3c6 100644 --- a/backend/crates/gateway-api/src/admin/client_keys.rs +++ b/backend/crates/gateway-api/src/admin/client_keys.rs @@ -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::)) + .route( + "/api/admin/client-keys/batch-update", + post(batch_update_client_keys::), + ) .route( "/api/admin/client-keys/create", post(create_client_key::), @@ -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, + group_ids: Option>, + enabled: Option, + max_concurrency: Option, + requests_per_minute: Option, + daily_limit_usd: Option, + weekly_limit_usd: Option, + peer_sharing: Option, + #[serde(default)] + provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates, + installation_seed: Option, +} + +impl BatchUpdateClientKeysRequest { + /// 复用单把密钥的字段校验,缺省和显式零值分别保留 + pub fn into_command(self) -> Result { + 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::>()?, + 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( + auth: AdminAuth, + State(state): State, + AdminJson(request): AdminJson, +) -> Result +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( auth: AdminAuth, State(state): State, @@ -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" => "排序字段不受支持", diff --git a/backend/crates/gateway-api/src/openai/models.rs b/backend/crates/gateway-api/src/openai/models.rs index b35d4dde7..aa7e8aa83 100644 --- a/backend/crates/gateway-api/src/openai/models.rs +++ b/backend/crates/gateway-api/src/openai/models.rs @@ -115,9 +115,14 @@ async fn models_response( } }) .collect::, ()>>(); - 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 表示改写后的正文 diff --git a/backend/crates/gateway-api/src/openai/responses/request.rs b/backend/crates/gateway-api/src/openai/responses/request.rs index c61f4a7c8..35a8f8adc 100644 --- a/backend/crates/gateway-api/src/openai/responses/request.rs +++ b/backend/crates/gateway-api/src/openai/responses/request.rs @@ -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(), diff --git a/backend/crates/gateway-api/tests/admin/account_groups.rs b/backend/crates/gateway-api/tests/admin/account_groups.rs index f3c1ca819..d6d05fb23 100644 --- a/backend/crates/gateway-api/tests/admin/account_groups.rs +++ b/backend/crates/gateway-api/tests/admin/account_groups.rs @@ -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 + ); +} diff --git a/backend/crates/gateway-api/tests/admin/client_keys.rs b/backend/crates/gateway-api/tests/admin/client_keys.rs index ec644030b..7c964889d 100644 --- a/backend/crates/gateway-api/tests/admin/client_keys.rs +++ b/backend/crates/gateway-api/tests/admin/client_keys.rs @@ -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::(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; diff --git a/backend/crates/gateway-api/tests/admin/mod.rs b/backend/crates/gateway-api/tests/admin/mod.rs index 0eacd0fbf..2b9f6a526 100644 --- a/backend/crates/gateway-api/tests/admin/mod.rs +++ b/backend/crates/gateway-api/tests/admin/mod.rs @@ -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 { + Err(AdminStoreError::new( + AdminStoreErrorKind::Unavailable, + "client key", + "unused batch update", + )) + } + async fn client_key_budget_window( &self, _: &gateway_core::policy::ClientApiKeyId, diff --git a/backend/crates/gateway-api/tests/openai/image_policy.rs b/backend/crates/gateway-api/tests/openai/group_permissions.rs similarity index 58% rename from backend/crates/gateway-api/tests/openai/image_policy.rs rename to backend/crates/gateway-api/tests/openai/group_permissions.rs index 059c7a704..97459f2a9 100644 --- a/backend/crates/gateway-api/tests/openai/image_policy.rs +++ b/backend/crates/gateway-api/tests/openai/group_permissions.rs @@ -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 { +pub(super) fn execution() -> Arc { 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"); + } +} diff --git a/backend/crates/gateway-api/tests/openai/mod.rs b/backend/crates/gateway-api/tests/openai/mod.rs index 2bbb171c7..f3967198a 100644 --- a/backend/crates/gateway-api/tests/openai/mod.rs +++ b/backend/crates/gateway-api/tests/openai/mod.rs @@ -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(), diff --git a/backend/crates/gateway-api/tests/openai/models.rs b/backend/crates/gateway-api/tests/openai/models.rs index 718c14afa..c03160627 100644 --- a/backend/crates/gateway-api/tests/openai/models.rs +++ b/backend/crates/gateway-api/tests/openai/models.rs @@ -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] diff --git a/backend/crates/gateway-core/src/account/fast_mode.rs b/backend/crates/gateway-core/src/account/fast_mode.rs index de39bcf72..f7ebb8535 100644 --- a/backend/crates/gateway-core/src/account/fast_mode.rs +++ b/backend/crates/gateway-core/src/account/fast_mode.rs @@ -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, } } diff --git a/backend/crates/gateway-core/src/account/model_access.rs b/backend/crates/gateway-core/src/account/model_access.rs index 5a441e6c6..9ad5e430b 100644 --- a/backend/crates/gateway-core/src/account/model_access.rs +++ b/backend/crates/gateway-core/src/account/model_access.rs @@ -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)] diff --git a/backend/crates/gateway-core/src/account/scope.rs b/backend/crates/gateway-core/src/account/scope.rs index 8acae913f..2b54f589b 100644 --- a/backend/crates/gateway-core/src/account/scope.rs +++ b/backend/crates/gateway-core/src/account/scope.rs @@ -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, providers_with_accounts: BTreeSet, providers_by_group: BTreeMap>, + group_model_access: BTreeMap, } 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, + ) -> Self { + self.group_model_access = policies; + self + } + + pub(crate) fn accounts_in_group( + &self, + group: &AccountGroupId, + ) -> impl Iterator { + 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, directory: Arc, @@ -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)) + }) } /// 目录按整个授权账号池过滤,不能只看用于获取元数据的账号政策 diff --git a/backend/crates/gateway-core/src/engine/execution/failure.rs b/backend/crates/gateway-core/src/engine/execution/failure.rs index 81daab4b9..85c80ddb7 100644 --- a/backend/crates/gateway-core/src/engine/execution/failure.rs +++ b/backend/crates/gateway-core/src/engine/execution/failure.rs @@ -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, diff --git a/backend/crates/gateway-core/src/engine/execution/service.rs b/backend/crates/gateway-core/src/engine/execution/service.rs index 2f9ae2e7c..189fd2d55 100644 --- a/backend/crates/gateway-core/src/engine/execution/service.rs +++ b/backend/crates/gateway-core/src/engine/execution/service.rs @@ -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( diff --git a/backend/crates/gateway-core/src/engine/group_permissions.rs b/backend/crates/gateway-core/src/engine/group_permissions.rs new file mode 100644 index 000000000..456c1298c --- /dev/null +++ b/backend/crates/gateway-core/src/engine/group_permissions.rs @@ -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(()) +} diff --git a/backend/crates/gateway-core/src/engine/image_generation.rs b/backend/crates/gateway-core/src/engine/image_generation.rs deleted file mode 100644 index 39f767067..000000000 --- a/backend/crates/gateway-core/src/engine/image_generation.rs +++ /dev/null @@ -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(()) -} diff --git a/backend/crates/gateway-core/src/engine/mod.rs b/backend/crates/gateway-core/src/engine/mod.rs index 55ee67f38..bc3c98682 100644 --- a/backend/crates/gateway-core/src/engine/mod.rs +++ b/backend/crates/gateway-core/src/engine/mod.rs @@ -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 { // 入口已校验原请求,此处复查中间件最终提交的 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 }) }) diff --git a/backend/crates/gateway-core/src/error/mod.rs b/backend/crates/gateway-core/src/error/mod.rs index 70c546a65..ac25101d1 100644 --- a/backend/crates/gateway-core/src/error/mod.rs +++ b/backend/crates/gateway-core/src/error/mod.rs @@ -508,6 +508,7 @@ impl fmt::Debug for ClientVisibleUpstreamResponse { /// Core 会在任何持久化或日志记录前取走 /// 这些事件,不能把它们当作诊断上下文使用 pub struct ProviderError { + denied_group_feature: Option, kind: ProviderErrorKind, send_state: UpstreamSendState, upstream_status: Option, @@ -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 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.", diff --git a/backend/crates/gateway-core/src/policy/mod.rs b/backend/crates/gateway-core/src/policy/mod.rs index f9cd1823b..21c563b41 100644 --- a/backend/crates/gateway-core/src/policy/mod.rs +++ b/backend/crates/gateway-core/src/policy/mod.rs @@ -1,6 +1,6 @@ //! 下游 Client API Key 的准入策略 //! -//! Client API Key 冻结账号分组权限;模型名称不参与权限判断 +//! Client API Key 在请求开始时冻结分组成员范围及其模型策略 mod client_version; mod peer_sharing; diff --git a/backend/crates/gateway-core/src/routing/mod.rs b/backend/crates/gateway-core/src/routing/mod.rs index f677877ea..d9252dc55 100644 --- a/backend/crates/gateway-core/src/routing/mod.rs +++ b/backend/crates/gateway-core/src/routing/mod.rs @@ -537,18 +537,11 @@ pub struct RoutingContext { pub struct ProviderCandidate { provider: ProviderKind, upstream_model: Option, - model_presentation: Option, emulated_features: BTreeSet, account_scope: Arc, } 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 diff --git a/backend/crates/gateway-core/src/routing/snapshot.rs b/backend/crates/gateway-core/src/routing/snapshot.rs index 1cc7f0ec7..d53c090d1 100644 --- a/backend/crates/gateway-core/src/routing/snapshot.rs +++ b/backend/crates/gateway-core/src/routing/snapshot.rs @@ -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 { + 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 { @@ -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), diff --git a/backend/crates/gateway-core/src/validation.rs b/backend/crates/gateway-core/src/validation.rs index e1d05fcba..844f8ab9d 100644 --- a/backend/crates/gateway-core/src/validation.rs +++ b/backend/crates/gateway-core/src/validation.rs @@ -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 { diff --git a/backend/crates/gateway-core/tests/engine/coordinator.rs b/backend/crates/gateway-core/tests/engine/coordinator.rs index 82de66541..7f3bcd08e 100644 --- a/backend/crates/gateway-core/tests/engine/coordinator.rs +++ b/backend/crates/gateway-core/tests/engine/coordinator.rs @@ -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(), diff --git a/backend/crates/gateway-core/tests/engine/middleware/mod.rs b/backend/crates/gateway-core/tests/engine/middleware/mod.rs index 243ba4a86..7d05c1de7 100644 --- a/backend/crates/gateway-core/tests/engine/middleware/mod.rs +++ b/backend/crates/gateway-core/tests/engine/middleware/mod.rs @@ -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()); } } diff --git a/backend/crates/gateway-core/tests/routing/snapshot.rs b/backend/crates/gateway-core/tests/routing/snapshot.rs index 5475dca02..604441169 100644 --- a/backend/crates/gateway-core/tests/routing/snapshot.rs +++ b/backend/crates/gateway-core/tests/routing/snapshot.rs @@ -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), diff --git a/backend/crates/gateway-plugin/runtime/src/callback/resources.rs b/backend/crates/gateway-plugin/runtime/src/callback/resources.rs index 4228927eb..4ec60dc43 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/resources.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/resources.rs @@ -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, diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/maintenance.rs b/backend/crates/gateway-plugin/runtime/tests/generation/maintenance.rs index 4388cf988..3a7d30db5 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/maintenance.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/maintenance.rs @@ -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, diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/compatibility.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/compatibility.rs index 2fc9bf3a3..9ffe0abb2 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/policy/compatibility.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/compatibility.rs @@ -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( diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/upstream_adapter.rs b/backend/crates/gateway-plugin/runtime/tests/generation/upstream_adapter.rs index 0f828e173..0e093fd2b 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/upstream_adapter.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/upstream_adapter.rs @@ -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")) diff --git a/backend/crates/gateway-plugin/runtime/tests/support/environment.rs b/backend/crates/gateway-plugin/runtime/tests/support/environment.rs index 1f76f0b8c..796482126 100644 --- a/backend/crates/gateway-plugin/runtime/tests/support/environment.rs +++ b/backend/crates/gateway-plugin/runtime/tests/support/environment.rs @@ -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()), diff --git a/backend/crates/gateway-plugin/sdk/docs/capabilities.md b/backend/crates/gateway-plugin/sdk/docs/capabilities.md index 2fadb2110..909a32e4b 100644 --- a/backend/crates/gateway-plugin/sdk/docs/capabilities.md +++ b/backend/crates/gateway-plugin/sdk/docs/capabilities.md @@ -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` 仍按完整替换校验,因不符合设置对象合同而拒绝。 diff --git a/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md b/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md index 38f80ef62..abefb80a8 100644 --- a/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md +++ b/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md @@ -41,7 +41,7 @@ Provider、业务协议和传输名称不能写入宿主兼容清单的 capabili `TypedCall` 包含只读的 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) diff --git a/backend/crates/gateway-protocol/src/openai/codex.rs b/backend/crates/gateway-protocol/src/openai/codex.rs index de9e79775..c424f30f6 100644 --- a/backend/crates/gateway-protocol/src/openai/codex.rs +++ b/backend/crates/gateway-protocol/src/openai/codex.rs @@ -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).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 { .or_else(|| effort.as_u64().map(|value| value.to_string())) } +/// 只识别协作线程自己的生成请求,review、compact、guardian 和父线程的工具历史均不受限 +#[must_use] +pub fn collaboration_subagent_requested<'a>( + body: &Map, + context: &Map, + 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, turn_metadata: Option<&str>) -> Option { + // 权威上下文与显式 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) -> Option<&str> { non_empty_string(body.get("turnMetadata")) .or_else(|| non_empty_string(body.get("turn_metadata"))) diff --git a/backend/crates/gateway-protocol/tests/openai/codex.rs b/backend/crates/gateway-protocol/tests/openai/codex.rs index 87a0ff3d7..1260258ec 100644 --- a/backend/crates/gateway-protocol/tests/openai/codex.rs +++ b/backend/crates/gateway-protocol/tests/openai/codex.rs @@ -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 + ); + } +} diff --git a/backend/crates/gateway-store/src/postgres/account_groups.rs b/backend/crates/gateway-store/src/postgres/account_groups.rs index 2e796cbcb..bfbd69275 100644 --- a/backend/crates/gateway-store/src/postgres/account_groups.rs +++ b/backend/crates/gateway-store/src/postgres/account_groups.rs @@ -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 { 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 { 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 let provider_counts = serde_json::from_value::>(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::, _>("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()))?; diff --git a/backend/crates/gateway-store/src/postgres/client_keys.rs b/backend/crates/gateway-store/src/postgres/client_keys.rs index 372050867..a00ea1cd8 100644 --- a/backend/crates/gateway-store/src/postgres/client_keys.rs +++ b/backend/crates/gateway-store/src/postgres/client_keys.rs @@ -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 { + 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::>(); + 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, bool, Option>)>( + "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 diff --git a/backend/crates/gateway-store/src/postgres/control_plane.rs b/backend/crates/gateway-store/src/postgres/control_plane.rs index 1dcf96173..bc79ee7b8 100644 --- a/backend/crates/gateway-store/src/postgres/control_plane.rs +++ b/backend/crates/gateway-store/src/postgres/control_plane.rs @@ -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 { + 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() diff --git a/backend/crates/gateway-store/src/postgres/snapshot.rs b/backend/crates/gateway-store/src/postgres/snapshot.rs index 750c93a99..a2936ef4a 100644 --- a/backend/crates/gateway-store/src/postgres/snapshot.rs +++ b/backend/crates/gateway-store/src/postgres/snapshot.rs @@ -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> { - 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)>( + "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() } diff --git a/backend/crates/gateway-store/tests/postgres/account_groups.rs b/backend/crates/gateway-store/tests/postgres/account_groups.rs index 02b3f5d9c..0370d41f9 100644 --- a/backend/crates/gateway-store/tests/postgres/account_groups.rs +++ b/backend/crates/gateway-store/tests/postgres/account_groups.rs @@ -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)>( + "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"), ) diff --git a/backend/crates/gateway-store/tests/postgres/client_keys.rs b/backend/crates/gateway-store/tests/postgres/client_keys.rs index b69485934..cf8249495 100644 --- a/backend/crates/gateway-store/tests/postgres/client_keys.rs +++ b/backend/crates/gateway-store/tests/postgres/client_keys.rs @@ -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::>()) + .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}; diff --git a/backend/crates/providers/openai/src/admin/mod.rs b/backend/crates/providers/openai/src/admin/mod.rs index 417ba07e3..622907703 100644 --- a/backend/crates/providers/openai/src/admin/mod.rs +++ b/backend/crates/providers/openai/src/admin/mod.rs @@ -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>, + installation_seed: Option, + ) -> Result, 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 } diff --git a/backend/crates/providers/openai/src/credential/catalog/mod.rs b/backend/crates/providers/openai/src/credential/catalog/mod.rs index 665091600..556c8fbff 100644 --- a/backend/crates/providers/openai/src/credential/catalog/mod.rs +++ b/backend/crates/providers/openai/src/credential/catalog/mod.rs @@ -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> { let mut accounts = BTreeMap::<&str, BTreeSet>::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 { 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() } diff --git a/backend/crates/providers/openai/src/credential/eligibility.rs b/backend/crates/providers/openai/src/credential/eligibility.rs index 91671166e..2d1e22d9a 100644 --- a/backend/crates/providers/openai/src/credential/eligibility.rs +++ b/backend/crates/providers/openai/src/credential/eligibility.rs @@ -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), } } } diff --git a/backend/crates/providers/openai/src/provider/execution.rs b/backend/crates/providers/openai/src/provider/execution.rs index 17b455a68..7f468464f 100644 --- a/backend/crates/providers/openai/src/provider/execution.rs +++ b/backend/crates/providers/openai/src/provider/execution.rs @@ -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 diff --git a/backend/crates/providers/openai/src/provider/mod.rs b/backend/crates/providers/openai/src/provider/mod.rs index ae28483cd..1650718b5 100644 --- a/backend/crates/providers/openai/src/provider/mod.rs +++ b/backend/crates/providers/openai/src/provider/mod.rs @@ -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, diff --git a/backend/crates/providers/openai/src/transport/profile/identity.rs b/backend/crates/providers/openai/src/transport/profile/identity.rs index c0761c72a..5020f40ce 100644 --- a/backend/crates/providers/openai/src/transport/profile/identity.rs +++ b/backend/crates/providers/openai/src/transport/profile/identity.rs @@ -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>, + installation_seed: Option, +) -> Result, 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 { diff --git a/backend/crates/providers/openai/src/transport/protocol/responses.rs b/backend/crates/providers/openai/src/transport/protocol/responses.rs index 41a075871..c2a9b6415 100644 --- a/backend/crates/providers/openai/src/transport/protocol/responses.rs +++ b/backend/crates/providers/openai/src/transport/protocol/responses.rs @@ -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 diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index 8317e701b..d0b304c5c 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -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(); } diff --git a/backend/crates/providers/openai/tests/provider/contract/search_model_access.rs b/backend/crates/providers/openai/tests/provider/contract/search_model_access.rs index ca2198c79..5e4468b16 100644 --- a/backend/crates/providers/openai/tests/provider/contract/search_model_access.rs +++ b/backend/crates/providers/openai/tests/provider/contract/search_model_access.rs @@ -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, 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; diff --git a/backend/crates/providers/openai/tests/transport/profile/identity.rs b/backend/crates/providers/openai/tests/transport/profile/identity.rs index 71edc1689..7f8e376c2 100644 --- a/backend/crates/providers/openai/tests/transport/profile/identity.rs +++ b/backend/crates/providers/openai/tests/transport/profile/identity.rs @@ -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(¤t), + Some(&Some(document(preset.clone()))), + None + ) + .unwrap(), + Some(document(expected.clone())) + ); + assert_eq!( + merge_batch_key_profile(Some(¤t), 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 { diff --git a/backend/crates/providers/xai/src/credential/catalog.rs b/backend/crates/providers/xai/src/credential/catalog.rs index 54969426d..384c7e9bf 100644 --- a/backend/crates/providers/xai/src/credential/catalog.rs +++ b/backend/crates/providers/xai/src/credential/catalog.rs @@ -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); + #[derive(Default)] struct PublishedCatalogState { generation: u64, - models: Vec, + models: Vec, } impl GrokCredentialCatalogService { @@ -496,27 +499,26 @@ impl GrokCredentialCatalogService { .map_err(|_| GrokCredentialCatalogError::Cache) } - /// Provider Registry 构建 RuntimeSnapshot 时使用的实时能力目录 - pub async fn query_models(&self) -> Result, GrokCredentialCatalogError> { - self.fetch_and_cache().await - } - - async fn fetch_and_cache(&self) -> Result, GrokCredentialCatalogError> { + /// 快照同时冻结套餐目录及其成员;来源变化也要求重新发布 + pub async fn query_models( + &self, + ) -> Result, GrokCredentialCatalogError> { let candidates = self .repository .list_loaded_for_provider() .await - .map_err(|_| GrokCredentialCatalogError::Store)? - .into_iter() - .filter(eligible_catalog_candidate) - .collect::>(); + .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, GrokCredentialCatalogError> { - let mut union = BTreeMap::::new(); - for credential in fetched { + fetched: &[(FetchedCredentialCatalog, BTreeSet)], +) -> Result, GrokCredentialCatalogError> { + let mut union = BTreeMap::::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()); } } } diff --git a/backend/crates/providers/xai/src/provider/mod.rs b/backend/crates/providers/xai/src/provider/mod.rs index 6f1082e85..f67ba01ff 100644 --- a/backend/crates/providers/xai/src/provider/mod.rs +++ b/backend/crates/providers/xai/src/provider/mod.rs @@ -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()) } diff --git a/backend/crates/providers/xai/tests/credential/catalog.rs b/backend/crates/providers/xai/tests/credential/catalog.rs index ff8b9d4ff..9b40227eb 100644 --- a/backend/crates/providers/xai/tests/credential/catalog.rs +++ b/backend/crates/providers/xai/tests/credential/catalog.rs @@ -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")) diff --git a/backend/crates/providers/xai/tests/provider/contract/mod.rs b/backend/crates/providers/xai/tests/provider/contract/mod.rs index f384e9c2e..76298eee5 100644 --- a/backend/crates/providers/xai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/xai/tests/provider/contract/mod.rs @@ -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() diff --git a/backend/migrations/.frozen-sha256 b/backend/migrations/.frozen-sha256 index 01be34402..92f021115 100644 --- a/backend/migrations/.frozen-sha256 +++ b/backend/migrations/.frozen-sha256 @@ -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 diff --git a/backend/migrations/0045_account_group_policies.sql b/backend/migrations/0045_account_group_policies.sql new file mode 100644 index 000000000..1863db822 --- /dev/null +++ b/backend/migrations/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 + ); diff --git a/docs/api.md b/docs/api.md index 475a9a711..e568fdf9f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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"`,非空数组派生 diff --git a/docs/architecture.md b/docs/architecture.md index dadfb999c..57baf5928 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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,账号也可以属于多个分组 diff --git a/frontend/src/api/modules/groups.ts b/frontend/src/api/modules/groups.ts index 7301d1e4b..4b298e482 100644 --- a/frontend/src/api/modules/groups.ts +++ b/frontend/src/api/modules/groups.ts @@ -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 @@ -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({ url: '/api/admin/account-groups/create', diff --git a/frontend/src/api/modules/keys.ts b/frontend/src/api/modules/keys.ts index 3bf01e3b8..3b0eb5a17 100644 --- a/frontend/src/api/modules/keys.ts +++ b/frontend/src/api/modules/keys.ts @@ -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> { + enabled?: boolean + peerSharing?: Partial + 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({ url: '/api/admin/client-keys/update', diff --git a/frontend/src/components/client-profile/ClientProfileEditor.vue b/frontend/src/components/client-profile/ClientProfileEditor.vue index d3a4c5659..e8b7ed51e 100644 --- a/frontend/src/components/client-profile/ClientProfileEditor.vue +++ b/frontend/src/components/client-profile/ClientProfileEditor.vue @@ -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({ required: true }) +const model = defineModel({ required: true }) const options = shallowRef() const preview = shallowRef() 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()) load()) @update:model-value="model = $event" /> -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({ required: true }) +const model = defineModel({ + default: () => ({}), +}) +const updates = defineModel('updates') const provider = shallowRef<(typeof PROVIDER_IDS)[number]>('openai') const providerOptions = PROVIDER_IDS.map(value => ({ value, @@ -32,20 +37,35 @@ const openai = profileModel('openai') const xai = profileModel('xai') function profileModel(providerId: string) { - return computed({ - get: () => (model.value[providerId] as T | undefined) ?? null, - set: value => updateProfile(providerId, value as ProviderRequestProfile | null), + return computed({ + 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 -} - + diff --git a/frontend/src/i18n/locales/en/common.json b/frontend/src/i18n/locales/en/common.json index e87bc81e3..931de8c62 100644 --- a/frontend/src/i18n/locales/en/common.json +++ b/frontend/src/i18n/locales/en/common.json @@ -62,7 +62,8 @@ "next": "Next", "confirm": "Confirm", "refresh": "Refresh", - "save": "Save" + "save": "Save", + "disable": "Disable" }, "providers": { "all": "All platforms", diff --git a/frontend/src/i18n/locales/en/groups.json b/frontend/src/i18n/locales/en/groups.json index 4d633540e..5b5a4f7ac 100644 --- a/frontend/src/i18n/locales/en/groups.json +++ b/frontend/src/i18n/locales/en/groups.json @@ -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}", diff --git a/frontend/src/i18n/locales/en/keys.json b/frontend/src/i18n/locales/en/keys.json index 7240680c7..a84672261 100644 --- a/frontend/src/i18n/locales/en/keys.json +++ b/frontend/src/i18n/locales/en/keys.json @@ -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" } } } diff --git a/frontend/src/i18n/locales/zh-Hans/common.json b/frontend/src/i18n/locales/zh-Hans/common.json index 5a6cf0ffd..b1fc0a287 100644 --- a/frontend/src/i18n/locales/zh-Hans/common.json +++ b/frontend/src/i18n/locales/zh-Hans/common.json @@ -62,7 +62,8 @@ "next": "下一步", "confirm": "确定", "refresh": "刷新", - "save": "保存" + "save": "保存", + "disable": "禁用" }, "providers": { "all": "全部平台", diff --git a/frontend/src/i18n/locales/zh-Hans/groups.json b/frontend/src/i18n/locales/zh-Hans/groups.json index e1cdc6734..f3bb20347 100644 --- a/frontend/src/i18n/locales/zh-Hans/groups.json +++ b/frontend/src/i18n/locales/zh-Hans/groups.json @@ -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": "删除后这些分组将立即失效,此操作不可撤销", diff --git a/frontend/src/i18n/locales/zh-Hans/keys.json b/frontend/src/i18n/locales/zh-Hans/keys.json index 603d9b27e..a36ba8956 100644 --- a/frontend/src/i18n/locales/zh-Hans/keys.json +++ b/frontend/src/i18n/locales/zh-Hans/keys.json @@ -110,6 +110,14 @@ "confirm": "允许访问", "description": "保存后也可访问未分组和以后新增的账号" } + }, + "batch": { + "edit": "批量编辑", + "updated": "已更新 {count} 个密钥", + "description": "已选 {count} 个密钥", + "partiallyEnabled": "部分密钥已启用", + "mixed": "多个值", + "clearLimit": "设为不限" } } } diff --git a/frontend/src/i18n/locales/zh-Hant/common.json b/frontend/src/i18n/locales/zh-Hant/common.json index 4bb4a541d..27ed78f03 100644 --- a/frontend/src/i18n/locales/zh-Hant/common.json +++ b/frontend/src/i18n/locales/zh-Hant/common.json @@ -62,7 +62,8 @@ "next": "下一步", "confirm": "確定", "refresh": "刷新", - "save": "保存" + "save": "保存", + "disable": "禁用" }, "providers": { "all": "全部平臺", diff --git a/frontend/src/i18n/locales/zh-Hant/groups.json b/frontend/src/i18n/locales/zh-Hant/groups.json index 3d7672793..c36510e17 100644 --- a/frontend/src/i18n/locales/zh-Hant/groups.json +++ b/frontend/src/i18n/locales/zh-Hant/groups.json @@ -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": "刪除後這些分組將立即失效,此操作不可撤銷", diff --git a/frontend/src/i18n/locales/zh-Hant/keys.json b/frontend/src/i18n/locales/zh-Hant/keys.json index e21bcf8cd..8907269bc 100644 --- a/frontend/src/i18n/locales/zh-Hant/keys.json +++ b/frontend/src/i18n/locales/zh-Hant/keys.json @@ -110,6 +110,14 @@ "confirm": "允許訪問", "description": "保存後也可訪問未分組和以後新增的賬號" } + }, + "batch": { + "edit": "批次編輯", + "updated": "已更新 {count} 個金鑰", + "description": "已選 {count} 個密鑰", + "partiallyEnabled": "部分密鑰已啟用", + "mixed": "多個值", + "clearLimit": "設為不限" } } } diff --git a/frontend/src/views/accounts/components/AccountModelAccessField.vue b/frontend/src/views/accounts/components/AccountModelAccessField.vue index b915b4bfa..b740f914b 100644 --- a/frontend/src/views/accounts/components/AccountModelAccessField.vue +++ b/frontend/src/views/accounts/components/AccountModelAccessField.vue @@ -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>('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, () => { -