fix(api-keys): harden scoped key auth after code review

Revoke existing keys on reset, unify scope enforcement, default empty
scopes to read-only, map API key scopes to tenant roles, and remove dead
key-generation helpers left over from the tenant api_key column removal.
This commit is contained in:
wizardchen
2026-07-05 10:40:49 +08:00
committed by lyingbug
parent 505bc7ddec
commit 3f516d7f31
17 changed files with 231 additions and 203 deletions
@@ -62,6 +62,14 @@ func (r *tenantAPIKeyRepository) RevokeAPIKey(ctx context.Context, tenantID uint
return nil
}
func (r *tenantAPIKeyRepository) RevokeAllAPIKeys(ctx context.Context, tenantID uint64) error {
now := time.Now()
return r.db.WithContext(ctx).
Model(&types.TenantAPIKey{}).
Where("tenant_id = ? AND revoked_at IS NULL", tenantID).
Update("revoked_at", &now).Error
}
func (r *tenantAPIKeyRepository) UpdateAPIKeyHash(ctx context.Context, id uint64, hash string) error {
return r.db.WithContext(ctx).
Model(&types.TenantAPIKey{}).
-58
View File
@@ -4,11 +4,9 @@ import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"errors"
"io"
"os"
"strings"
"time"
@@ -180,62 +178,6 @@ func (s *tenantService) DeleteTenant(ctx context.Context, id uint64) error {
return nil
}
// UpdateAPIKey updates the API key for a specific tenant
func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, error) {
logger.Info(ctx, "Start updating tenant API Key")
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return "", errors.New("tenant ID cannot be 0")
}
tenant, err := s.repo.GetTenantByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return "", err
}
logger.Infof(ctx, "Generating new API Key for tenant, ID: %d", id)
plaintextAPIKey := s.generateApiKey(tenant.ID)
logger.Infof(ctx, "Tenant API Key generated successfully, ID: %d", id)
return plaintextAPIKey, nil
}
// generateApiKey generates a secure API key for tenant authentication
func (r *tenantService) generateApiKey(tenantID uint64) string {
// 1. Convert tenant_id to bytes
idBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(idBytes, uint64(tenantID))
// 2. Encrypt tenant_id using AES-GCM
block, err := aes.NewCipher(apiKeySecret())
if err != nil {
panic("Failed to create AES cipher: " + err.Error())
}
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic("Failed to create GCM cipher: " + err.Error())
}
ciphertext := aesgcm.Seal(nil, nonce, idBytes, nil)
// 3. Combine nonce and ciphertext, then encode with base64
combined := append(nonce, ciphertext...)
encoded := base64.RawURLEncoding.EncodeToString(combined)
// Create final API Key in format: sk-{encrypted_part}
return "sk-" + encoded
}
// ExtractTenantIDFromAPIKey extracts the tenant ID from an API key
func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) {
// 1. Validate format and extract encrypted part
+7 -25
View File
@@ -110,31 +110,6 @@ func (s *tenantAPIKeyService) AuthenticateTenantAPIKey(
return nil, apprepo.ErrTenantAPIKeyNotFound
}
func (s *tenantAPIKeyService) EnsureTenantAPIKey(ctx context.Context, tenantID uint64, apiKey string) error {
if tenantID == 0 || strings.TrimSpace(apiKey) == "" {
return nil
}
token := strings.TrimSpace(apiKey)
hash := hashTenantAPIKey(token)
if existing, err := s.repo.GetAPIKeyByHash(ctx, hash); err == nil && existing != nil {
return nil
} else if err != nil && !errors.Is(err, apprepo.ErrTenantAPIKeyNotFound) {
return err
}
key := &types.TenantAPIKey{
TenantID: tenantID,
Name: "Tenant API key",
KeyHash: hash,
APIKey: token,
Scopes: types.StringArray{
types.TenantAPIKeyScopeRead,
types.TenantAPIKeyScopeWrite,
types.TenantAPIKeyScopeAdmin,
},
}
return s.repo.CreateAPIKey(ctx, key)
}
func (s *tenantAPIKeyService) ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) {
keys, err := s.repo.ListAPIKeys(ctx, tenantID)
if err != nil {
@@ -152,6 +127,13 @@ func (s *tenantAPIKeyService) RevokeAPIKey(ctx context.Context, tenantID uint64,
return s.repo.RevokeAPIKey(ctx, tenantID, id)
}
func (s *tenantAPIKeyService) RevokeAllAPIKeys(ctx context.Context, tenantID uint64) error {
if tenantID == 0 {
return nil
}
return s.repo.RevokeAllAPIKeys(ctx, tenantID)
}
func generateTenantAPIKeyToken() (string, error) {
var b [32]byte
if _, err := rand.Read(b[:]); err != nil {
@@ -85,6 +85,16 @@ func (r *fakeTenantAPIKeyRepo) RevokeAPIKey(_ context.Context, tenantID uint64,
return apprepo.ErrTenantAPIKeyNotFound
}
func (r *fakeTenantAPIKeyRepo) RevokeAllAPIKeys(_ context.Context, tenantID uint64) error {
now := time.Now()
for _, key := range r.byHash {
if key.TenantID == tenantID && key.RevokedAt == nil {
key.RevokedAt = &now
}
}
return nil
}
func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyHash(_ context.Context, id uint64, hash string) error {
for oldHash, key := range r.byHash {
if key.ID == id && key.RevokedAt == nil {
@@ -106,32 +116,6 @@ func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyLastUsed(_ context.Context, id uint64
return nil
}
func TestTenantAPIKeyServiceEnsureTenantAPIKeyBackfillsMetadata(t *testing.T) {
ctx := context.Background()
repo := newFakeTenantAPIKeyRepo()
svc := NewTenantAPIKeyService(repo)
token := "sk-42-migrated-secret-value"
if err := svc.EnsureTenantAPIKey(ctx, 42, token); err != nil {
t.Fatalf("EnsureTenantAPIKey returned error: %v", err)
}
keys, err := svc.ListAPIKeys(ctx, 42)
if err != nil {
t.Fatalf("ListAPIKeys returned error: %v", err)
}
if len(keys) != 1 {
t.Fatalf("tenant keys count = %d, want 1", len(keys))
}
key := keys[0]
if key.APIKey != token {
t.Fatalf("tenant key api_key = %q, want %q", key.APIKey, token)
}
if !(types.TenantAPIKeyScope{Scopes: key.Scopes}).HasScope(types.TenantAPIKeyScopeAdmin) {
t.Fatalf("tenant key should include admin scope")
}
}
func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testing.T) {
ctx := context.Background()
repo := newFakeTenantAPIKeyRepo()
@@ -158,3 +142,43 @@ func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testi
t.Fatalf("AuthenticateAPIKey after repair returned error: %v", err)
}
}
func TestTenantAPIKeyServiceRevokeAllAPIKeys(t *testing.T) {
ctx := context.Background()
repo := newFakeTenantAPIKeyRepo()
svc := NewTenantAPIKeyService(repo)
first, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: 42,
Name: "first",
Scopes: []string{types.TenantAPIKeyScopeRead},
})
if err != nil {
t.Fatalf("CreateAPIKey first returned error: %v", err)
}
second, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: 42,
Name: "second",
Scopes: []string{types.TenantAPIKeyScopeRead},
})
if err != nil {
t.Fatalf("CreateAPIKey second returned error: %v", err)
}
if err := svc.RevokeAllAPIKeys(ctx, 42); err != nil {
t.Fatalf("RevokeAllAPIKeys returned error: %v", err)
}
if _, err := svc.AuthenticateAPIKey(ctx, first.Token); err == nil {
t.Fatal("first key should be revoked")
}
if _, err := svc.AuthenticateAPIKey(ctx, second.Token); err == nil {
t.Fatal("second key should be revoked")
}
keys, err := svc.ListAPIKeys(ctx, 42)
if err != nil {
t.Fatalf("ListAPIKeys returned error: %v", err)
}
if len(keys) != 0 {
t.Fatalf("active keys count = %d, want 0", len(keys))
}
}