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

@@ -0,0 +1,43 @@
package repository
import (
"context"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
)
func TestAPIKeyCacheIncrementCreateCountUsesFixedWindow(t *testing.T) {
server := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: server.Addr()})
defer func() { _ = client.Close() }()
cache := NewAPIKeyCache(client)
ctx := context.Background()
key := apiKeyCreateCountKey(7)
count, err := cache.IncrementCreateCount(ctx, 7, time.Hour)
require.NoError(t, err)
require.Equal(t, int64(1), count)
require.Equal(t, time.Hour, server.TTL(key))
// 后续创建不得延长窗口,否则持续创建会让计数永不过期。
server.FastForward(40 * time.Minute)
count, err = cache.IncrementCreateCount(ctx, 7, time.Hour)
require.NoError(t, err)
require.Equal(t, int64(2), count)
require.Equal(t, 20*time.Minute, server.TTL(key))
// 其他用户独立计数。
count, err = cache.IncrementCreateCount(ctx, 8, time.Hour)
require.NoError(t, err)
require.Equal(t, int64(1), count)
// 窗口到期后重新计数。
server.FastForward(21 * time.Minute)
count, err = cache.IncrementCreateCount(ctx, 7, time.Hour)
require.NoError(t, err)
require.Equal(t, int64(1), count)
}