Merge pull request #9225 from debug-zhang/fix/3210-api-key-existence-oracle

fix(security): hide custom api key existence in creation errors
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-12-04 15:19:40 +08:00
commit 725b235f97
2 files changed
+192 -8

No files matched your search

+29 -8
View File
@@ -4,8 +4,10 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"html"
"log/slog"
"math"
"sort"
"strconv"
@@ -25,9 +27,16 @@ import (
)
var (
ErrAPIKeyNotFound = infraerrors.NotFound("API_KEY_NOT_FOUND", "api key not found")
ErrGroupNotAllowed = infraerrors.Forbidden("GROUP_NOT_ALLOWED", "user is not allowed to bind this group")
ErrAPIKeyExists = infraerrors.Conflict("API_KEY_EXISTS", "api key already exists")
ErrAPIKeyNotFound = infraerrors.NotFound("API_KEY_NOT_FOUND", "api key not found")
ErrGroupNotAllowed = infraerrors.Forbidden("GROUP_NOT_ALLOWED", "user is not allowed to bind this group")
// ErrAPIKeyExists is internal only: it may describe a unique-constraint race
// or an existing key owned by another user. It must never reach API clients,
// otherwise key creation becomes an API key existence oracle.
ErrAPIKeyExists = infraerrors.Conflict("API_KEY_EXISTS", "api key already exists")
// ErrAPIKeyUnavailable is the single client-facing rejection for custom keys.
// It intentionally does not distinguish a malformed key from a collision with
// an existing key, so callers cannot probe which keys exist.
ErrAPIKeyUnavailable = infraerrors.BadRequest("API_KEY_UNAVAILABLE", "unable to use this key, please choose another")
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")
@@ -530,17 +539,21 @@ func (s *APIKeyService) Create(ctx context.Context, userID int64, req CreateAPIK
}
var key string
isCustomKey := req.CustomKey != nil && *req.CustomKey != ""
// 判断是否使用自定义Key
if req.CustomKey != nil && *req.CustomKey != "" {
if isCustomKey {
// 检查限流(仅对自定义key进行限流)
if err := s.checkAPIKeyRateLimit(ctx, userID); err != nil {
return nil, err
}
// 验证自定义Key格式
// 验证自定义Key格式。具体的失败原因只写入服务端日志:
// 客户端错误必须与"Key 已被占用"完全一致,否则创建接口会变成
// API Key 存在性探测器。
if err := s.ValidateCustomKey(*req.CustomKey); err != nil {
return nil, err
slog.Info("custom_api_key_rejected", "user_id", userID, "reason", "invalid_format", "detail", err)
return nil, ErrAPIKeyUnavailable
}
// 检查Key是否已存在
@@ -549,9 +562,10 @@ func (s *APIKeyService) Create(ctx context.Context, userID int64, req CreateAPIK
return nil, fmt.Errorf("check key exists: %w", err)
}
if exists {
// Key已存在,增加错误计数
// Key已存在,增加错误计数;响应与格式错误保持一致,不暴露存在性。
s.incrementAPIKeyErrorCount(ctx, userID)
return nil, ErrAPIKeyExists
slog.Warn("custom_api_key_rejected", "user_id", userID, "reason", "already_exists")
return nil, ErrAPIKeyUnavailable
}
key = *req.CustomKey
@@ -591,6 +605,13 @@ func (s *APIKeyService) Create(ctx context.Context, userID int64, req CreateAPIK
}
if err := s.apiKeyRepo.Create(ctx, apiKey); err != nil {
// 并发创建可能在校验之后抢到同一个 Key(唯一约束冲突),
// 对外仍返回同一个通用错误,避免泄露存在性。
if isCustomKey && errors.Is(err, ErrAPIKeyExists) {
s.incrementAPIKeyErrorCount(ctx, userID)
slog.Warn("custom_api_key_rejected", "user_id", userID, "reason", "already_exists")
return nil, ErrAPIKeyUnavailable
}
return nil, fmt.Errorf("create api key: %w", err)
}
@@ -0,0 +1,163 @@
//go:build unit
package service
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/stretchr/testify/require"
)
// customKeyRepoStub 覆盖创建自定义 Key 所需的仓库方法,其余方法沿用
// apiKeyRepoStub(未配置 cfg 时不会被调用)。
type customKeyRepoStub struct {
*apiKeyRepoStub
exists bool
existsErr error
createErr error
created []*APIKey
existsKeys []string
}
func (s *customKeyRepoStub) ExistsByKey(ctx context.Context, key string) (bool, error) {
s.existsKeys = append(s.existsKeys, key)
return s.exists, s.existsErr
}
func (s *customKeyRepoStub) Create(ctx context.Context, key *APIKey) error {
if s.createErr != nil {
return s.createErr
}
s.created = append(s.created, key)
return nil
}
type countingCreateAttemptsCache struct {
*apiKeyCacheStub
attempts int
}
func (s *countingCreateAttemptsCache) IncrementCreateAttemptCount(ctx context.Context, userID int64) error {
s.attempts++
return nil
}
func newCustomKeyService(repo *customKeyRepoStub, cache APIKeyCache, cfg *config.Config) *APIKeyService {
return &APIKeyService{
apiKeyRepo: repo,
userRepo: &userRepoStub{user: &User{ID: 7}},
cache: cache,
cfg: cfg,
}
}
// 已存在的 Key(可能属于他人)必须返回与格式错误完全一致的通用错误,
// 响应体不得出现 API_KEY_EXISTS / "already exists"。
func TestAPIKeyServiceCreate_CustomKeyCollisionReturnsGenericError(t *testing.T) {
repo := &customKeyRepoStub{apiKeyRepoStub: &apiKeyRepoStub{}, exists: true}
cache := &countingCreateAttemptsCache{apiKeyCacheStub: &apiKeyCacheStub{}}
svc := newCustomKeyService(repo, cache, nil)
custom := "sk-victim-key-0123456789"
_, err := svc.Create(context.Background(), 7, CreateAPIKeyRequest{Name: "k", CustomKey: &custom})
require.Error(t, err)
require.ErrorIs(t, err, ErrAPIKeyUnavailable)
require.Equal(t, 1, cache.attempts, "collision should still count towards the custom key rate limit")
require.Empty(t, repo.created, "a colliding custom key must not be created")
statusCode, body := infraerrors.ToHTTP(err)
require.Equal(t, 400, statusCode)
require.Equal(t, "API_KEY_UNAVAILABLE", body.Reason)
require.True(t, strings.Contains(strings.ToLower(body.Message), "unable to use this key"))
raw, marshalErr := json.Marshal(body)
require.NoError(t, marshalErr)
require.NotContains(t, string(raw), "API_KEY_EXISTS")
require.NotContains(t, strings.ToLower(string(raw)), "already exists")
}
// 格式非法与已存在两种情况必须返回同一个错误(同 code、同 reason、同 message),
// 客户端无法据此判断 Key 是否存在。
func TestAPIKeyServiceCreate_CustomKeyFailuresAreIndistinguishable(t *testing.T) {
tests := []struct {
name string
key string
exists bool
}{
{name: "too short", key: "sk-short", exists: false},
{name: "invalid characters", key: "sk-invalid key-0123456789", exists: false},
{name: "already taken", key: "sk-taken-key-0123456789", exists: true},
}
var first *infraerrors.ApplicationError
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
repo := &customKeyRepoStub{apiKeyRepoStub: &apiKeyRepoStub{}, exists: tt.exists}
svc := newCustomKeyService(repo, nil, nil)
key := tt.key
_, err := svc.Create(context.Background(), 7, CreateAPIKeyRequest{Name: "k", CustomKey: &key})
require.ErrorIs(t, err, ErrAPIKeyUnavailable)
require.False(t, errors.Is(err, ErrAPIKeyTooShort))
require.False(t, errors.Is(err, ErrAPIKeyInvalidChars))
appErr := infraerrors.FromError(err)
if first == nil {
first = appErr
return
}
require.Equal(t, first.Code, appErr.Code)
require.Equal(t, first.Reason, appErr.Reason)
require.Equal(t, first.Message, appErr.Message)
})
}
}
// 正常创建不受影响(软删除的 Key 已被 tombstone,ExistsByKey 返回 false)。
func TestAPIKeyServiceCreate_CustomKeyCreatesNormally(t *testing.T) {
repo := &customKeyRepoStub{apiKeyRepoStub: &apiKeyRepoStub{}}
cache := &countingCreateAttemptsCache{apiKeyCacheStub: &apiKeyCacheStub{}}
svc := newCustomKeyService(repo, cache, &config.Config{})
custom := "sk-reused-after-delete-0123456789"
created, err := svc.Create(context.Background(), 7, CreateAPIKeyRequest{Name: "k", CustomKey: &custom})
require.NoError(t, err)
require.Equal(t, custom, created.Key)
require.Len(t, repo.created, 1)
require.Equal(t, custom, repo.created[0].Key)
require.Zero(t, cache.attempts)
}
// ExistsByKey 与插入之间的唯一约束竞态(或其它插入冲突)也必须映射为通用错误。
func TestAPIKeyServiceCreate_CustomKeyInsertConflictReturnsGenericError(t *testing.T) {
repo := &customKeyRepoStub{
apiKeyRepoStub: &apiKeyRepoStub{},
createErr: ErrAPIKeyExists,
}
svc := newCustomKeyService(repo, nil, nil)
custom := "sk-race-key-0123456789"
_, err := svc.Create(context.Background(), 7, CreateAPIKeyRequest{Name: "k", CustomKey: &custom})
require.ErrorIs(t, err, ErrAPIKeyUnavailable)
require.NotErrorIs(t, err, ErrAPIKeyExists)
_, body := infraerrors.ToHTTP(err)
require.Equal(t, "API_KEY_UNAVAILABLE", body.Reason)
}
// 系统生成 Key 的逻辑保持不变。
func TestAPIKeyServiceCreate_GeneratedKeyStillWorks(t *testing.T) {
repo := &customKeyRepoStub{apiKeyRepoStub: &apiKeyRepoStub{}}
svc := newCustomKeyService(repo, nil, &config.Config{})
created, err := svc.Create(context.Background(), 7, CreateAPIKeyRequest{Name: "k"})
require.NoError(t, err)
require.NotEmpty(t, created.Key)
require.Len(t, repo.created, 1)
}