feat: add scoped tenant api keys
This commit is contained in:
@@ -13,11 +13,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
werrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
werrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
)
|
||||
|
||||
var apiKeySecret = func() []byte {
|
||||
@@ -53,8 +52,8 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant)
|
||||
|
||||
logger.Infof(ctx, "Creating tenant, name: %s", tenant.Name)
|
||||
|
||||
// Create tenant with initial values
|
||||
tenant.APIKey = s.generateApiKey(0)
|
||||
// New tenants do not receive an API key by default. Integrations create
|
||||
// keys explicitly through tenant_api_keys.
|
||||
tenant.Status = "active"
|
||||
tenant.CreatedAt = time.Now()
|
||||
tenant.UpdatedAt = time.Now()
|
||||
@@ -74,29 +73,7 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Tenant created successfully, ID: %d, generating official API Key", tenant.ID)
|
||||
plaintextAPIKey := s.generateApiKey(tenant.ID)
|
||||
tenant.APIKey = plaintextAPIKey
|
||||
|
||||
// Manually encrypt APIKey before update, because db.Updates() does not trigger BeforeSave hook
|
||||
if key := utils.GetAESKey(); key != nil && tenant.APIKey != "" {
|
||||
if encrypted, err := utils.EncryptAESGCM(tenant.APIKey, key); err == nil {
|
||||
tenant.APIKey = encrypted
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.repo.UpdateTenant(ctx, tenant); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenant.ID,
|
||||
"tenant_name": tenant.Name,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Restore plaintext for the response so callers don't see enc:v1: ciphertext.
|
||||
tenant.APIKey = plaintextAPIKey
|
||||
|
||||
logger.Infof(ctx, "Tenant creation and update completed, ID: %d, name: %s", tenant.ID, tenant.Name)
|
||||
logger.Infof(ctx, "Tenant created successfully, ID: %d, name: %s", tenant.ID, tenant.Name)
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
@@ -151,12 +128,6 @@ func (s *tenantService) UpdateTenant(ctx context.Context, tenant *types.Tenant)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Generate new API key if empty
|
||||
if tenant.APIKey == "" {
|
||||
logger.Info(ctx, "API Key is empty, generating new API Key")
|
||||
tenant.APIKey = s.generateApiKey(tenant.ID)
|
||||
}
|
||||
|
||||
tenant.UpdatedAt = time.Now()
|
||||
logger.Info(ctx, "Saving tenant information to database")
|
||||
|
||||
@@ -228,23 +199,8 @@ func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, er
|
||||
|
||||
logger.Infof(ctx, "Generating new API Key for tenant, ID: %d", id)
|
||||
plaintextAPIKey := s.generateApiKey(tenant.ID)
|
||||
tenant.APIKey = plaintextAPIKey
|
||||
|
||||
// Manually encrypt APIKey before update, because db.Updates() does not trigger BeforeSave hook
|
||||
if key := utils.GetAESKey(); key != nil && tenant.APIKey != "" {
|
||||
if encrypted, err := utils.EncryptAESGCM(tenant.APIKey, key); err == nil {
|
||||
tenant.APIKey = encrypted
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.repo.UpdateTenant(ctx, tenant); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": id,
|
||||
})
|
||||
return "", err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Tenant API Key updated successfully, ID: %d", id)
|
||||
logger.Infof(ctx, "Tenant API Key generated successfully, ID: %d", id)
|
||||
return plaintextAPIKey, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
type tenantAPIKeyService struct {
|
||||
repo interfaces.TenantAPIKeyRepository
|
||||
}
|
||||
|
||||
func NewTenantAPIKeyService(repo interfaces.TenantAPIKeyRepository) interfaces.TenantAPIKeyService {
|
||||
return &tenantAPIKeyService{repo: repo}
|
||||
}
|
||||
|
||||
func (s *tenantAPIKeyService) CreateAPIKey(
|
||||
ctx context.Context, req interfaces.TenantAPIKeyCreateRequest,
|
||||
) (*interfaces.TenantAPIKeyCreateResult, error) {
|
||||
if req.TenantID == 0 {
|
||||
return nil, errors.New("tenant_id is required")
|
||||
}
|
||||
name := strings.TrimSpace(req.Name)
|
||||
if name == "" {
|
||||
return nil, errors.New("name is required")
|
||||
}
|
||||
token, err := generateTenantAPIKeyToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := &types.TenantAPIKey{
|
||||
TenantID: req.TenantID,
|
||||
Name: name,
|
||||
KeyHash: hashTenantAPIKey(token),
|
||||
APIKey: token,
|
||||
Scopes: normalizeAPIKeyScopes(req.Scopes),
|
||||
KnowledgeBaseIDs: normalizeAPIKeyIDs(req.KnowledgeBaseIDs),
|
||||
ExpiresAt: req.ExpiresAt,
|
||||
}
|
||||
if len(key.Scopes) == 0 {
|
||||
key.Scopes = types.StringArray{types.TenantAPIKeyScopeRead}
|
||||
}
|
||||
if err := s.repo.CreateAPIKey(ctx, key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &interfaces.TenantAPIKeyCreateResult{APIKey: key, Token: token}, nil
|
||||
}
|
||||
|
||||
func (s *tenantAPIKeyService) AuthenticateAPIKey(ctx context.Context, token string) (*types.TenantAPIKey, error) {
|
||||
token = strings.TrimSpace(token)
|
||||
if token == "" {
|
||||
return nil, apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
key, err := s.repo.GetAPIKeyByHash(ctx, hashTenantAPIKey(token))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if key.RevokedAt != nil {
|
||||
return nil, apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
if key.ExpiresAt != nil && time.Now().After(*key.ExpiresAt) {
|
||||
return nil, apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
_ = s.repo.UpdateAPIKeyLastUsed(ctx, key.ID, time.Now())
|
||||
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) 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 {
|
||||
return nil, err
|
||||
}
|
||||
for _, key := range keys {
|
||||
if err := s.ensureAPIKeyHash(ctx, key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (s *tenantAPIKeyService) RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error {
|
||||
return s.repo.RevokeAPIKey(ctx, tenantID, id)
|
||||
}
|
||||
|
||||
func generateTenantAPIKeyToken() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "sk-" + base64.RawURLEncoding.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
func hashTenantAPIKey(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
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 normalizeAPIKeyScopes(in []string) types.StringArray {
|
||||
out := types.StringArray{}
|
||||
seen := map[string]struct{}{}
|
||||
for _, scope := range in {
|
||||
scope = strings.ToLower(strings.TrimSpace(scope))
|
||||
switch scope {
|
||||
case types.TenantAPIKeyScopeRead, types.TenantAPIKeyScopeWrite, types.TenantAPIKeyScopeAdmin:
|
||||
default:
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[scope]; ok {
|
||||
continue
|
||||
}
|
||||
seen[scope] = struct{}{}
|
||||
out = append(out, scope)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeAPIKeyIDs(in []string) types.StringArray {
|
||||
out := types.StringArray{}
|
||||
seen := map[string]struct{}{}
|
||||
for _, id := range in {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
type fakeTenantAPIKeyRepo struct {
|
||||
byHash map[string]*types.TenantAPIKey
|
||||
nextID uint64
|
||||
}
|
||||
|
||||
func TestTenantAPIKeyServiceCreateAPIKeyUsesSKPrefix(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newFakeTenantAPIKeyRepo()
|
||||
svc := NewTenantAPIKeyService(repo)
|
||||
|
||||
result, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: 42,
|
||||
Name: "integration",
|
||||
Scopes: []string{types.TenantAPIKeyScopeRead},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(result.Token, "sk-") {
|
||||
t.Fatalf("created token = %q, want sk- prefix", result.Token)
|
||||
}
|
||||
if result.APIKey.APIKey != result.Token {
|
||||
t.Fatalf("created api_key = %q, want token %q", result.APIKey.APIKey, result.Token)
|
||||
}
|
||||
}
|
||||
|
||||
func newFakeTenantAPIKeyRepo() *fakeTenantAPIKeyRepo {
|
||||
return &fakeTenantAPIKeyRepo{byHash: map[string]*types.TenantAPIKey{}, nextID: 1}
|
||||
}
|
||||
|
||||
func (r *fakeTenantAPIKeyRepo) CreateAPIKey(_ context.Context, key *types.TenantAPIKey) error {
|
||||
if _, ok := r.byHash[key.KeyHash]; ok {
|
||||
return errors.New("duplicate key hash")
|
||||
}
|
||||
cp := *key
|
||||
cp.ID = r.nextID
|
||||
r.nextID++
|
||||
r.byHash[cp.KeyHash] = &cp
|
||||
key.ID = cp.ID
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *fakeTenantAPIKeyRepo) GetAPIKeyByHash(_ context.Context, hash string) (*types.TenantAPIKey, error) {
|
||||
key, ok := r.byHash[hash]
|
||||
if !ok {
|
||||
return nil, apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
cp := *key
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (r *fakeTenantAPIKeyRepo) ListAPIKeys(_ context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) {
|
||||
out := []*types.TenantAPIKey{}
|
||||
for _, key := range r.byHash {
|
||||
if key.TenantID == tenantID && key.RevokedAt == nil {
|
||||
cp := *key
|
||||
out = append(out, &cp)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *fakeTenantAPIKeyRepo) RevokeAPIKey(_ context.Context, tenantID uint64, id uint64) error {
|
||||
now := time.Now()
|
||||
for _, key := range r.byHash {
|
||||
if key.ID == id && key.TenantID == tenantID && key.RevokedAt == nil {
|
||||
key.RevokedAt = &now
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
|
||||
func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyHash(_ context.Context, id uint64, hash string) error {
|
||||
for oldHash, key := range r.byHash {
|
||||
if key.ID == id && key.RevokedAt == nil {
|
||||
delete(r.byHash, oldHash)
|
||||
key.KeyHash = hash
|
||||
r.byHash[hash] = key
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return apprepo.ErrTenantAPIKeyNotFound
|
||||
}
|
||||
|
||||
func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyLastUsed(_ context.Context, id uint64, at time.Time) error {
|
||||
for _, key := range r.byHash {
|
||||
if key.ID == id && key.RevokedAt == nil {
|
||||
key.LastUsedAt = &at
|
||||
}
|
||||
}
|
||||
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()
|
||||
svc := NewTenantAPIKeyService(repo)
|
||||
token := "sk-42-migrated-secret-value"
|
||||
key := &types.TenantAPIKey{
|
||||
TenantID: 42,
|
||||
Name: "Tenant API key",
|
||||
KeyHash: "migrated-tenant-42",
|
||||
APIKey: token,
|
||||
Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin},
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user