feat(keys): support validity periods and start budgets at manual reset (#787)

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
This commit is contained in:
Zyy
2026-11-28 15:59:49 +08:00
committed by GitHub
co-authored by Zyy
parent 4c49ddb479
commit 9684b9d00f
48 changed files with 590 additions and 140 deletions
@@ -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<Utc>,
}
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<PlaintextClientApiKey>,
@@ -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<gateway_core::policy::ClientKeyValidity>,
pub peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
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<Utc>,
) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
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 {
@@ -337,6 +337,11 @@ impl ClientKeyService for DefaultClientKeyService {
context: &MutationContext,
command: CreateClientKey,
) -> Result<CreatedClientKey, AdminError> {
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<ClientKeyMutation, AdminError> {
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())?;
}
@@ -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);
};
@@ -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);
@@ -85,6 +85,7 @@ impl PluginResourceAccess for DefaultPluginResourceAccess {
resource_key,
groups,
NewClientKey {
validity: Default::default(),
peer_sharing: Default::default(),
id,
name: command.name,
@@ -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,
@@ -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<gateway_core::policy::ClientKeyValidity>,
peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
#[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<String>,
expires_at_display: Option<String>,
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::<ProviderRequestProfileOverrides>();
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,
@@ -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(),
@@ -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(),
@@ -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(),
+59 -4
View File
@@ -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<chrono::DateTime<chrono::Utc>>,
pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
}
#[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<chrono::Utc>) -> 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<String>,
defaults: Arc<ClientSettings>,
@@ -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<String>) -> 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",
})
}
}
@@ -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<ProviderKind, BTreeMap<String, BTreeSet<Pro
/// Store 读取到的一个启用 Client API Key 策略事实
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotClientPolicyFacts {
validity: ClientKeyValidity,
peer_sharing: ClientPeerSharing,
name_snapshot: Option<String>,
request_profiles: BTreeMap<ProviderKind, crate::account::OpaqueProviderData>,
@@ -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<String>) -> 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),
);
}
@@ -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());
}
@@ -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(),
@@ -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(),
@@ -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::<Vec<_>>();
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<Decimal, GatewayError> {
row.get::<String, _>(field)
.parse()
@@ -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<String>,
pub request_profiles: std::collections::BTreeMap<
@@ -76,6 +79,7 @@ impl ClientApiKeySnapshot {
requests_per_minute: i64,
) -> StoreResult<Self> {
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<ProviderKind, OpaqueProviderData>,
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<ProviderKind, OpaqueProviderData>,
pub id: String,
@@ -322,6 +328,7 @@ impl NewClientApiKey {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdateClientApiKeyDetails {
pub validity: Option<ClientKeyValidity>,
pub peer_sharing: Option<ClientPeerSharing>,
pub request_profile_override_updates: BTreeMap<ProviderKind, Option<OpaqueProviderData>>,
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::<Postgres>::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<bool> {
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<Admin
fn admin_client_key_record(record: ClientApiKeyRecord) -> AdminStoreResult<AdminClientKeyRecord> {
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<ClientApiK
.map_err(|source| invalid("invalid groups").with_source(source))?;
Ok(
ClientApiKeyRecord {
validity: ClientKeyValidity {
starts_at: row
.try_get("starts_at")
.map_err(|source| invalid("invalid start time").with_source(source))?,
expires_at: row
.try_get("expires_at")
.map_err(|source| invalid("invalid expiry time").with_source(source))?,
},
peer_sharing: row
.try_get::<sqlx::types::Json<ClientPeerSharing>, _>("peer_sharing_json")
.map_err(|source| invalid("invalid peer sharing").with_source(source))?
@@ -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(),
@@ -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<BTreeMap<String, serde_json::Map<String, serde_json::Value>>>,
String,
sqlx::types::Json<gateway_core::policy::ClientPeerSharing>,
Option<chrono::DateTime<chrono::Utc>>,
Option<chrono::DateTime<chrono::Utc>>,
),
>(
"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()
@@ -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<AccountGroupId>) -> 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(),
@@ -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()),
@@ -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<Option<OpaqueProviderData>>| UpdateClientKey {
validity: Default::default(),
peer_sharing: None,
id: id.clone(),
name: "profile".to_owned(),
@@ -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(),
+1
View File
@@ -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
@@ -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)
);
+10 -5
View File
@@ -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 连接的下一次请求同样生效,已开始的请求保持原有快照
+4 -4
View File
@@ -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 负责签发、身份校验、轮换、不活动期限和最长有效期。
+11 -1
View File
@@ -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<Omit<ApiKeyWriteParam, 'name' | 'label' | 'peerSharing'>> {
export interface ApiKeyBatchChanges extends Partial<Omit<ApiKeyWriteParam, 'name' | 'label' | 'peerSharing' | 'validity'>> {
enabled?: boolean
peerSharing?: Partial<ApiKeyPeerSharing>
providerRequestProfileOverrides?: ProviderRequestProfileUpdates
+2 -2
View File
@@ -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",
+17 -3
View File
@@ -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",
+2 -2
View File
@@ -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",
@@ -353,7 +353,7 @@
"batchImport": "批量导入",
"selectAccountPlatform": "选择账号平台",
"accountPlatform": "账号平台",
"maximumWordsOptional": "最多 500 字,可不填",
"notesPlaceholder": "最多 500 字",
"namePlaceholder": "留空保留原名称,仅单账号导入生效",
"copyAccount": "复制账号",
"accountCopied": "账号已复制",
+17 -3
View File
@@ -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": "日限额",
@@ -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 插件包",
@@ -353,7 +353,7 @@
"batchImport": "批量導入",
"selectAccountPlatform": "選擇賬號平臺",
"accountPlatform": "賬號平臺",
"maximumWordsOptional": "最多 500 字,可不填",
"notesPlaceholder": "最多 500 字",
"namePlaceholder": "留空保留原名稱,僅單賬號導入生效",
"copyAccount": "複製賬號",
"accountCopied": "賬號已複製",
+17 -3
View File
@@ -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": "日限額",
@@ -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 插件包",
@@ -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')"
/>
</div>
</template>
@@ -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)"
/>
</ZFormItem>
<ZFormItem :label="t('keys.editor.labelOptional')">
<ZFormItem :label="t('keys.editor.label')">
<ZInput
:model-value="form.label" :aria-label="t('keys.editor.labelOptional')"
:model-value="form.label" :aria-label="t('keys.editor.label')"
:placeholder="t('keys.editor.forExampleBackendService')"
:disabled="saving"
@update:model-value="updateForm('label', $event)"
/>
</ZFormItem>
<ApiKeyValidityFields
class="col-span-full min-w-0"
:model-value="form.validity" :disabled="saving"
@update:model-value="updateForm('validity', $event)"
/>
</div>
<ZFormItem
v-if="!editing"
prop="customKey"
:label="t('keys.editor.customKeyOptional')"
:label="t('keys.editor.customKey')"
>
<ZInput
:model-value="form.customKey" type="password"
autocomplete="new-password"
:spellcheck="false"
:aria-label="t('keys.editor.customKeyOptional')"
:aria-label="t('keys.editor.customKey')"
:placeholder="t('keys.editor.keyPlaceholder')"
:disabled="saving"
@update:model-value="updateForm('customKey', $event)"
@@ -49,7 +49,7 @@ function update(field: typeof fields.value[number], value: string) {
</script>
<template>
<div class="grid gap-6 sm:grid-cols-2">
<div class="grid grid-cols-2 gap-4 sm:grid-cols-4">
<ZFormItem v-for="field in fields" :key="field.key" :prop="field.key" :label="field.label">
<template v-if="mixed?.includes(field.key)" #label-extra>
<span class="text-z-xs text-z-text-secondary">{{ t('keys.batch.mixed') }}</span>
@@ -1,13 +1,18 @@
<script setup lang="ts">
import type { ApiKeyPeerSharing } from '@/api'
import { ZCheckbox, ZFormItem, ZSwitch } from '@codex-proxy/ui'
import { ZCheckbox, ZFormItem, ZSegmented } from '@codex-proxy/ui'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import HelpPopover from '@/components/HelpPopover.vue'
defineProps<{ sharing: Partial<ApiKeyPeerSharing>, disabled: boolean }>()
const props = defineProps<{ sharing: Partial<ApiKeyPeerSharing>, disabled: boolean }>()
const emit = defineEmits<{ change: [field: keyof ApiKeyPeerSharing, value: boolean] }>()
const { t } = useI18n({ useScope: 'global' })
const mode = computed(() => {
if (props.sharing.enabled === undefined)
return ''
return props.sharing.enabled ? 'on' : 'off'
})
const permissions = computed(() => ({
sharePool: t('keys.editor.sharePool'),
shareQuota: t('keys.editor.shareQuota'),
@@ -21,9 +26,13 @@ const permissions = computed(() => ({
<HelpPopover :label="t('keys.editor.peerSharing')" :content="t('keys.editor.peerSharingHelp')" />
</template>
<div class="flex flex-wrap items-center gap-x-5 gap-y-3">
<ZSwitch
:model-value="sharing.enabled === true" :aria-label="t('keys.editor.peerSharing')" :disabled="disabled"
@update:model-value="emit('change', 'enabled', $event)"
<ZSegmented
:options="[
{ label: t('common.values.off'), value: 'off' },
{ label: t('common.values.on'), value: 'on' },
]"
:model-value="mode" :aria-label="t('keys.editor.peerSharing')" :disabled="disabled"
@update:model-value="emit('change', 'enabled', $event === 'on')"
/>
<span v-if="sharing.enabled === undefined" class="text-z-sm text-z-text-secondary">{{ t('keys.batch.partiallyEnabled') }}</span>
<template v-if="sharing.enabled">
@@ -1,23 +1,77 @@
<script setup lang="ts">
import type { ApiKey } from '@/api'
import { ZPopover, ZTag } from '@codex-proxy/ui'
import { ChevronDown } from '@lucide/vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{
apiKey: {
enabled: boolean
}
}>()
const props = defineProps<{ apiKey: ApiKey }>()
const { t } = useI18n({ useScope: 'global' })
const badge = computed(() => {
if (!props.apiKey.enabled) {
return {
label: t('common.status.disabled'),
tone: 'default',
} as const
}
switch (props.apiKey.validityStatus) {
case 'scheduled': return {
label: t('keys.validity.scheduled'),
tone: 'info',
} as const
case 'expired': return {
label: t('keys.validity.expired'),
tone: 'default',
} as const
default: return {
label: props.apiKey.validity.expiresAt
? t('keys.validity.timeLimited')
: t('keys.validity.noExpiry'),
tone: 'success',
} as const
}
})
</script>
<template>
<span
class="inline-flex h-6 min-w-14 items-center justify-center rounded-full px-2 text-z-sm leading-none font-bold"
:class="{
'bg-z-success-container text-z-success-on-container': apiKey.enabled,
'bg-z-fill-quaternary text-z-text-secondary': !apiKey.enabled,
}"
>
{{ apiKey.enabled ? t('common.status.enabled') : t('common.status.disabled') }}
</span>
<ZTag v-if="!apiKey.validity.expiresAt" :type="badge.tone" round>
{{ badge.label }}
</ZTag>
<ZPopover v-else trigger="hover-click" placement="top" :hover-delay="240">
<template #reference="{ id, open }">
<button
type="button"
class="inline-flex cursor-pointer items-center rounded-full border-0 bg-transparent p-0 leading-none outline-none focus-visible:ring-2 focus-visible:ring-z-control-outline"
:aria-controls="open ? id : undefined" :aria-expanded="open" aria-haspopup="dialog"
>
<ZTag :type="badge.tone" round>
<span class="flex items-center gap-1 whitespace-nowrap">
{{ badge.label }}
<ChevronDown class="size-3" aria-hidden="true" />
</span>
</ZTag>
</button>
</template>
<section role="dialog" :aria-label="t('keys.validity.label')" class="grid max-w-[calc(100vw-1rem)] gap-2 px-3 py-2.5 text-z-sm">
<h3 class="m-0 text-z-sm font-emphasis text-z-text">
{{ t('keys.validity.label') }}
</h3>
<dl class="m-0 grid grid-cols-[auto_auto] items-baseline gap-x-4 gap-y-1">
<dt class="text-z-text-secondary">
{{ t('keys.validity.startsAt') }}
</dt>
<dd class="m-0 text-right tabular-nums">
<time :datetime="apiKey.validity.startsAt ?? undefined">{{ apiKey.startsAtDisplay }}</time>
</dd>
<dt class="text-z-text-secondary">
{{ t('keys.validity.expiresAt') }}
</dt>
<dd class="m-0 text-right tabular-nums">
<time :datetime="apiKey.validity.expiresAt">{{ apiKey.expiresAtDisplay }}</time>
</dd>
</dl>
</section>
</ZPopover>
</template>
@@ -0,0 +1,65 @@
<script setup lang="ts">
import type { DatePickerValue } from '@codex-proxy/ui'
import type { ApiKeyValidity } from '@/api'
import { ZDatePicker, ZFormItem } from '@codex-proxy/ui'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{ disabled: boolean }>()
const validity = defineModel<ApiKeyValidity>({ required: true })
const { t } = useI18n({ useScope: 'global' })
const range = computed(() => {
const { startsAt, expiresAt } = validity.value
return startsAt && expiresAt
? [
new Date(startsAt),
new Date(expiresAt),
]
: null
})
function nextDays(days: number) {
const start = new Date()
start.setHours(0, 0, 0, 0)
const end = new Date(start)
end.setDate(start.getDate() + days)
return [start, end]
}
const shortcuts = computed(() => [
{
text: t('keys.validity.week'),
value: () => nextDays(7),
},
{
text: t('keys.validity.month'),
value: () => nextDays(30),
},
])
function setRange(value: DatePickerValue) {
const [start, end] = Array.isArray(value)
? value
: []
validity.value = {
startsAt: start instanceof Date
? start.toISOString()
: null,
expiresAt: end instanceof Date
? end.toISOString()
: null,
}
}
</script>
<template>
<ZFormItem prop="validity" :label="t('keys.validity.label')">
<ZDatePicker
type="datetimerange" single-panel class="w-full" :disabled="disabled"
:model-value="range" :shortcuts="shortcuts" :aria-label="t('keys.validity.label')"
:start-placeholder="t('keys.validity.startDate')" :end-placeholder="t('keys.validity.endDate')"
@update:model-value="setRange"
/>
</ZFormItem>
</template>
@@ -1,4 +1,4 @@
import type { ApiKey, ApiKeyPeerSharing, ProviderRequestProfiles } from '@/api'
import type { ApiKey, ApiKeyPeerSharing, ApiKeyValidity, ProviderRequestProfiles } from '@/api'
import { cloneDeep } from 'es-toolkit'
import { ref, shallowRef } from 'vue'
import { createApiKey, updateApiKey } from '@/api'
@@ -9,6 +9,7 @@ import { notification as ZNotification } from '@/plugins/notification'
import { decodeKeyProfiles, encodeKeyProfiles } from '@/providers/openai/request-profile/installationSeed'
export interface ApiKeyFormValue {
validity: ApiKeyValidity
peerSharing: ApiKeyPeerSharing
providerRequestProfileOverrides: ProviderRequestProfiles
installationSeed: string
@@ -67,6 +68,7 @@ export function useApiKeyEditor(options: {
await savingKeyAction.run(
async () => {
const payload = {
validity: { ...form.value.validity },
peerSharing: { ...form.value.peerSharing },
name: form.value.name.trim(),
label: form.value.label.trim() || null,
@@ -138,6 +140,7 @@ export function useApiKeyEditor(options: {
function emptyForm(): ApiKeyFormValue {
return {
validity: { startsAt: null, expiresAt: null },
peerSharing: {
enabled: false,
sharePool: false,
@@ -166,6 +169,7 @@ function limitInputValue(limit: string | number) {
export function apiKeyFormValue(key: ApiKey): ApiKeyFormValue {
const { profiles, installationSeed } = decodeKeyProfiles(cloneDeep(key.providerRequestProfileOverrides))
return {
validity: { ...key.validity },
peerSharing: { ...key.peerSharing },
providerRequestProfileOverrides: profiles,
installationSeed,
@@ -48,6 +48,15 @@ export function useApiKeyFormRules(form: () => ApiKeyFormValue) {
const { t } = useI18n({ useScope: 'global' })
const limitRules = useApiKeyLimitRules()
return computed<FormRules<ApiKeyFormValue>>(() => ({
validity: {
type: 'object',
validator: () => {
const { startsAt, expiresAt } = form().validity
return !startsAt || !expiresAt || Date.parse(startsAt) < Date.parse(expiresAt)
},
message: t('keys.validity.invalidRange'),
trigger: ['change'],
},
groupIds: {
type: 'array',
validator: (_rule, value) => !form().peerSharing.enabled || (Array.isArray(value) && value.length > 0),
+1 -1
View File
@@ -41,7 +41,7 @@ export const apiKeyColumns = computed(() => (defineTableColumns<ApiKey>([
key: 'limits',
label: t('keys.fields.requestLimits'),
kind: 'text',
size: 'xl',
size: 'lg',
},
{
key: 'createdAtDisplay',
+3 -3
View File
@@ -216,17 +216,17 @@ watch([showFormModal, showBatchEdit], ([editor, batch]) => {
<ApiKeyBudgetCell :api-key="row" />
</template>
<template #limits="{ row }">
<dl class="m-0 grid grid-cols-[max-content_max-content] gap-x-2 gap-y-1 text-xs tabular-nums">
<dl class="m-0 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-2 gap-y-1 text-xs tabular-nums">
<dt class="text-right text-z-text-tertiary">
{{ t('keys.page.concurrency') }}
</dt>
<dd class="m-0 whitespace-nowrap text-z-text">
<dd class="m-0 break-all whitespace-normal text-z-text">
{{ row.maxConcurrency || '∞' }}
</dd>
<dt class="text-right text-z-text-tertiary">
RPM
</dt>
<dd class="m-0 whitespace-nowrap text-z-text">
<dd class="m-0 break-all whitespace-normal text-z-text">
{{ row.requestsPerMinute || '∞' }}
</dd>
</dl>
@@ -583,7 +583,7 @@ watch(
{{ t('plugins.installation.digestHelp') }}
</PluginHelpPopover>
</template>
<ZInput v-model="connectionForm.sha256" :disabled="busy" maxlength="64" :aria-label="t('plugins.installation.shaChecksum')" :placeholder="t('plugins.installation.optionalSha')" class="font-mono [&_input::placeholder]:font-normal" />
<ZInput v-model="connectionForm.sha256" :disabled="busy" maxlength="64" :aria-label="t('plugins.installation.shaChecksum')" :placeholder="t('plugins.installation.digestPlaceholder')" class="font-mono [&_input::placeholder]:font-normal" />
</ZFormItem>
<PluginSourceProxyField v-model="connectionForm.outboundProxyId" :disabled="busy" />
</div>