diff --git a/backend/crates/gateway-admin/src/model/client_keys.rs b/backend/crates/gateway-admin/src/model/client_keys.rs index 2683f24df..33a935ff3 100644 --- a/backend/crates/gateway-admin/src/model/client_keys.rs +++ b/backend/crates/gateway-admin/src/model/client_keys.rs @@ -108,6 +108,7 @@ pub struct ClientKeyListQuery { /// 不含完整明文 Key 的管理投影 #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClientKeyRecord { + pub validity: gateway_core::policy::ClientKeyValidity, pub peer_sharing: gateway_core::policy::ClientPeerSharing, pub request_profile_overrides: ProviderRequestProfileOverrides, pub id: ClientApiKeyId, @@ -124,6 +125,13 @@ pub struct ClientKeyRecord { pub updated_at: DateTime, } +impl ClientKeyRecord { + #[must_use] + pub fn is_active(&self) -> bool { + self.enabled && self.validity.is_active() + } +} + /// Client Key 列表页 #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClientKeyPage { @@ -168,6 +176,7 @@ impl fmt::Debug for ClientKeySecret { /// API 提交的 Client Key 创建命令 #[derive(Debug, Clone, PartialEq, Eq)] pub struct CreateClientKey { + pub validity: gateway_core::policy::ClientKeyValidity, pub peer_sharing: gateway_core::policy::ClientPeerSharing, pub request_profile_overrides: ProviderRequestProfileOverrides, pub custom_key: Option, @@ -181,6 +190,7 @@ pub struct CreateClientKey { /// 管理用例生成 ID 与明文后的持久化命令 #[derive(Clone, PartialEq, Eq)] pub struct NewClientKey { + pub validity: gateway_core::policy::ClientKeyValidity, pub peer_sharing: gateway_core::policy::ClientPeerSharing, pub request_profile_overrides: ProviderRequestProfileOverrides, pub id: ClientApiKeyId, @@ -207,6 +217,7 @@ impl fmt::Debug for NewClientKey { /// 修改 Client Key 的公开策略字段 #[derive(Debug, Clone, PartialEq, Eq)] pub struct UpdateClientKey { + pub validity: Option, pub peer_sharing: Option, pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates, pub id: ClientApiKeyId, @@ -293,13 +304,33 @@ pub enum ClientKeyBudgetPeriod { All, } -/// 清零所选窗口并恢复日历规则,保留限额与历史费用 +/// 清零所选窗口,保留限额与历史费用 #[derive(Debug, Clone, PartialEq, Eq)] pub struct ResetClientKeyBudget { pub id: ClientApiKeyId, pub period: ClientKeyBudgetPeriod, } +impl ResetClientKeyBudget { + /// 返回所选日、周窗口的终点;插件重置以起止相同表示等待下次使用 + #[must_use] + pub fn window_ends( + &self, + origin: &ClientKeyBudgetMutationOrigin, + start: DateTime, + ) -> (Option>, Option>) { + let end = |days| match origin { + ClientKeyBudgetMutationOrigin::Admin => start + chrono::Duration::days(days), + ClientKeyBudgetMutationOrigin::Plugin(_) => start, + }; + match self.period { + ClientKeyBudgetPeriod::Daily => (Some(end(1)), None), + ClientKeyBudgetPeriod::Weekly => (None, Some(end(7))), + ClientKeyBudgetPeriod::All => (Some(end(1)), Some(end(7))), + } + } +} + /// 显式窗口复用已有日/周金额上限,外部周期的选择归调用方 #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ClientKeyBudgetWindowPeriod { 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 73d879134..67c9935c6 100644 --- a/backend/crates/gateway-admin/src/use_case/client_keys.rs +++ b/backend/crates/gateway-admin/src/use_case/client_keys.rs @@ -337,6 +337,11 @@ impl ClientKeyService for DefaultClientKeyService { context: &MutationContext, command: CreateClientKey, ) -> Result { + if !command.validity.is_valid() { + return Err(AdminError::invalid( + "请填写完整有效期,到期时间须晚于生效时间", + )); + } crate::model::client_keys::validate_group_ids(&command.group_ids) .map_err(|_| AdminError::invalid("API Key 分组不合法"))?; for (provider, profile) in &command.request_profile_overrides { @@ -354,6 +359,7 @@ impl ClientKeyService for DefaultClientKeyService { .store .create_client_key( NewClientKey { + validity: command.validity, peer_sharing: command.peer_sharing, request_profile_overrides: command.request_profile_overrides, id, @@ -382,6 +388,11 @@ impl ClientKeyService for DefaultClientKeyService { ) -> Result { crate::model::client_keys::validate_group_ids(&command.group_ids) .map_err(|_| AdminError::invalid("API Key 分组不合法"))?; + if command.validity.is_some_and(|range| !range.is_valid()) { + return Err(AdminError::invalid( + "请填写完整有效期,到期时间须晚于生效时间", + )); + } for (provider, profile) in &command.request_profile_override_updates { self.validate_profile(provider, profile.as_ref())?; } diff --git a/backend/crates/gateway-admin/src/use_case/key_usage.rs b/backend/crates/gateway-admin/src/use_case/key_usage.rs index a94e480d0..571bbe2e1 100644 --- a/backend/crates/gateway-admin/src/use_case/key_usage.rs +++ b/backend/crates/gateway-admin/src/use_case/key_usage.rs @@ -137,7 +137,7 @@ impl KeyUsageService for DefaultKeyUsageService { self.keys .get_client_key(id) .await - .map(|key| key.filter(|key| key.enabled).map(|key| key.budget)) + .map(|key| key.filter(|key| key.is_active()).map(|key| key.budget)) .map_err(|error| map_store_error(error, "key usage budget")) } @@ -159,7 +159,7 @@ impl KeyUsageService for DefaultKeyUsageService { self.keys .reveal_client_key(&id) .await - .map(|secret| secret.filter(|secret| secret.record.enabled)) + .map(|secret| secret.filter(|secret| secret.record.is_active())) .map_err(|error| map_store_error(error, "key usage config")) } @@ -176,7 +176,7 @@ impl KeyUsageService for DefaultKeyUsageService { .get_client_key(&id) .await .map_err(|error| map_store_error(error, "key usage profile"))? - .filter(|key| key.enabled) + .filter(|key| key.is_active()) else { return Ok(None); }; diff --git a/backend/crates/gateway-admin/src/use_case/peer_link/mod.rs b/backend/crates/gateway-admin/src/use_case/peer_link/mod.rs index 3dd1f09c5..e38ac6ae4 100644 --- a/backend/crates/gateway-admin/src/use_case/peer_link/mod.rs +++ b/backend/crates/gateway-admin/src/use_case/peer_link/mod.rs @@ -104,7 +104,7 @@ impl PeerLinkService for DefaultPeerLinkService { .get_client_key(client.policy().key_id()) .await .map_err(|error| map_store_error(error, "client API key"))? - .filter(|key| key.enabled) + .filter(|key| key.is_active()) .ok_or(PeerLinkError::Unauthorized)?; let budget_observed_at = Utc::now(); let sharing = intersect_sharing(frozen_sharing, key.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 99be94233..657e9e995 100644 --- a/backend/crates/gateway-admin/src/use_case/plugin_resources.rs +++ b/backend/crates/gateway-admin/src/use_case/plugin_resources.rs @@ -85,6 +85,7 @@ impl PluginResourceAccess for DefaultPluginResourceAccess { resource_key, groups, NewClientKey { + validity: Default::default(), peer_sharing: Default::default(), id, name: command.name, 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 6a66c3cbd..a9e0b9e9e 100644 --- a/backend/crates/gateway-admin/tests/use_case/client_keys.rs +++ b/backend/crates/gateway-admin/tests/use_case/client_keys.rs @@ -151,6 +151,7 @@ impl ClientKeyStore for TestClientKeyStore { } self.plaintexts.lock().unwrap().push(key.plaintext); let record = ClientKeyRecord { + validity: Default::default(), peer_sharing: key.peer_sharing, request_profile_overrides: Default::default(), id: key.id, @@ -318,6 +319,7 @@ async fn plugin_client_key_list_projects_only_public_identity_and_uses_stable_na list_response: Mutex::new(Some(ClientKeyPage { config_revision: Revision::new(7).expect("revision"), items: vec![ClientKeyRecord { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), id: key_id.clone(), @@ -455,6 +457,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat .update( &mutation_context(), UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), id: ClientApiKeyId::new("key_existing").unwrap(), @@ -476,6 +479,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat fn create_command(key: Option<&str>) -> CreateClientKey { CreateClientKey { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), custom_key: key.map(|value| PlaintextClientApiKey::new(value).unwrap()), @@ -570,6 +574,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() { .update( &mutation_context(), UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), id: ClientApiKeyId::new("key_existing").unwrap(), @@ -592,6 +597,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() { async fn clearing_an_unregistered_provider_profile_is_rejected_before_writing() { let services = super::AdminHarness::new().build().await; let command = UpdateClientKey { + validity: None, id: ClientApiKeyId::new("key_existing").unwrap(), name: "test".to_owned(), label: None, diff --git a/backend/crates/gateway-api/src/admin/client_keys.rs b/backend/crates/gateway-api/src/admin/client_keys.rs index 2bf34a7ef..4ca66912b 100644 --- a/backend/crates/gateway-api/src/admin/client_keys.rs +++ b/backend/crates/gateway-api/src/admin/client_keys.rs @@ -153,6 +153,8 @@ impl ClientKeySort { #[derive(Clone, PartialEq, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CreateClientKeyRequest { + #[serde(default)] + validity: gateway_core::policy::ClientKeyValidity, #[serde(default)] peer_sharing: gateway_core::policy::ClientPeerSharing, #[serde(default)] @@ -188,6 +190,7 @@ impl CreateClientKeyRequest { let request_profile_overrides = normalize_request_profile_overrides(self.provider_request_profile_overrides)?; Ok(CreateClientKey { + validity: self.validity, peer_sharing: self.peer_sharing, request_profile_overrides, custom_key: self @@ -216,6 +219,7 @@ impl CreateClientKeyRequest { #[derive(Debug, Clone, PartialEq, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct UpdateClientKeyRequest { + validity: Option, peer_sharing: Option, #[serde(default)] provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates, @@ -241,6 +245,7 @@ impl UpdateClientKeyRequest { let request_profile_override_updates = normalize_request_profile_override_updates(self.provider_request_profile_overrides)?; Ok(UpdateClientKey { + validity: self.validity, peer_sharing: self.peer_sharing, request_profile_override_updates, id: client_key_id(self.id, "clientKeyMutationNotFound")?, @@ -370,6 +375,10 @@ impl #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientKeyView { + validity: gateway_core::policy::ClientKeyValidity, + validity_status: gateway_core::policy::ClientKeyValidityStatus, + starts_at_display: Option, + expires_at_display: Option, peer_sharing: gateway_core::policy::ClientPeerSharing, provider_request_profile_overrides: ProviderRequestProfileOverrides, id: String, @@ -407,6 +416,10 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView { .collect::(); Self { provider_request_profile_overrides, + validity: record.validity, + validity_status: record.validity.status_at(time.now()), + starts_at_display: record.validity.starts_at.map(|start| time.datetime(&start)), + expires_at_display: record.validity.expires_at.map(|end| time.datetime(&end)), peer_sharing: record.peer_sharing, id: record.id.to_string(), name: record.name, diff --git a/backend/crates/gateway-api/tests/admin/client_keys.rs b/backend/crates/gateway-api/tests/admin/client_keys.rs index 865885331..73a6486b5 100644 --- a/backend/crates/gateway-api/tests/admin/client_keys.rs +++ b/backend/crates/gateway-api/tests/admin/client_keys.rs @@ -491,6 +491,7 @@ fn client_key_responses_should_keep_shape_and_redact_creation_debug() { .expect("valid time"); let view = ClientKeyView::from(( gateway_admin::model::client_keys::ClientKeyRecord { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), budget: Default::default(), diff --git a/backend/crates/gateway-api/tests/admin/mod.rs b/backend/crates/gateway-api/tests/admin/mod.rs index ae9c12555..6f249b17a 100644 --- a/backend/crates/gateway-api/tests/admin/mod.rs +++ b/backend/crates/gateway-api/tests/admin/mod.rs @@ -1137,6 +1137,7 @@ impl ClientKeyStore for MemoryClientKeyStore { let now = Utc::now(); Ok(Some(ClientKeySecret::new( ClientKeyRecord { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), budget: Default::default(), diff --git a/backend/crates/gateway-api/tests/key_usage/fixtures.rs b/backend/crates/gateway-api/tests/key_usage/fixtures.rs index e69ef1809..a80ca0d8c 100644 --- a/backend/crates/gateway-api/tests/key_usage/fixtures.rs +++ b/backend/crates/gateway-api/tests/key_usage/fixtures.rs @@ -18,6 +18,7 @@ pub(super) async fn fixture() -> AdminTestFixture { let fixture = key_fixture().await; let now = Utc::now(); *fixture.client_key.lock().unwrap() = Some(ClientKeyRecord { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), id: ClientApiKeyId::new("key-42").unwrap(), diff --git a/backend/crates/gateway-core/src/policy/mod.rs b/backend/crates/gateway-core/src/policy/mod.rs index 21c563b41..a1cd8e795 100644 --- a/backend/crates/gateway-core/src/policy/mod.rs +++ b/backend/crates/gateway-core/src/policy/mod.rs @@ -93,6 +93,49 @@ impl fmt::Debug for PlaintextClientApiKey { } } +/// 密钥可用的绝对时间范围,包含起点、不包含终点 +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ClientKeyValidity { + pub starts_at: Option>, + pub expires_at: Option>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ClientKeyValidityStatus { + Scheduled, + Active, + Expired, +} + +impl ClientKeyValidity { + #[must_use] + pub fn is_valid(self) -> bool { + match (self.starts_at, self.expires_at) { + (None, None) => true, + (Some(start), Some(end)) => start < end, + _ => false, + } + } + + #[must_use] + pub fn status_at(self, now: chrono::DateTime) -> ClientKeyValidityStatus { + if self.expires_at.is_some_and(|end| now >= end) { + ClientKeyValidityStatus::Expired + } else if self.starts_at.is_some_and(|start| now < start) { + ClientKeyValidityStatus::Scheduled + } else { + ClientKeyValidityStatus::Active + } + } + + #[must_use] + pub fn is_active(self) -> bool { + self.status_at(chrono::Utc::now()) == ClientKeyValidityStatus::Active + } +} + /// 零表示对应维度不额外限制 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] @@ -122,6 +165,7 @@ pub struct ClientSettings { /// 从 `client_api_keys` 冻结的公开准入事实 #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClientPolicy { + validity: ClientKeyValidity, peer_sharing: ClientPeerSharing, name_snapshot: Option, defaults: Arc, @@ -168,6 +212,7 @@ impl ClientPolicy { limits: RateLimits, ) -> Self { Self { + validity: ClientKeyValidity::default(), peer_sharing: ClientPeerSharing::default(), name_snapshot: None, defaults: Arc::new(ClientSettings { @@ -183,6 +228,12 @@ impl ClientPolicy { } } + #[must_use] + pub const fn with_validity(mut self, validity: ClientKeyValidity) -> Self { + self.validity = validity; + self + } + #[must_use] pub fn with_name_snapshot(mut self, name: Option) -> Self { self.name_snapshot = name; @@ -233,17 +284,21 @@ impl ClientPolicy { self.limits } - /// 禁用的 Key 不接受新请求 + /// 每次准入按当前时间检查冻结的有效期 /// /// # Errors /// - /// Key 已禁用时返回稳定拒绝原因 + /// Key 已禁用或不在有效期内时返回拒绝原因 pub fn authorize(&self) -> Result<(), PolicyError> { - if self.enabled { + if !self.enabled { + Err(PolicyError::Denied { + reason: "client API key is disabled", + }) + } else if self.validity.is_active() { Ok(()) } else { Err(PolicyError::Denied { - reason: "client API key is disabled", + reason: "client API key is outside its validity period", }) } } diff --git a/backend/crates/gateway-core/src/routing/snapshot.rs b/backend/crates/gateway-core/src/routing/snapshot.rs index 1c74c4fd5..5720b6581 100644 --- a/backend/crates/gateway-core/src/routing/snapshot.rs +++ b/backend/crates/gateway-core/src/routing/snapshot.rs @@ -10,8 +10,8 @@ use crate::account::{FastMode, ProviderAccountId}; use crate::concurrency::ConcurrencyQueuePolicy; use crate::operation::{Operation, OperationKind}; use crate::policy::{ - ClientApiKeyId, ClientPeerSharing, ClientPolicy, CodexClientMinVersions, PlaintextClientApiKey, - RateLimits, + ClientApiKeyId, ClientKeyValidity, ClientPeerSharing, ClientPolicy, CodexClientMinVersions, + PlaintextClientApiKey, RateLimits, }; use crate::settings::{SettingsValues, compiled::CompiledSettings}; use crate::validation::RoutingError; @@ -30,6 +30,7 @@ type ModelCatalogAccounts = BTreeMap, request_profiles: BTreeMap, @@ -46,6 +47,12 @@ impl SnapshotClientPolicyFacts { self } + #[must_use] + pub const fn with_validity(mut self, validity: ClientKeyValidity) -> Self { + self.validity = validity; + self + } + #[must_use] pub fn with_name_snapshot(mut self, name: Option) -> Self { self.name_snapshot = name; @@ -69,6 +76,7 @@ impl SnapshotClientPolicyFacts { limits: RateLimits, ) -> Self { Self { + validity: ClientKeyValidity::default(), peer_sharing: ClientPeerSharing::default(), key_id, name_snapshot: None, @@ -634,6 +642,7 @@ async fn compile_runtime_snapshot( policy.limits, ) .with_name_snapshot(policy.name_snapshot) + .with_validity(policy.validity) .with_peer_sharing(policy.peer_sharing), ); } diff --git a/backend/crates/gateway-core/tests/policy/contract.rs b/backend/crates/gateway-core/tests/policy/contract.rs index 4d40fe563..e559f64de 100644 --- a/backend/crates/gateway-core/tests/policy/contract.rs +++ b/backend/crates/gateway-core/tests/policy/contract.rs @@ -64,3 +64,36 @@ fn migrated_client_keys_keep_their_exact_value_without_prefix_or_length_limits() assert!(PlaintextClientApiKey::new(value).is_err()); } } + +#[test] +fn client_key_validity_includes_the_start_and_excludes_the_end() { + use gateway_core::policy::{ClientKeyValidity, ClientKeyValidityStatus}; + let start = chrono::Utc::now(); + let end = start + chrono::TimeDelta::days(7); + let range = ClientKeyValidity { + starts_at: Some(start), + expires_at: Some(end), + }; + assert!(range.is_valid()); + assert_eq!( + range.status_at(start - chrono::TimeDelta::milliseconds(1)), + ClientKeyValidityStatus::Scheduled + ); + assert_eq!(range.status_at(start), ClientKeyValidityStatus::Active); + assert_eq!(range.status_at(end), ClientKeyValidityStatus::Expired); + assert!( + !ClientKeyValidity { + expires_at: Some(start), + ..range + } + .is_valid() + ); + assert!( + !ClientKeyValidity { + starts_at: None, + ..range + } + .is_valid() + ); + assert!(ClientKeyValidity::default().is_valid()); +} diff --git a/backend/crates/gateway-plugin/runtime/tests/callback/key_facts.rs b/backend/crates/gateway-plugin/runtime/tests/callback/key_facts.rs index ab1a9938c..ff8cff68f 100644 --- a/backend/crates/gateway-plugin/runtime/tests/callback/key_facts.rs +++ b/backend/crates/gateway-plugin/runtime/tests/callback/key_facts.rs @@ -52,6 +52,7 @@ async fn key_facts_read_current_database_groups_without_secrets() { .client_keys() .update_client_key( UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), id: ClientApiKeyId::new(id).unwrap(), diff --git a/backend/crates/gateway-plugin/runtime/tests/support/environment.rs b/backend/crates/gateway-plugin/runtime/tests/support/environment.rs index 0dde907b7..6a0a9adf2 100644 --- a/backend/crates/gateway-plugin/runtime/tests/support/environment.rs +++ b/backend/crates/gateway-plugin/runtime/tests/support/environment.rs @@ -158,6 +158,7 @@ impl Environment { .client_keys() .create_client_key( NewClientKey { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: BTreeMap::new(), id: ClientApiKeyId::new(id).unwrap(), diff --git a/backend/crates/gateway-store/src/postgres/client_budgets/store.rs b/backend/crates/gateway-store/src/postgres/client_budgets/store.rs index 91ff43b98..cfbbfa5ab 100644 --- a/backend/crates/gateway-store/src/postgres/client_budgets/store.rs +++ b/backend/crates/gateway-store/src/postgres/client_budgets/store.rs @@ -7,7 +7,7 @@ use chrono::{DateTime, Utc}; use futures::future::BoxFuture; use gateway_admin::model::{ MutationContext, - client_keys::{ClientKeyBudgetMutationOrigin, ClientKeyBudgetPeriod, ResetClientKeyBudget}, + client_keys::{ClientKeyBudgetMutationOrigin, ResetClientKeyBudget}, }; use gateway_admin::ports::store::AdminStoreResult; use gateway_core::{ @@ -40,7 +40,7 @@ pub(in crate::postgres) async fn reset_client_key_budget( crate::postgres::plugins::begin_plugin_mutation(pool, owner).await? } }; - reset_client_key_budget_in_transaction(&mut tx, &command, context) + reset_client_key_budget_in_transaction(&mut tx, &command, &origin, context) .await .map_err(|error| crate::admin_store_error("client API key budget", error))?; tx.commit().await.map_err(|source| { @@ -54,6 +54,7 @@ pub(in crate::postgres) async fn reset_client_key_budget( async fn reset_client_key_budget_in_transaction( tx: &mut Transaction<'_, Postgres>, command: &ResetClientKeyBudget, + origin: &ClientKeyBudgetMutationOrigin, context: &MutationContext, ) -> StoreResult<()> { // 与准入、结算共用 Key 行锁,重置边界必须在取得锁之后确定 @@ -70,47 +71,40 @@ async fn reset_client_key_budget_in_transaction( id: command.id.as_str().to_owned(), }); } - let daily = matches!( - command.period, - ClientKeyBudgetPeriod::Daily | ClientKeyBudgetPeriod::All - ); - let weekly = matches!( - command.period, - ClientKeyBudgetPeriod::Weekly | ClientKeyBudgetPeriod::All - ); let reset_at = Utc::now(); - // 起止时间收拢到重置边界,窗口保持未开启,同时排除重置前完成的迟到费用 + let (daily_end, weekly_end) = command.window_ends(origin, reset_at); + // 首次建账时未选周期保持未开启,已有账本只更新所选周期 sqlx::query( "insert into client_api_key_budget_windows (client_api_key_id,daily_start,daily_end,weekly_start,weekly_end,revision) - values ($1,$4,$4,$4,$4,1) + values ($1,$2,coalesce($3::timestamptz,$2),$2,coalesce($4::timestamptz,$2),1) on conflict (client_api_key_id) do update set - daily_used_usd = case when $2 then 0 else client_api_key_budget_windows.daily_used_usd end, - daily_start = case when $2 then $4 else client_api_key_budget_windows.daily_start end, - daily_end = case when $2 then $4 else client_api_key_budget_windows.daily_end end, - weekly_used_usd = case when $3 then 0 else client_api_key_budget_windows.weekly_used_usd end, - weekly_start = case when $3 then $4 else client_api_key_budget_windows.weekly_start end, - weekly_end = case when $3 then $4 else client_api_key_budget_windows.weekly_end end, - daily_explicit=case when $2 then false else client_api_key_budget_windows.daily_explicit end, - weekly_explicit=case when $3 then false else client_api_key_budget_windows.weekly_explicit end, + daily_used_usd = case when $3 is not null then 0 else client_api_key_budget_windows.daily_used_usd end, + daily_start = case when $3 is not null then $2 else client_api_key_budget_windows.daily_start end, + daily_end = case when $3 is not null then excluded.daily_end else client_api_key_budget_windows.daily_end end, + weekly_used_usd = case when $4 is not null then 0 else client_api_key_budget_windows.weekly_used_usd end, + weekly_start = case when $4 is not null then $2 else client_api_key_budget_windows.weekly_start end, + weekly_end = case when $4 is not null then excluded.weekly_end else client_api_key_budget_windows.weekly_end end, + daily_explicit=case when $3 is not null then false else client_api_key_budget_windows.daily_explicit end, + weekly_explicit=case when $4 is not null then false else client_api_key_budget_windows.weekly_explicit end, revision=client_api_key_budget_windows.revision+1, last_operation_request=null", ) .bind(command.id.as_str()) - .bind(daily) - .bind(weekly) .bind(reset_at) + .bind(daily_end) + .bind(weekly_end) .execute(&mut **tx) .await .map_err(|source| postgres_unavailable("reset client budget", source))?; let mut fields = Vec::new(); - if daily { + if daily_end.is_some() { fields.extend([ "daily_used_usd".to_owned(), "daily_start".to_owned(), "daily_end".to_owned(), ]); } - if weekly { + if weekly_end.is_some() { fields.extend([ "weekly_used_usd".to_owned(), "weekly_start".to_owned(), @@ -163,7 +157,7 @@ impl PgClientBudgetStore { .map(|charge| charge.request_id.as_str()) .collect::>(); let row = sqlx::query( - "select k.enabled, k.daily_limit_usd::text, k.weekly_limit_usd::text, + "select k.enabled, k.starts_at, k.expires_at, k.daily_limit_usd::text, k.weekly_limit_usd::text, w.daily_start, w.daily_end, w.weekly_start, w.weekly_end, coalesce(w.daily_explicit,false) as daily_explicit, coalesce(w.weekly_explicit,false) as weekly_explicit, @@ -184,6 +178,16 @@ impl PgClientBudgetStore { "Client API key is disabled.", )); } + let validity = gateway_core::policy::ClientKeyValidity { + starts_at: row.get("starts_at"), + expires_at: row.get("expires_at"), + }; + if !validity.is_active() { + return Err(GatewayError::new( + GatewayErrorKind::PolicyDenied, + "Client API key is outside its validity period.", + )); + } let parse = |field: &str| -> Result { row.get::(field) .parse() diff --git a/backend/crates/gateway-store/src/postgres/client_keys.rs b/backend/crates/gateway-store/src/postgres/client_keys.rs index 87b152b0d..4922081b7 100644 --- a/backend/crates/gateway-store/src/postgres/client_keys.rs +++ b/backend/crates/gateway-store/src/postgres/client_keys.rs @@ -34,7 +34,9 @@ use gateway_core::{ engine::budget::{ClientBudgetLimits, ClientBudgetStatus}, engine::execution::ClientApiKeyUsageSink, metering::Decimal, - policy::{ClientApiKeyId, ClientPeerSharing, PlaintextClientApiKey, RateLimits}, + policy::{ + ClientApiKeyId, ClientKeyValidity, ClientPeerSharing, PlaintextClientApiKey, RateLimits, + }, routing::{AccountGroupId, ProviderKind}, task::{DaemonTask, WorkerDaemonContext, WorkerTaskError}, }; @@ -55,6 +57,7 @@ const CLIENT_API_KEY_LAST_USED_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs( #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClientApiKeySnapshot { + pub validity: ClientKeyValidity, pub peer_sharing: ClientPeerSharing, pub name_snapshot: Option, pub request_profiles: std::collections::BTreeMap< @@ -76,6 +79,7 @@ impl ClientApiKeySnapshot { requests_per_minute: i64, ) -> StoreResult { Ok(Self { + validity: ClientKeyValidity::default(), peer_sharing: ClientPeerSharing::default(), name_snapshot: None, request_profiles: std::collections::BTreeMap::new(), @@ -122,6 +126,7 @@ impl fmt::Debug for ClientApiKeySecret { #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClientApiKeyRecord { + pub validity: ClientKeyValidity, pub peer_sharing: ClientPeerSharing, pub request_profile_overrides: BTreeMap, pub id: String, @@ -284,6 +289,7 @@ pub struct ClientApiKeyPage { #[derive(Clone)] pub struct NewClientApiKey { + pub validity: ClientKeyValidity, pub peer_sharing: ClientPeerSharing, pub request_profile_overrides: BTreeMap, pub id: String, @@ -322,6 +328,7 @@ impl NewClientApiKey { #[derive(Debug, Clone, PartialEq, Eq)] pub struct UpdateClientApiKeyDetails { + pub validity: Option, pub peer_sharing: Option, pub request_profile_override_updates: BTreeMap>, pub id: String, @@ -389,7 +396,7 @@ impl ClientApiKeyRepository for PgClientApiKeyRepository { let total = count_client_api_keys(&self.pool, query.search.as_deref()).await?; let mut statement = QueryBuilder::::new( "select k.id, k.name, k.label, k.peer_sharing_json, k.provider_request_profiles_json as request_profile_overrides, - left(k.key, least(10, length(k.key) / 2)) as prefix, k.enabled, + left(k.key, least(10, length(k.key) / 2)) as prefix, k.enabled, k.starts_at, k.expires_at, k.max_concurrency, k.requests_per_minute, k.last_used_at, k.created_at, k.updated_at, '[]'::jsonb as groups, '{}'::text[] as provider_kinds from client_api_keys k @@ -449,7 +456,7 @@ impl ClientApiKeyRepository for PgClientApiKeyRepository { require_nonempty(ENTITY, "id", id)?; let record = sqlx::query( "select k.id, k.name, k.label, k.peer_sharing_json, k.provider_request_profiles_json as request_profile_overrides, - left(k.key, least(10, length(k.key) / 2)) as prefix, k.enabled, + left(k.key, least(10, length(k.key) / 2)) as prefix, k.enabled, k.starts_at, k.expires_at, k.max_concurrency, k.requests_per_minute, k.last_used_at, k.created_at, k.updated_at, coalesce(groups.groups, '[]'::jsonb) as groups, case @@ -687,10 +694,11 @@ impl PgAdminClientKeyStore { } } - /// 会话恢复只读启用状态,不加载明文凭据或其他 Key 的资料 + /// 会话恢复只读启用状态和有效期,不加载明文凭据或其他 Key 的资料 pub async fn is_enabled(&self, id: &ClientApiKeyId) -> AdminStoreResult { sqlx::query_scalar::<_, bool>( - "SELECT EXISTS(SELECT 1 FROM client_api_keys WHERE id = $1 AND enabled)", + "SELECT EXISTS(SELECT 1 FROM client_api_keys WHERE id = $1 AND enabled + AND (starts_at IS NULL OR starts_at <= now()) AND (expires_at IS NULL OR now() < expires_at))", ) .bind(id.as_str()) .fetch_one(&self.keys.pool) @@ -980,6 +988,7 @@ impl ClientKeyStore for PgAdminClientKeyStore { .control_plane .create_client_api_key( NewClientApiKey { + validity: command.validity, peer_sharing: command.peer_sharing, request_profile_overrides: command.request_profile_overrides, id: id.as_str().to_owned(), @@ -1011,6 +1020,8 @@ impl ClientKeyStore for PgAdminClientKeyStore { "weekly_limit_usd", "provider_request_profiles_json", "peer_sharing_json", + "starts_at", + "expires_at", ] .into_iter() .map(str::to_owned) @@ -1032,6 +1043,7 @@ impl ClientKeyStore for PgAdminClientKeyStore { .control_plane .update_client_api_key( UpdateClientApiKeyDetails { + validity: command.validity, peer_sharing: command.peer_sharing, request_profile_override_updates: command.request_profile_override_updates, id: id.as_str().to_owned(), @@ -1063,6 +1075,13 @@ impl ClientKeyStore for PgAdminClientKeyStore { "peer_sharing_json", ] .into_iter() + .chain( + command + .validity + .map(|_| ["starts_at", "expires_at"]) + .into_iter() + .flatten(), + ) .map(str::to_owned) .collect(), ), @@ -1240,6 +1259,7 @@ fn admin_client_key_cursor(cursor: ClientApiKeyCursor) -> AdminStoreResult AdminStoreResult { Ok(AdminClientKeyRecord { + validity: record.validity, peer_sharing: record.peer_sharing, request_profile_overrides: record.request_profile_overrides, id: ClientApiKeyId::new(record.id) @@ -1293,8 +1313,8 @@ pub(crate) async fn insert_client_api_key_in_transaction( sqlx::query( "insert into client_api_keys ( id, name, label, key, enabled, max_concurrency, requests_per_minute, - last_used_at, created_at, updated_at, daily_limit_usd, weekly_limit_usd, provider_request_profiles_json, peer_sharing_json - ) values ($1, $2, $3, $4, true, $5, $6, null, now(), now(), $7::text::numeric, $8::text::numeric, $9::jsonb, $10::jsonb)", + last_used_at, created_at, updated_at, daily_limit_usd, weekly_limit_usd, provider_request_profiles_json, peer_sharing_json, starts_at, expires_at + ) values ($1, $2, $3, $4, true, $5, $6, null, now(), now(), $7::text::numeric, $8::text::numeric, $9::jsonb, $10::jsonb, $11, $12)", ) .bind(&key.id) .bind(key.name.trim()) @@ -1306,6 +1326,8 @@ pub(crate) async fn insert_client_api_key_in_transaction( .bind(key.budget.weekly_usd.canonical()) .bind(sqlx::types::Json(request_profile_overrides)) .bind(sqlx::types::Json(key.peer_sharing)) + .bind(key.validity.starts_at) + .bind(key.validity.expires_at) .execute(&mut **transaction) .await .map_err(|error| { @@ -1385,7 +1407,9 @@ pub(crate) async fn update_client_api_key_in_transaction( weekly_limit_usd = coalesce($7::text::numeric, weekly_limit_usd), provider_request_profiles_json = (provider_request_profiles_json - $8::text[]) || $9::jsonb, - peer_sharing_json = coalesce($10::jsonb, peer_sharing_json) + peer_sharing_json = coalesce($10::jsonb, peer_sharing_json), + starts_at = case when $11 then $12 else starts_at end, + expires_at = case when $11 then $13 else expires_at end where id = $1", ) .bind(&key.id) @@ -1398,6 +1422,9 @@ pub(crate) async fn update_client_api_key_in_transaction( .bind(removed_profiles) .bind(sqlx::types::Json(replacement_profiles)) .bind(key.peer_sharing.map(sqlx::types::Json)) + .bind(key.validity.is_some()) + .bind(key.validity.and_then(|range| range.starts_at)) + .bind(key.validity.and_then(|range| range.expires_at)) .execute(&mut **transaction) .await .map_err(|source| postgres_unavailable("update client API key in transaction", source))?; @@ -1709,6 +1736,14 @@ fn client_record_from_row(row: &sqlx::postgres::PgRow) -> StoreResult, _>("peer_sharing_json") .map_err(|source| invalid("invalid peer sharing").with_source(source))? diff --git a/backend/crates/gateway-store/src/postgres/plugins/resources.rs b/backend/crates/gateway-store/src/postgres/plugins/resources.rs index a7acc248f..512af0cdb 100644 --- a/backend/crates/gateway-store/src/postgres/plugins/resources.rs +++ b/backend/crates/gateway-store/src/postgres/plugins/resources.rs @@ -203,6 +203,7 @@ impl PluginResourceStore for PgPluginStore { return Err(denied()); } let key = NewClientApiKey { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: command.request_profile_overrides, id: command.id.as_str().to_owned(), diff --git a/backend/crates/gateway-store/src/postgres/snapshot.rs b/backend/crates/gateway-store/src/postgres/snapshot.rs index 7d6248c50..14574746a 100644 --- a/backend/crates/gateway-store/src/postgres/snapshot.rs +++ b/backend/crates/gateway-store/src/postgres/snapshot.rs @@ -150,6 +150,7 @@ impl SnapshotStorePort for PgRuntimeSnapshotRepository { ) .with_name_snapshot(key.name_snapshot) .with_request_profiles(key.request_profiles) + .with_validity(key.validity) .with_peer_sharing(key.peer_sharing) }) .collect(); @@ -331,12 +332,14 @@ async fn load_client_keys( sqlx::types::Json>>, String, sqlx::types::Json, + Option>, + Option>, ), >( "select k.id, k.key, coalesce(array_agg(kg.account_group_id order by kg.account_group_id) filter (where kg.account_group_id is not null), '{}') as group_ids, - k.max_concurrency, k.requests_per_minute, k.provider_request_profiles_json, k.name, k.peer_sharing_json + k.max_concurrency, k.requests_per_minute, k.provider_request_profiles_json, k.name, k.peer_sharing_json, k.starts_at, k.expires_at from client_api_keys k left join client_api_key_groups kg on kg.client_api_key_id = k.id where k.enabled @@ -352,6 +355,10 @@ async fn load_client_keys( key.request_profiles = decode_request_profiles(row.5.0)?; key.name_snapshot = Some(row.6); key.peer_sharing = row.7.0; + key.validity = gateway_core::policy::ClientKeyValidity { + starts_at: row.8, + expires_at: row.9, + }; Ok(key) }) .collect() diff --git a/backend/crates/gateway-store/tests/postgres/account_groups.rs b/backend/crates/gateway-store/tests/postgres/account_groups.rs index 0370d41f9..d2edd03de 100644 --- a/backend/crates/gateway-store/tests/postgres/account_groups.rs +++ b/backend/crates/gateway-store/tests/postgres/account_groups.rs @@ -203,6 +203,7 @@ async fn groups_aggregate_cross_provider_members_and_key_bindings_without_multip let (scope_revision, widened) = keys .update_client_key( UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), daily_limit_usd: None, @@ -230,6 +231,7 @@ async fn groups_aggregate_cross_provider_members_and_key_bindings_without_multip let (restricted_revision, restricted) = keys .update_client_key( UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), daily_limit_usd: None, @@ -449,6 +451,7 @@ async fn group_costs_should_include_statusless_websocket_but_reject_statusless_h fn new_key(id: &str, group_ids: Vec) -> NewClientKey { let marker = char::from(id.as_bytes().last().copied().unwrap_or(b'k')); NewClientKey { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), budget: Default::default(), diff --git a/backend/crates/gateway-store/tests/postgres/client_budgets/store.rs b/backend/crates/gateway-store/tests/postgres/client_budgets/store.rs index 23c3f80c8..e18880a0e 100644 --- a/backend/crates/gateway-store/tests/postgres/client_budgets/store.rs +++ b/backend/crates/gateway-store/tests/postgres/client_budgets/store.rs @@ -89,6 +89,7 @@ async fn deleting_a_key_preserves_its_ledger_and_settles_inflight_requests_once( keys.create_client_key( NewClientKey { + validity: Default::default(), id: key_id("replacement"), name: "original".into(), label: None, @@ -202,6 +203,7 @@ async fn manual_reset_clears_selected_windows_and_preserves_policy_and_history() store.settle(billed.clone()).await.unwrap(); assert!(store.admit(key_id(key)).await.is_err()); let before = status(&database, key).await; + let earliest_start = SystemTime::now() - std::time::Duration::from_micros(1); admin .reset_client_key_budget( ResetClientKeyBudget { @@ -217,19 +219,32 @@ async fn manual_reset_clears_selected_windows_and_preserves_policy_and_history() assert_eq!(after.daily_used_usd.canonical(), daily); assert_eq!(after.weekly_used_usd.canonical(), weekly); assert_eq!(after.limits, before.limits); - assert_eq!( - after.daily_resets_at(), - (period == ClientKeyBudgetPeriod::Weekly) - .then_some(before.daily_resets_at()) - .flatten() - ); - assert_eq!( - after.weekly_resets_at(), - (period == ClientKeyBudgetPeriod::Daily) - .then_some(before.weekly_resets_at()) - .flatten() - ); - // 同一费用重试既不重复扣额,也不能重新开启已重置的窗口 + for (selected, window, previous, hours) in [ + ( + period != ClientKeyBudgetPeriod::Weekly, + after.daily_window, + before.daily_window, + 24, + ), + ( + period != ClientKeyBudgetPeriod::Daily, + after.weekly_window, + before.weekly_window, + 168, + ), + ] { + if selected { + let window = window.unwrap(); + assert!((earliest_start..=SystemTime::now()).contains(&window.start)); + assert_eq!( + window.end.duration_since(window.start).unwrap(), + std::time::Duration::from_hours(hours) + ); + } else { + assert_eq!(window, previous); + } + } + // 已入账费用的重试不会再次扣额或移动窗口 store.settle(billed).await.unwrap(); assert_eq!(status(&database, key).await, after); assert_eq!( @@ -247,7 +262,7 @@ async fn manual_reset_clears_selected_windows_and_preserves_policy_and_history() } #[tokio::test] -async fn manual_reset_restarts_selected_windows_only_after_new_usage() { +async fn late_charges_and_new_usage_preserve_manual_reset_windows() { let Some(database) = TestDatabase::create("budget_reset_restart").await else { return; }; @@ -261,9 +276,6 @@ async fn manual_reset_restarts_selected_windows_only_after_new_usage() { seed(&database, key, "10", "20").await; store.admit(key_id(key)).await.unwrap(); store.settle(charge(key, key, "1")).await.unwrap(); - sqlx::query("update client_api_key_budget_windows set weekly_start = weekly_start - interval '3 days', weekly_end = weekly_end - interval '3 days' where client_api_key_id = $1") - .bind(key).execute(&database.pool).await.unwrap(); - let before = status(&database, key).await; let delayed = charge(key, &format!("{key}-delayed"), "0.5"); let old = charge(key, &format!("{key}-old"), "0.7"); admin @@ -278,7 +290,7 @@ async fn manual_reset_restarts_selected_windows_only_after_new_usage() { .await .unwrap(); let reset = status(&database, key).await; - // 重置前完成的迟到费用保留历史,但不能开启窗口或重新扣入所选周期 + // 重置前完成的迟到费用保留历史,但不能重新扣入所选周期 store.settle(delayed).await.unwrap(); let delayed = status(&database, key).await; assert_eq!(delayed.daily_resets_at(), reset.daily_resets_at()); @@ -302,17 +314,8 @@ async fn manual_reset_restarts_selected_windows_only_after_new_usage() { store.admit(key_id(key)).await.unwrap(); let restarted = status(&database, key).await; - assert_eq!(restarted.daily_resets_at(), before.daily_resets_at()); - if period == ClientKeyBudgetPeriod::Daily { - assert_eq!(restarted.weekly_resets_at(), before.weekly_resets_at()); - } else { - assert_eq!( - restarted.weekly_resets_at().unwrap(), - restarted.daily_resets_at().unwrap() + std::time::Duration::from_secs(6 * 86400) - ); - assert_ne!(restarted.weekly_resets_at(), before.weekly_resets_at()); - } - // 开启窗口后仍保留重置边界,另一笔重置前的迟到费用也不能重新扣额 + assert_eq!(restarted, delayed); + // 新请求准入后,重置前完成的费用仍按原完成时间归属 store.settle(old).await.unwrap(); let after_old = status(&database, key).await; assert_eq!(after_old.daily_resets_at(), restarted.daily_resets_at()); @@ -401,7 +404,8 @@ async fn manual_reset_excludes_old_completions_but_counts_inflight_requests_afte } #[tokio::test] -async fn manual_reset_leaves_unused_and_expired_windows_inactive_and_reports_missing_keys() { +async fn manual_reset_opens_selected_windows_for_unused_and_expired_keys_and_reports_missing_keys() +{ let Some(database) = TestDatabase::create("budget_reset_inactive").await else { return; }; @@ -414,12 +418,15 @@ async fn manual_reset_leaves_unused_and_expired_windows_inactive_and_reports_mis store.settle(charge("expired", "old", "2")).await.unwrap(); sqlx::query("update client_api_key_budget_windows set daily_end = now() - interval '1 second', weekly_end = now() - interval '1 second'") .execute(&database.pool).await.unwrap(); - for key in ["unused", "expired"] { + for (key, period) in [ + ("unused", ClientKeyBudgetPeriod::Weekly), + ("expired", ClientKeyBudgetPeriod::All), + ] { admin .reset_client_key_budget( ResetClientKeyBudget { id: key_id(key), - period: ClientKeyBudgetPeriod::All, + period, }, ClientKeyBudgetMutationOrigin::Admin, &context(), @@ -427,8 +434,11 @@ async fn manual_reset_leaves_unused_and_expired_windows_inactive_and_reports_mis .await .unwrap(); let after = status(&database, key).await; - assert!(after.daily_resets_at().is_none()); - assert!(after.weekly_resets_at().is_none()); + assert_eq!( + after.daily_resets_at().is_some(), + period == ClientKeyBudgetPeriod::All + ); + assert!(after.weekly_resets_at().is_some()); assert_eq!(after.daily_used_usd.canonical(), "0"); } // 未使用的 Key 也记录控制版本,重置前读到的窗口版本不能继续提交 @@ -720,6 +730,7 @@ async fn budget_updates_preserve_omitted_limits_and_do_not_clear_usage() { .await .unwrap(); let update = UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), id: ClientApiKeyId::new("key").unwrap(), @@ -740,6 +751,7 @@ async fn budget_updates_preserve_omitted_limits_and_do_not_clear_usage() { admin .update_client_key( UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), daily_limit_usd: None, @@ -765,6 +777,7 @@ async fn budget_updates_preserve_omitted_limits_and_do_not_clear_usage() { admin .update_client_key( UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), daily_limit_usd: Some("0".parse().unwrap()), diff --git a/backend/crates/gateway-store/tests/postgres/client_keys.rs b/backend/crates/gateway-store/tests/postgres/client_keys.rs index cf8249495..6eca2f3e5 100644 --- a/backend/crates/gateway-store/tests/postgres/client_keys.rs +++ b/backend/crates/gateway-store/tests/postgres/client_keys.rs @@ -84,6 +84,7 @@ async fn peer_sharing_persists_across_reads_and_cannot_lose_its_group_scope() { store .create_client_key( NewClientKey { + validity: Default::default(), peer_sharing: sharing, request_profile_overrides: Default::default(), id: id.clone(), @@ -113,6 +114,7 @@ async fn peer_sharing_persists_across_reads_and_cannot_lose_its_group_scope() { .unwrap(); assert_eq!(snapshot.client_api_keys[0].peer_sharing, sharing); let mut update = UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), id: id.clone(), @@ -398,6 +400,7 @@ async fn custom_keys_persist_exactly_and_keep_short_keys_masked() { let (_, record) = store .create_client_key( NewClientKey { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), id: id.clone(), @@ -454,6 +457,7 @@ async fn duplicate_custom_keys_conflict_atomically_without_extra_audits() { }; let key = "custom-key-case-sensitive!"; let command = |id: &str| NewClientKey { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), id: ClientApiKeyId::new(id).unwrap(), @@ -491,6 +495,7 @@ async fn duplicate_custom_keys_conflict_atomically_without_extra_audits() { #[test] fn generated_client_key_format_remains_valid() { let key = NewClientApiKey { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), budget: Default::default(), @@ -525,6 +530,7 @@ async fn client_key_names_are_checked_atomically_on_create_and_rename() { request_id: "duplicate-name-test".to_owned(), }; let create = |id: &str, name: &str| NewClientKey { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), id: ClientApiKeyId::new(id).unwrap(), @@ -536,6 +542,7 @@ async fn client_key_names_are_checked_atomically_on_create_and_rename() { plaintext: format!("synthetic-credential-{id}"), }; let update = |id: ClientApiKeyId, name: &str| UpdateClientKey { + validity: Default::default(), peer_sharing: None, request_profile_override_updates: Default::default(), id, @@ -1000,6 +1007,7 @@ async fn dedicated_reveal_returns_plaintext_without_debug_exposure() { fn client_key_debug_redacts_plaintext() { let secret = format!("sk_{}", "s".repeat(43)); let key = NewClientApiKey { + validity: Default::default(), peer_sharing: Default::default(), request_profile_overrides: Default::default(), budget: Default::default(), @@ -1074,6 +1082,7 @@ async fn key_profile_override_roundtrips_and_explicit_clear_restores_inheritance let (_, record) = store .create_client_key( NewClientKey { + validity: Default::default(), peer_sharing: Default::default(), id: id.clone(), name: "profile".to_owned(), @@ -1097,6 +1106,7 @@ async fn key_profile_override_roundtrips_and_explicit_clear_restores_inheritance ); assert_eq!(record.request_profile_overrides.get(&xai), Some(&profile)); let update = |override_value: Option>| UpdateClientKey { + validity: Default::default(), peer_sharing: None, id: id.clone(), name: "profile".to_owned(), diff --git a/backend/crates/gateway-store/tests/postgres/snapshot.rs b/backend/crates/gateway-store/tests/postgres/snapshot.rs index 6c648f44f..7aa622b72 100644 --- a/backend/crates/gateway-store/tests/postgres/snapshot.rs +++ b/backend/crates/gateway-store/tests/postgres/snapshot.rs @@ -10,6 +10,7 @@ use super::TestDatabase; #[test] fn client_key_snapshot_debug_redacts_plaintext_key() { let policy = ClientApiKeySnapshot { + validity: Default::default(), peer_sharing: Default::default(), name_snapshot: None, request_profiles: Default::default(), diff --git a/backend/migrations/.frozen-sha256 b/backend/migrations/.frozen-sha256 index 1b901e903..9aa45e60c 100644 --- a/backend/migrations/.frozen-sha256 +++ b/backend/migrations/.frozen-sha256 @@ -46,3 +46,4 @@ aeff99fee7cef5a553ae49ffe27a48f49e31ccfb3fbc61a2482c9b109478202d 0041_account_m e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_and_runtime_settings.sql 98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql 709df48f4dd067332177fb8bee15c5e75d4666a0dc9c7a8e48f8480a01a99908 0048_openai_runtime_settings.sql +c7ade39b6c5026c1a728bf4e3e0d64c5d5b6aba1cf6fa13a64ca2b79172ab56c 0049_client_key_validity.sql diff --git a/backend/migrations/0049_client_key_validity.sql b/backend/migrations/0049_client_key_validity.sql new file mode 100644 index 000000000..4e80b3464 --- /dev/null +++ b/backend/migrations/0049_client_key_validity.sql @@ -0,0 +1,7 @@ +ALTER TABLE client_api_keys + ADD COLUMN starts_at timestamptz, + ADD COLUMN expires_at timestamptz, + ADD CONSTRAINT client_api_keys_validity_order CHECK ( + (starts_at IS NULL AND expires_at IS NULL) OR + (starts_at IS NOT NULL AND expires_at IS NOT NULL AND starts_at < expires_at) + ); diff --git a/docs/api.md b/docs/api.md index 393be8c1b..a2bd03c57 100644 --- a/docs/api.md +++ b/docs/api.md @@ -944,7 +944,7 @@ OpenAI 选号阶段确认本次可选账号全部额度耗尽时,HTTP 返回 ` 金额使用十进制字符串,`total` 为当前周期限额,`used` 为该周期已结算金额,`remaining` 为限额减已用且最低为零。 不限额时 `total`、`remaining` 均为 `null`,仍返回已用金额。`resetsAt` 为 RFC3339 窗口结束时间。 原生窗口尚未开启或已到期时,`resetsAt` 为 `null`,`used` 为 `"0"`;显式窗口到期后仍返回已结算金额和结束时间。 -原生窗口按部署时区的自然日或首次使用起的七个本地日历日划分,显式窗口采用[插件设置的边界](#7-client-key)。 +默认按部署时区的自然日或首次使用起的七个本地日历日划分,手动重置、对齐账号或插件设置的窗口采用[各自的起止时间](#限额与调度)。 修改限额、管理员重置和费用结算均复用现有 Key 账本,不从请求日志重算余额 缺失、非法、已禁用或已删除的 Key 返回 OpenAI 风格 `401` 错误;未知查询参数返回 `400 invalid_usage_query`, @@ -2243,6 +2243,11 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范 } ``` +创建、更新可传 `validity`,其中 `startsAt`、`expiresAt` 为带时区的 RFC3339 时间点。起点包含在有效期内,到达终点即失效。起止时间须成对填写,终点须晚于起点。 +创建时默认立即生效且长期有效;更新时省略整个对象保留原有效期,传入对象会替换两个边界,两者同时为空可恢复长期有效。 +管理页面使用浏览器本地时间选择起止日期和时分秒。新建默认留空,选择日期时默认 00:00:00;7 天和 30 天从今天零点起按日历日计算。 +列表提供 `validity`、查询时的 `validityStatus`(`scheduled`、`active`、`expired`)和按部署时区格式化的 `startsAtDisplay`、`expiresAtDisplay`。手动重置额度保留密钥有效期 + 自定义 Key 的分组权限、日/周限额和并发规则按本平台配置执行,不导入其他平台的历史用量 ### 限额与调度 @@ -2258,10 +2263,10 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范 切换部署时区不修改已打开窗口的起止点或金额,到期后续接窗口不与旧窗口重叠。 通过[插件预算接口](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#client-key-预算)设置的显式窗口使用指定起止时间, 到期后仍返回当前消费与结束时间,不自动开启下一周期;未开始或已到期时拒绝准入,零金额上限也不例外。 -手动重置清零所选周期的已用金额、退出显式模式并清除到期时间,保留限额上限和历史费用,返回 `{ id }`。 -所选窗口的重置时间返回 `null`,下次使用时按新建 Key 的规则重新开启。重置前完成但延迟结算的费用不再计入所选周期,也不会开启窗口; -重置后完成的请求继续计费,包括重置时仍在进行的请求。操作保留管理员审计,不改变账号上游额度。 -费用按请求完成时间归属窗口。并发按同一 Key 的执行中请求累计,包含 SSE 与每个 WebSocket +管理员手动重置会清零所选周期的已用金额并立即开启本期窗口,日额度从重置时起计 24 小时,周额度计 7 天。 +操作返回 `{ id }`,随后查询即可看到新的到期时间。重置会退出所选周期的显式模式,本期到期后按原生日历规则续开。 +重置保留限额、历史费用和管理员审计,不改变账号上游额度。费用按完成时间归属,重置前完成的迟到费用排除在新窗口外,重置后完成的在途请求计入新窗口。 +并发按同一 Key 的执行中请求累计,包含 SSE 与每个 WebSocket `response.create`;空闲连接不占名额,内部重试不重复占用。 修改 Key 策略对既有 WebSocket 连接的下一次请求同样生效,已开始的请求保持原有快照 diff --git a/docs/architecture.md b/docs/architecture.md index 102626317..6ade74796 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -897,9 +897,9 @@ Core 拥有容量池、上限与等待合同,OpenAI Provider 负责识别请 日金额、七天金额、并发和 RPM 按 Client Key 跨账号、跨 Provider 合计,零表示不限;修改限额不重置已用金额。 Core 负责准入与结算时序,Store 持久化费用账本,Admin 负责限额配置。 -Admin 的手动重置复用同一账本与 Key 行锁,在一个事务中清零所选周期金额、推进计费起点并写入审计, -关闭所选窗口并保留费用事件,不推进配置 revision,下次使用时重新开启窗口。 -结算仍按完成时间判断归属,重置前完成的费用不会重新扣入已重置周期或开启窗口。 +密钥生效与到期时间保存在 `client_api_keys`,Core 在每次认证时对照当前时间检查快照中的有效期,无须在边界时刻重建快照。 +管理员手动重置复用同一账本与 Key 行锁,在一个事务中清零所选周期金额、从重置时刻开启本期窗口并写入审计。 +操作保留费用事件,不推进配置 revision。结算按完成时间判断归属,重置前完成的费用不会重新扣入已重置周期。 管理员手动对齐账号窗口时,同一事务更新所选周期的边界、从费用事件重算已用金额并记录审计。一次性对齐的窗口到期后恢复原生滚动。 插件预算回调通过 `PluginClientKeyAccess` 进入同一 `ClientKeyService` 和 `ClientKeyStore`,存储事务先复核插件实例版本, 再执行原生预算操作;不建立另一份预算状态。查询复用账本投影,不触发准入。局部更新金额上限不改用量或窗口, @@ -1021,7 +1021,7 @@ OpenAI / xAI 导入用例。并发槽位由单个 Worker 统一管理,条目 管理员和密钥登录共用 `/api/auth/*`、AuthService、Redis 会话结构和 `cpr_session` Cookie。 登录类型只选择凭据校验方式,权限来自服务端保存的身份。管理入口只接受管理员身份或部署级管理 API Key; -AuthService 每次恢复 Key 会话时重新检查 Key 是否存在且启用;Key 会话不能访问管理员页面和管理接口。 +AuthService 每次恢复 Key 会话时重新检查 Key 是否存在、启用且处于有效期内;Key 会话不能访问管理员页面和管理接口。 前端只维护一份 Auth Store,不在每个 API 请求上标记身份;401 会话失效、403 权限不足和 503 依赖故障分别处理。 成功登录替换当前浏览器的旧会话,登出必须确认服务端撤销。 管理员访问凭据和续期凭据绑定同一逻辑会话,AuthService 负责签发、身份校验、轮换、不活动期限和最长有效期。 diff --git a/frontend/src/api/modules/keys.ts b/frontend/src/api/modules/keys.ts index cced8ede3..1e72ba2bf 100644 --- a/frontend/src/api/modules/keys.ts +++ b/frontend/src/api/modules/keys.ts @@ -13,7 +13,16 @@ export interface ApiKeyPeerSharing { sharePlans: boolean } +export interface ApiKeyValidity { + startsAt: string | null + expiresAt: string | null +} + export interface ApiKey { + validity: ApiKeyValidity + validityStatus: 'scheduled' | 'active' | 'expired' + startsAtDisplay: string | null + expiresAtDisplay: string | null peerSharing: ApiKeyPeerSharing providerRequestProfileOverrides: ProviderRequestProfiles @@ -75,6 +84,7 @@ interface ApiKeyListParams { } export interface ApiKeyWriteParam { + validity?: ApiKeyValidity peerSharing: ApiKeyPeerSharing name: string label: string | null @@ -120,7 +130,7 @@ export function createApiKey(data: ApiKeyCreateParam) { }) } -export interface ApiKeyBatchChanges extends Partial> { +export interface ApiKeyBatchChanges extends Partial> { enabled?: boolean peerSharing?: Partial providerRequestProfileOverrides?: ProviderRequestProfileUpdates diff --git a/frontend/src/i18n/locales/en/accounts.json b/frontend/src/i18n/locales/en/accounts.json index 837371e3e..dafa86aa5 100644 --- a/frontend/src/i18n/locales/en/accounts.json +++ b/frontend/src/i18n/locales/en/accounts.json @@ -353,8 +353,8 @@ "batchImport": "Batch", "selectAccountPlatform": "Select account platform", "accountPlatform": "Account platform", - "maximumWordsOptional": "Maximum 500 words, optional", - "namePlaceholder": "Optional, applies only when importing one account", + "notesPlaceholder": "Up to 500 characters", + "namePlaceholder": "Leave blank to keep the original name. Applies to single-account imports.", "copyAccount": "Copy account", "accountCopied": "Account copied", "howToAddAccount": "How to add an account", diff --git a/frontend/src/i18n/locales/en/keys.json b/frontend/src/i18n/locales/en/keys.json index c25750ea5..b21cb94b4 100644 --- a/frontend/src/i18n/locales/en/keys.json +++ b/frontend/src/i18n/locales/en/keys.json @@ -1,5 +1,19 @@ { "keys": { + "validity": { + "noExpiry": "No expiry", + "timeLimited": "Time-limited", + "label": "Key validity", + "startsAt": "Starts at", + "expiresAt": "Expires at", + "startDate": "Start date", + "endDate": "End date", + "week": "7 days", + "month": "30 days", + "invalidRange": "Expiry must be after the start time", + "scheduled": "Scheduled", + "expired": "Expired" + }, "configuration": { "platform": "Platform", "toggleWebSocket": "Switch WebSocket configuration", @@ -69,7 +83,7 @@ "dailyQuota": "Daily quota", "weeklyQuota": "Weekly quota", "keyQuotaReset": "Key quota reset", - "description": "Clear spending for the selected period, the reset date is set again on the next request", + "description": "Clear spending for the selected periods and start them again now", "targetKey": "Target key", "resetScope": "Reset scope", "currentlyUsed": "Currently used", @@ -93,9 +107,9 @@ "editor": { "description": "Set API key details, account groups, and usage limits", "namePlaceholder": "For example: Production", - "labelOptional": "Label (optional)", + "label": "Label", "forExampleBackendService": "For example: backend service", - "customKeyOptional": "Custom Key (optional)", + "customKey": "Custom Key", "keyPlaceholder": "Leave blank to generate a key", "upstreamIdentity": "Upstream identity", "dailyLimit": "Daily limit", diff --git a/frontend/src/i18n/locales/en/plugins.json b/frontend/src/i18n/locales/en/plugins.json index dd273162e..2b4073908 100644 --- a/frontend/src/i18n/locales/en/plugins.json +++ b/frontend/src/i18n/locales/en/plugins.json @@ -235,9 +235,9 @@ "allowPrereleaseLabel": "Allow prerelease lookup", "verificationSummary": "Verification summary", "digestHelpTitle": "About package verification", - "digestHelp": "Optional 64-character SHA-256 hexadecimal digest from the publisher, used to verify the download", + "digestHelp": "Use the publisher’s 64-character SHA-256 hexadecimal digest to verify the download", "shaChecksum": "SHA-256 checksum", - "optionalSha": "Optional, SHA-256", + "digestPlaceholder": "64 hexadecimal characters", "versionFound": "Version found", "preRelease": "Pre-release", "thereIsNoTarGzOrTgz": "There is no tar.gz or tgz plugin package for this release", diff --git a/frontend/src/i18n/locales/zh-Hans/accounts.json b/frontend/src/i18n/locales/zh-Hans/accounts.json index 7df6e9183..b8407d527 100644 --- a/frontend/src/i18n/locales/zh-Hans/accounts.json +++ b/frontend/src/i18n/locales/zh-Hans/accounts.json @@ -353,7 +353,7 @@ "batchImport": "批量导入", "selectAccountPlatform": "选择账号平台", "accountPlatform": "账号平台", - "maximumWordsOptional": "最多 500 字,可不填", + "notesPlaceholder": "最多 500 字", "namePlaceholder": "留空保留原名称,仅单账号导入生效", "copyAccount": "复制账号", "accountCopied": "账号已复制", diff --git a/frontend/src/i18n/locales/zh-Hans/keys.json b/frontend/src/i18n/locales/zh-Hans/keys.json index 0257378d6..47959d5fb 100644 --- a/frontend/src/i18n/locales/zh-Hans/keys.json +++ b/frontend/src/i18n/locales/zh-Hans/keys.json @@ -1,5 +1,19 @@ { "keys": { + "validity": { + "noExpiry": "长期有效", + "timeLimited": "限时有效", + "label": "密钥有效期", + "startsAt": "生效时间", + "expiresAt": "到期时间", + "startDate": "开始日期", + "endDate": "结束日期", + "week": "7 天", + "month": "30 天", + "invalidRange": "到期时间须晚于生效时间", + "scheduled": "待生效", + "expired": "已到期" + }, "configuration": { "platform": "平台", "toggleWebSocket": "切换 WebSocket 配置", @@ -69,7 +83,7 @@ "dailyQuota": "日额度", "weeklyQuota": "周额度", "keyQuotaReset": "已重置密钥额度", - "description": "清零所选周期的已用金额,下次使用时重新确定重置日期", + "description": "所选周期的已用金额清零,新周期从现在开始", "targetKey": "目标密钥", "resetScope": "重置范围", "currentlyUsed": "当前已用", @@ -93,9 +107,9 @@ "editor": { "description": "配置密钥信息、分组与使用限制", "namePlaceholder": "例如:生产环境", - "labelOptional": "标签(可选)", + "label": "标签", "forExampleBackendService": "例如:后端服务", - "customKeyOptional": "自定义 API密钥(可选)", + "customKey": "自定义 API 密钥", "keyPlaceholder": "留空自动生成", "upstreamIdentity": "上游身份", "dailyLimit": "日限额", diff --git a/frontend/src/i18n/locales/zh-Hans/plugins.json b/frontend/src/i18n/locales/zh-Hans/plugins.json index dac8a1aae..cab6a19f2 100644 --- a/frontend/src/i18n/locales/zh-Hans/plugins.json +++ b/frontend/src/i18n/locales/zh-Hans/plugins.json @@ -235,9 +235,9 @@ "allowPrereleaseLabel": "允许查询预发行版", "verificationSummary": "校验摘要", "digestHelpTitle": "校验摘要说明", - "digestHelp": "可选,填写发布者提供的 64 位 SHA-256 十六进制摘要,用于核对下载内容", + "digestHelp": "填写发布者提供的 64 位 SHA-256 十六进制摘要,用于核对下载内容", "shaChecksum": "SHA-256 校验摘要", - "optionalSha": "可选,SHA-256", + "digestPlaceholder": "64 位十六进制摘要", "versionFound": "已找到版本", "preRelease": "预发行版", "thereIsNoTarGzOrTgz": "此版本没有 tar.gz 或 tgz 插件包", diff --git a/frontend/src/i18n/locales/zh-Hant/accounts.json b/frontend/src/i18n/locales/zh-Hant/accounts.json index 8e15f7881..e8a8d30b4 100644 --- a/frontend/src/i18n/locales/zh-Hant/accounts.json +++ b/frontend/src/i18n/locales/zh-Hant/accounts.json @@ -353,7 +353,7 @@ "batchImport": "批量導入", "selectAccountPlatform": "選擇賬號平臺", "accountPlatform": "賬號平臺", - "maximumWordsOptional": "最多 500 字,可不填", + "notesPlaceholder": "最多 500 字", "namePlaceholder": "留空保留原名稱,僅單賬號導入生效", "copyAccount": "複製賬號", "accountCopied": "賬號已複製", diff --git a/frontend/src/i18n/locales/zh-Hant/keys.json b/frontend/src/i18n/locales/zh-Hant/keys.json index 847b5a037..258945b80 100644 --- a/frontend/src/i18n/locales/zh-Hant/keys.json +++ b/frontend/src/i18n/locales/zh-Hant/keys.json @@ -1,5 +1,19 @@ { "keys": { + "validity": { + "noExpiry": "長期有效", + "timeLimited": "限時有效", + "label": "密鑰有效期", + "startsAt": "生效時間", + "expiresAt": "到期時間", + "startDate": "開始日期", + "endDate": "結束日期", + "week": "7 天", + "month": "30 天", + "invalidRange": "到期時間須晚於生效時間", + "scheduled": "待生效", + "expired": "已到期" + }, "configuration": { "platform": "平台", "toggleWebSocket": "切換 WebSocket 配置", @@ -69,7 +83,7 @@ "dailyQuota": "日額度", "weeklyQuota": "周額度", "keyQuotaReset": "已重置密鑰額度", - "description": "清零所選週期的已用金額,下次使用時重新確定重置日期", + "description": "所選週期的已用金額歸零,新週期從現在開始", "targetKey": "目標密鑰", "resetScope": "重置範圍", "currentlyUsed": "當前已用", @@ -93,9 +107,9 @@ "editor": { "description": "配置密鑰信息、分組與使用限制", "namePlaceholder": "例如:生產環境", - "labelOptional": "標籤(可選)", + "label": "標籤", "forExampleBackendService": "例如:後端服務", - "customKeyOptional": "自定義 API密鑰(可選)", + "customKey": "自定義 API 密鑰", "keyPlaceholder": "留空自動生成", "upstreamIdentity": "上游身份", "dailyLimit": "日限額", diff --git a/frontend/src/i18n/locales/zh-Hant/plugins.json b/frontend/src/i18n/locales/zh-Hant/plugins.json index f8f476787..e29b76284 100644 --- a/frontend/src/i18n/locales/zh-Hant/plugins.json +++ b/frontend/src/i18n/locales/zh-Hant/plugins.json @@ -235,9 +235,9 @@ "allowPrereleaseLabel": "允許查詢預發行版", "verificationSummary": "校驗摘要", "digestHelpTitle": "校驗摘要說明", - "digestHelp": "可選,填寫發佈者提供的 64 位 SHA-256 十六進制摘要,用於覈對下載內容", + "digestHelp": "填寫發佈者提供的 64 位 SHA-256 十六進制摘要,用於覈對下載內容", "shaChecksum": "SHA-256 校驗摘要", - "optionalSha": "可選,SHA-256", + "digestPlaceholder": "64 位十六進位摘要", "versionFound": "已找到版本", "preRelease": "預發行版", "thereIsNoTarGzOrTgz": "此版本沒有 tar.gz 或 tgz 插件包", diff --git a/frontend/src/views/accounts/components/account-create-modal/AccountSetupFields.vue b/frontend/src/views/accounts/components/account-create-modal/AccountSetupFields.vue index 4f08cb7de..c143c5423 100644 --- a/frontend/src/views/accounts/components/account-create-modal/AccountSetupFields.vue +++ b/frontend/src/views/accounts/components/account-create-modal/AccountSetupFields.vue @@ -54,7 +54,7 @@ const name = computed({ :preserve-proxy="false" :disabled="disabled" :name-placeholder="t('accounts.onboarding.namePlaceholder')" - :notes-placeholder="t('accounts.onboarding.maximumWordsOptional')" + :notes-placeholder="t('accounts.onboarding.notesPlaceholder')" /> diff --git a/frontend/src/views/keys/components/ApiKeyFormModal.vue b/frontend/src/views/keys/components/ApiKeyFormModal.vue index e65972eda..c8842fab8 100644 --- a/frontend/src/views/keys/components/ApiKeyFormModal.vue +++ b/frontend/src/views/keys/components/ApiKeyFormModal.vue @@ -17,6 +17,7 @@ import InstallationSeedField from '@/providers/openai/request-profile/Installati import { useApiKeyFormRules } from '../composables/useApiKeyFormRules' import ApiKeyLimitFields from './ApiKeyLimitFields.vue' import ApiKeyPeerSharingField from './ApiKeyPeerSharingField.vue' +import ApiKeyValidityFields from './ApiKeyValidityFields.vue' const props = defineProps<{ groups: AccountGroupRef[] @@ -102,26 +103,31 @@ function updatePeerSharing(key: keyof ApiKeyPeerSharing, value: boolean) { @update:model-value="updateForm('name', $event)" /> - + +