refactor(api-keys): remove API key reset endpoint and update documentation
Eliminate the POST /tenants/{id}/api-key endpoint for resetting tenant API keys, transitioning to a more granular API key management approach. Update related documentation and API specifications to reflect the new structure, including changes to the tenant API key management paths. Adjust frontend code and internationalization files to remove references to the deprecated API key reset functionality, enhancing clarity and consistency across the application.
This commit is contained in:
@@ -62,14 +62,6 @@ 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{}).
|
||||
@@ -83,6 +75,23 @@ func (r *tenantAPIKeyRepository) UpdateAPIKeyHash(ctx context.Context, id uint64
|
||||
// key_hash is not the real SHA-256 of the API key yet.
|
||||
const placeholderKeyHashPrefix = "migrated-tenant-"
|
||||
|
||||
func (r *tenantAPIKeyRepository) HasKeysWithPlaceholderHash(ctx context.Context) (bool, error) {
|
||||
var id uint64
|
||||
err := r.db.WithContext(ctx).Session(&gorm.Session{SkipHooks: true}).
|
||||
Model(&types.TenantAPIKey{}).
|
||||
Select("id").
|
||||
Where("key_hash LIKE ? AND revoked_at IS NULL", placeholderKeyHashPrefix+"%").
|
||||
Limit(1).
|
||||
Scan(&id).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return id != 0, nil
|
||||
}
|
||||
|
||||
func (r *tenantAPIKeyRepository) ListKeysWithPlaceholderHash(
|
||||
ctx context.Context,
|
||||
) ([]*types.TenantAPIKey, error) {
|
||||
|
||||
@@ -2,13 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
werrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
@@ -17,10 +11,6 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
var apiKeySecret = func() []byte {
|
||||
return []byte(os.Getenv("TENANT_AES_KEY"))
|
||||
}
|
||||
|
||||
// ListTenantsParams defines parameters for listing tenants with filtering and pagination
|
||||
type ListTenantsParams struct {
|
||||
Page int // Page number for pagination
|
||||
@@ -178,48 +168,6 @@ func (s *tenantService) DeleteTenant(ctx context.Context, id uint64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExtractTenantIDFromAPIKey extracts the tenant ID from an API key
|
||||
func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) {
|
||||
// 1. Validate format and extract encrypted part
|
||||
parts := strings.SplitN(apiKey, "-", 2)
|
||||
if len(parts) != 2 || parts[0] != "sk" {
|
||||
return 0, errors.New("invalid API key format")
|
||||
}
|
||||
|
||||
// 2. Decode the base64 part
|
||||
encryptedData, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return 0, errors.New("invalid API key encoding")
|
||||
}
|
||||
|
||||
// 3. Separate nonce and ciphertext
|
||||
if len(encryptedData) < 12 {
|
||||
return 0, errors.New("invalid API key length")
|
||||
}
|
||||
nonce, ciphertext := encryptedData[:12], encryptedData[12:]
|
||||
|
||||
// 4. Decrypt
|
||||
block, err := aes.NewCipher(apiKeySecret())
|
||||
if err != nil {
|
||||
return 0, errors.New("decryption error")
|
||||
}
|
||||
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return 0, errors.New("decryption error")
|
||||
}
|
||||
|
||||
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return 0, errors.New("API key is invalid or has been tampered with")
|
||||
}
|
||||
|
||||
// 5. Convert back to tenant_id
|
||||
tenantID := binary.LittleEndian.Uint64(plaintext)
|
||||
|
||||
return tenantID, nil
|
||||
}
|
||||
|
||||
// ListAllTenants lists all tenants (for users with cross-tenant access permission)
|
||||
// This method returns all tenants without filtering, intended for admin users
|
||||
func (s *tenantService) ListAllTenants(ctx context.Context) ([]*types.Tenant, error) {
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
@@ -75,66 +74,22 @@ func (s *tenantAPIKeyService) AuthenticateAPIKey(ctx context.Context, token stri
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func (s *tenantAPIKeyService) AuthenticateTenantAPIKey(
|
||||
ctx context.Context, tenantID uint64, token string,
|
||||
) (*types.TenantAPIKey, error) {
|
||||
token = strings.TrimSpace(token)
|
||||
if tenantID == 0 || token == "" {
|
||||
return nil, apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
if key, err := s.AuthenticateAPIKey(ctx, token); err == nil && key != nil {
|
||||
if key.TenantID != tenantID {
|
||||
return nil, apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
return key, nil
|
||||
} else if err != nil && !errors.Is(err, apprepo.ErrTenantAPIKeyNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
keys, err := s.repo.ListAPIKeys(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, key := range keys {
|
||||
if key == nil || subtle.ConstantTimeCompare([]byte(key.APIKey), []byte(token)) != 1 {
|
||||
continue
|
||||
}
|
||||
if key.ExpiresAt != nil && time.Now().After(*key.ExpiresAt) {
|
||||
return nil, apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
if err := s.ensureAPIKeyHash(ctx, key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = s.repo.UpdateAPIKeyLastUsed(ctx, key.ID, time.Now())
|
||||
return key, nil
|
||||
}
|
||||
return nil, apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
|
||||
func (s *tenantAPIKeyService) ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) {
|
||||
keys, err := s.repo.ListAPIKeys(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, key := range keys {
|
||||
if err := s.ensureAPIKeyHash(ctx, key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return keys, nil
|
||||
return s.repo.ListAPIKeys(ctx, tenantID)
|
||||
}
|
||||
|
||||
func (s *tenantAPIKeyService) RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error {
|
||||
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 (s *tenantAPIKeyService) BackfillMissingKeyHashes(ctx context.Context) (int, error) {
|
||||
has, err := s.repo.HasKeysWithPlaceholderHash(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !has {
|
||||
return 0, nil
|
||||
}
|
||||
keys, err := s.repo.ListKeysWithPlaceholderHash(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -169,21 +124,6 @@ func hashTenantAPIKey(token string) string {
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *tenantAPIKeyService) ensureAPIKeyHash(ctx context.Context, key *types.TenantAPIKey) error {
|
||||
if key == nil || strings.TrimSpace(key.APIKey) == "" {
|
||||
return nil
|
||||
}
|
||||
hash := hashTenantAPIKey(key.APIKey)
|
||||
if key.KeyHash == hash {
|
||||
return nil
|
||||
}
|
||||
if err := s.repo.UpdateAPIKeyHash(ctx, key.ID, hash); err != nil {
|
||||
return err
|
||||
}
|
||||
key.KeyHash = hash
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeAPIKeyIDs(in []string) types.StringArray {
|
||||
out := types.StringArray{}
|
||||
seen := map[string]struct{}{}
|
||||
|
||||
@@ -85,16 +85,6 @@ 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 {
|
||||
@@ -107,6 +97,15 @@ func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyHash(_ context.Context, id uint64, ha
|
||||
return apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
|
||||
func (r *fakeTenantAPIKeyRepo) HasKeysWithPlaceholderHash(_ context.Context) (bool, error) {
|
||||
for _, key := range r.byHash {
|
||||
if key.RevokedAt == nil && strings.HasPrefix(key.KeyHash, "migrated-tenant-") {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (r *fakeTenantAPIKeyRepo) ListKeysWithPlaceholderHash(_ context.Context) ([]*types.TenantAPIKey, error) {
|
||||
out := []*types.TenantAPIKey{}
|
||||
for _, key := range r.byHash {
|
||||
@@ -127,33 +126,6 @@ func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyLastUsed(_ context.Context, id uint64
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newFakeTenantAPIKeyRepo()
|
||||
svc := NewTenantAPIKeyService(repo)
|
||||
token := "sk-42-migrated-secret-value"
|
||||
key := &types.TenantAPIKey{
|
||||
TenantID: 42,
|
||||
Name: "Tenant API key",
|
||||
KeyHash: "migrated-tenant-42",
|
||||
APIKey: token,
|
||||
Role: types.TenantRoleAdmin,
|
||||
}
|
||||
if err := repo.CreateAPIKey(ctx, key); err != nil {
|
||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||
}
|
||||
got, err := svc.AuthenticateTenantAPIKey(ctx, 42, token)
|
||||
if err != nil {
|
||||
t.Fatalf("AuthenticateTenantAPIKey returned error: %v", err)
|
||||
}
|
||||
if got.KeyHash != hashTenantAPIKey(token) {
|
||||
t.Fatalf("repaired hash = %q, want %q", got.KeyHash, hashTenantAPIKey(token))
|
||||
}
|
||||
if _, err := svc.AuthenticateAPIKey(ctx, token); err != nil {
|
||||
t.Fatalf("AuthenticateAPIKey after repair returned error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newFakeTenantAPIKeyRepo()
|
||||
@@ -165,7 +137,7 @@ func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {
|
||||
Name: "legacy",
|
||||
KeyHash: "migrated-tenant-7",
|
||||
APIKey: token,
|
||||
Role: types.TenantRoleAdmin,
|
||||
Role: types.TenantRoleOwner,
|
||||
}
|
||||
if err := repo.CreateAPIKey(ctx, legacy); err != nil {
|
||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||
@@ -178,52 +150,31 @@ func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {
|
||||
if n != 1 {
|
||||
t.Fatalf("backfilled = %d, want 1", n)
|
||||
}
|
||||
// After backfill the key authenticates via the fast hash path.
|
||||
if _, err := svc.AuthenticateAPIKey(ctx, token); err != nil {
|
||||
t.Fatalf("AuthenticateAPIKey after backfill returned error: %v", err)
|
||||
}
|
||||
// Idempotent: a second run finds nothing to do.
|
||||
if n, err := svc.BackfillMissingKeyHashes(ctx); err != nil || n != 0 {
|
||||
t.Fatalf("second BackfillMissingKeyHashes = (%d, %v), want (0, nil)", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantAPIKeyServiceRevokeAllAPIKeys(t *testing.T) {
|
||||
func TestTenantAPIKeyServiceRevokeAPIKey(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newFakeTenantAPIKeyRepo()
|
||||
svc := NewTenantAPIKeyService(repo)
|
||||
|
||||
first, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
created, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: 42,
|
||||
Name: "first",
|
||||
Name: "integration",
|
||||
Role: types.TenantRoleViewer,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateAPIKey first returned error: %v", err)
|
||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||
}
|
||||
second, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: 42,
|
||||
Name: "second",
|
||||
Role: types.TenantRoleViewer,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateAPIKey second returned error: %v", err)
|
||||
if err := svc.RevokeAPIKey(ctx, 42, created.APIKey.ID); err != nil {
|
||||
t.Fatalf("RevokeAPIKey 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))
|
||||
if _, err := svc.AuthenticateAPIKey(ctx, created.Token); err == nil {
|
||||
t.Fatal("revoked key should not authenticate")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user