feat(api-key): 增加 API Key 创建数量与频率限制

- 新增 api_key_create.max_active_per_user(默认 200)与
  api_key_create.max_per_user_per_hour(默认 20),0 表示不限制
- 创建频率按固定一小时窗口统计,自定义与自动生成的 Key 统一计入
- 创建计数独立于 Key 生命周期,删除或修改 Key 不再重置计数
- 移除不再使用的 DeleteCreateAttemptCount 缓存方法
This commit is contained in:
shaw committed 2026-09-30 13:44:02 +08:00
1 parent a0f41f95a0
commit 9ecb340822
12 files changed
+302 -48

No files matched your search

+37 -8
View File
@@ -30,6 +30,8 @@ var (
ErrAPIKeyTooShort = infraerrors.BadRequest("API_KEY_TOO_SHORT", "api key must be at least 16 characters")
ErrAPIKeyInvalidChars = infraerrors.BadRequest("API_KEY_INVALID_CHARS", "api key can only contain letters, numbers, underscores, and hyphens")
ErrAPIKeyRateLimited = infraerrors.TooManyRequests("API_KEY_RATE_LIMITED", "too many failed attempts, please try again later")
ErrAPIKeyCreateLimited = infraerrors.TooManyRequests("API_KEY_CREATE_RATE_LIMITED", "too many api keys created recently, please try again later")
ErrAPIKeyCountExceeded = infraerrors.Forbidden("API_KEY_COUNT_EXCEEDED", "api key count limit reached, please delete unused keys first")
ErrAPIKeyAuthOverloaded = infraerrors.ServiceUnavailable("API_KEY_AUTH_OVERLOADED", "api key authentication is temporarily overloaded")
ErrInvalidIPPattern = infraerrors.BadRequest("INVALID_IP_PATTERN", "invalid IP or CIDR pattern")
// ErrAPIKeyExpired = infraerrors.Forbidden("API_KEY_EXPIRED", "api key has expired")
@@ -48,6 +50,7 @@ const (
defaultAuthLookupConcurrency = 64
defaultNegativeAuthCacheSize = 16384
apiKeyMaxErrorsPerHour = 20
apiKeyCreateCountWindow = time.Hour
apiKeyLastUsedMinTouch = 30 * time.Second
apiKeySortCurrentConcurrency = "current_concurrency"
// DB 写失败后的短退避,避免请求路径持续同步重试造成写风暴与高延迟。
@@ -172,7 +175,7 @@ type APIKeyQuotaUsageState struct {
type APIKeyCache interface {
GetCreateAttemptCount(ctx context.Context, userID int64) (int, error)
IncrementCreateAttemptCount(ctx context.Context, userID int64) error
DeleteCreateAttemptCount(ctx context.Context, userID int64) error
IncrementCreateCount(ctx context.Context, userID int64, window time.Duration) (int64, error)
IncrementDailyUsage(ctx context.Context, apiKey string) error
SetDailyUsageExpiry(ctx context.Context, apiKey string, ttl time.Duration) error
@@ -435,6 +438,34 @@ func (s *APIKeyService) checkAPIKeyRateLimit(ctx context.Context, userID int64)
return nil
}
// checkAPIKeyCreateLimits 校验创建 API Key 的防滥用限制(对自定义与自动生成的 Key 一视同仁)。
// 数量上限按未删除的 Key 计;创建次数按固定窗口累计,删除 Key 不返还次数,
// 以阻断"删除后反复新建"的循环。Redis 出错时与自定义 Key 限流一致,不阻止用户操作。
func (s *APIKeyService) checkAPIKeyCreateLimits(ctx context.Context, userID int64) error {
if s.cfg == nil {
return nil
}
if maxActive := s.cfg.APIKeyCreate.MaxActivePerUser; maxActive > 0 {
count, err := s.apiKeyRepo.CountByUserID(ctx, userID)
if err != nil {
return fmt.Errorf("count api keys: %w", err)
}
if count >= int64(maxActive) {
return ErrAPIKeyCountExceeded
}
}
if maxPerHour := s.cfg.APIKeyCreate.MaxPerUserPerHour; maxPerHour > 0 && s.cache != nil {
count, err := s.cache.IncrementCreateCount(ctx, userID, apiKeyCreateCountWindow)
if err != nil {
return nil
}
if count > int64(maxPerHour) {
return ErrAPIKeyCreateLimited
}
}
return nil
}
// incrementAPIKeyErrorCount 增加用户创建自定义Key的错误计数
func (s *APIKeyService) incrementAPIKeyErrorCount(ctx context.Context, userID int64) {
if s.cache == nil {
@@ -530,6 +561,10 @@ func (s *APIKeyService) Create(ctx context.Context, userID int64, req CreateAPIK
}
}
if err := s.checkAPIKeyCreateLimits(ctx, userID); err != nil {
return nil, err
}
// 创建API Key记录
apiKey := &APIKey{
UserID: userID,
@@ -820,10 +855,6 @@ func (s *APIKeyService) Update(ctx context.Context, id int64, userID int64, req
if req.Status != nil {
apiKey.Status = *req.Status
fields.Status = true
// 如果状态改变,清除Redis缓存
if s.cache != nil {
_ = s.cache.DeleteCreateAttemptCount(ctx, apiKey.UserID)
}
}
// Update quota fields
@@ -931,9 +962,7 @@ func (s *APIKeyService) Delete(ctx context.Context, id int64, userID int64) erro
}
// 删除成功后再清理缓存,避免"缓存已清但删除失败"的竞态。
if s.cache != nil {
_ = s.cache.DeleteCreateAttemptCount(ctx, userID)
}
// 注意:不清零创建相关计数,否则"删除后反复新建"即可绕过创建限流。
s.InvalidateAuthCacheByKey(ctx, key)
s.lastUsedTouchL1.Delete(id)