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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +104,6 @@ func (f *flowTenantSvc) DeleteTenant(context.Context, uint64) error { return nil
|
||||
func (f *flowTenantSvc) ListTenants(context.Context) ([]*types.Tenant, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *flowTenantSvc) ExtractTenantIDFromAPIKey(string) (uint64, error) { return 0, nil }
|
||||
func (f *flowTenantSvc) ListAllTenants(context.Context) ([]*types.Tenant, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -93,8 +93,8 @@ type createTenantRequest struct {
|
||||
// fields an Owner is permitted to mutate via the public API are bound;
|
||||
// everything else (storage_quota, status, business, api_key, agent /
|
||||
// retrieval / storage configs, ...) is intentionally NOT writable here
|
||||
// — those go through dedicated endpoints (POST /:id/api-key,
|
||||
// PUT /tenants/kv/:key, ...) that have their own validation.
|
||||
// — those go through dedicated endpoints (PUT /tenants/kv/:key, ...)
|
||||
// that have their own validation.
|
||||
//
|
||||
// Pointers so we can distinguish "not sent" from "explicit empty
|
||||
// string"; when nil we leave the existing column untouched.
|
||||
@@ -477,7 +477,7 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {
|
||||
// Strict whitelist: only Name / Description are mutable through the
|
||||
// public PUT. Storage quota, status, business, configs, api_key and
|
||||
// every other privileged column live behind dedicated endpoints
|
||||
// (POST /:id/api-key, PUT /tenants/kv/:key, ...). Without this, an
|
||||
// (PUT /tenants/kv/:key, ...). Without this, an
|
||||
// Owner — including any user who just self-served a tenant — could
|
||||
// flip status / bump storage_quota by simply crafting an extended
|
||||
// JSON body. Pointers distinguish "field omitted" from "explicit
|
||||
@@ -541,63 +541,6 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ResetAPIKey godoc
|
||||
// @Summary 重置租户 API Key
|
||||
// @Description 吊销该租户全部现有 API Key 后创建一把新的全权限 Key
|
||||
// @Tags 租户管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "租户ID"
|
||||
// @Success 200 {object} map[string]interface{} "新生成的 API Key"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 403 {object} errors.AppError "权限不足"
|
||||
// @Security Bearer
|
||||
// @Router /tenants/{id}/api-key [post]
|
||||
func (h *TenantHandler) ResetAPIKey(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Invalid tenant ID: %s", secutils.SanitizeForLog(c.Param("id")))
|
||||
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Resetting API key for tenant, ID: %d", id)
|
||||
if h.apiKeyService == nil {
|
||||
c.Error(errors.NewInternalServerError("API key service is not configured"))
|
||||
return
|
||||
}
|
||||
if err := h.apiKeyService.RevokeAllAPIKeys(ctx, id); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"tenant_id": id})
|
||||
c.Error(errors.NewInternalServerError("Failed to reset API key").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: id,
|
||||
Name: "Tenant API key",
|
||||
Role: types.TenantRoleOwner,
|
||||
})
|
||||
if err != nil {
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
logger.Error(ctx, "Failed to reset API key: application error", appErr)
|
||||
c.Error(appErr)
|
||||
} else {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to reset API key").WithDetails(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "API key reset successfully, tenant ID: %d", id)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"api_key": result.APIKey.APIKey,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *TenantHandler) ListAPIKeys(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
|
||||
@@ -43,7 +43,6 @@ func (s *stubTenantService) ListAllTenants(context.Context) ([]*types.Tenant, er
|
||||
func (s *stubTenantService) SearchTenants(context.Context, string, uint64, int, int) ([]*types.Tenant, int64, error) {
|
||||
return nil, 0, nil
|
||||
}
|
||||
func (s *stubTenantService) ExtractTenantIDFromAPIKey(string) (uint64, error) { return 0, nil }
|
||||
func (s *stubTenantService) BulkSetStorageQuota(context.Context, int64) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ func RequireCrossTenantAccess(cfg *config.Config) gin.HandlerFunc {
|
||||
// auth middleware.
|
||||
//
|
||||
// The router places this on the /tenants/:id group so every per-tenant
|
||||
// endpoint (GetTenant / UpdateTenant / DeleteTenant / ResetAPIKey /
|
||||
// endpoint (GetTenant / UpdateTenant / DeleteTenant /
|
||||
// member management / leave) shares the same check, replacing what was
|
||||
// previously a copy-pasted block in each handler.
|
||||
//
|
||||
|
||||
@@ -237,26 +237,16 @@ func authenticateAPIKeyRequest(
|
||||
apiKey string,
|
||||
) bool {
|
||||
ctx := c.Request.Context()
|
||||
var key *types.TenantAPIKey
|
||||
var tenantID uint64
|
||||
|
||||
if authenticated, err := apiKeyService.AuthenticateAPIKey(ctx, apiKey); err == nil && authenticated != nil {
|
||||
key = authenticated
|
||||
tenantID = key.TenantID
|
||||
} else if tenantIDFromKey, extractErr := tenantService.ExtractTenantIDFromAPIKey(apiKey); extractErr == nil {
|
||||
if authenticated, err := apiKeyService.AuthenticateTenantAPIKey(ctx, tenantIDFromKey, apiKey); err == nil && authenticated != nil {
|
||||
key = authenticated
|
||||
tenantID = tenantIDFromKey
|
||||
}
|
||||
}
|
||||
|
||||
if key == nil {
|
||||
// AuthenticateAPIKey resolves the key by SHA-256 hash (see startup
|
||||
// BackfillMissingKeyHashes for migration 000065 placeholder rows).
|
||||
key, err := apiKeyService.AuthenticateAPIKey(ctx, apiKey)
|
||||
if err != nil || key == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid API key"})
|
||||
c.Abort()
|
||||
return false
|
||||
}
|
||||
|
||||
attachAPIKeyAuthContext(c, tenantService, userService, tenantID, key)
|
||||
attachAPIKeyAuthContext(c, tenantService, userService, key.TenantID, key)
|
||||
if c.IsAborted() {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -161,10 +161,6 @@ func (f *fakeTenantService) ListTenants(ctx context.Context) ([]*types.Tenant, e
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeTenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (f *fakeTenantService) ListAllTenants(ctx context.Context) ([]*types.Tenant, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -426,7 +426,7 @@ func (g *rbacGuards) CrossTenant() gin.HandlerFunc {
|
||||
// PathTenantMatch enforces that the URL :id matches the caller's
|
||||
// active tenant context (cross-tenant superusers bypass). Routes apply
|
||||
// it at the /tenants/:id group level so every per-tenant endpoint —
|
||||
// GetTenant / UpdateTenant / DeleteTenant / ResetAPIKey / member
|
||||
// GetTenant / UpdateTenant / DeleteTenant / member
|
||||
// management / leave — shares the same check. Replaces the
|
||||
// authorizeTenantAccess helper that used to live inside the tenant
|
||||
// handler.
|
||||
|
||||
@@ -527,7 +527,7 @@ func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGua
|
||||
// - GET /:id Viewer+ (read tenant settings)
|
||||
// - PUT /:id Owner+ (mutate tenant config)
|
||||
// - DELETE /:id Owner+ (also normally a CanAccessAllTenants op)
|
||||
// - POST /:id/api-key Owner+ (rotating the tenant API key is sensitive)
|
||||
// - GET/POST/DELETE /:id/api-keys Owner+ (scoped API key management)
|
||||
// - GET /:id/members Viewer+ (any member can see who else is in)
|
||||
// - POST /:id/members Owner+ (only Owner can add new members)
|
||||
// - PUT /:id/members/:user_id Owner+ (only Owner can change roles)
|
||||
@@ -596,7 +596,6 @@ func RegisterTenantRoutes(
|
||||
tenantByID.GET("", g.Viewer(), handler.GetTenant)
|
||||
tenantByID.PUT("", g.Owner(), handler.UpdateTenant)
|
||||
tenantByID.DELETE("", g.Owner(), handler.DeleteTenant)
|
||||
tenantByID.POST("/api-key", g.Owner(), handler.ResetAPIKey)
|
||||
tenantByID.GET("/api-keys", g.Owner(), handler.ListAPIKeys)
|
||||
tenantByID.POST("/api-keys", g.Owner(), handler.CreateAPIKey)
|
||||
tenantByID.DELETE("/api-keys/:key_id", g.Owner(), handler.DeleteAPIKey)
|
||||
|
||||
@@ -29,7 +29,6 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {
|
||||
v1 := engine.Group("/api/v1")
|
||||
tenantByID := v1.Group("/tenants/:id")
|
||||
{
|
||||
tenantByID.POST("/api-key", reachedOK)
|
||||
tenantByID.GET("/api-keys", reachedOK)
|
||||
tenantByID.POST("/api-keys", reachedOK)
|
||||
tenantByID.DELETE("/api-keys/:key_id", reachedOK)
|
||||
@@ -46,7 +45,6 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodPost, "/api/v1/tenants/42/api-key"},
|
||||
{http.MethodGet, "/api/v1/tenants/42/api-keys"},
|
||||
{http.MethodPost, "/api/v1/tenants/42/api-keys"},
|
||||
{http.MethodDelete, "/api/v1/tenants/42/api-keys/7"},
|
||||
|
||||
@@ -51,7 +51,6 @@ func (s *stubTenantService) UpdateTenant(context.Context, *types.Tenant) (*types
|
||||
panic("unexpected")
|
||||
}
|
||||
func (s *stubTenantService) DeleteTenant(context.Context, uint64) error { panic("unexpected") }
|
||||
func (s *stubTenantService) ExtractTenantIDFromAPIKey(string) (uint64, error) { panic("unexpected") }
|
||||
func (s *stubTenantService) ListAllTenants(context.Context) ([]*types.Tenant, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
|
||||
@@ -23,8 +23,6 @@ type TenantService interface {
|
||||
UpdateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error)
|
||||
// DeleteTenant deletes a tenant
|
||||
DeleteTenant(ctx context.Context, id uint64) error
|
||||
// ExtractTenantIDFromAPIKey extracts the tenant ID from the API key
|
||||
ExtractTenantIDFromAPIKey(apiKey string) (uint64, error)
|
||||
// ListAllTenants lists all tenants (for users with cross-tenant access permission)
|
||||
ListAllTenants(ctx context.Context) ([]*types.Tenant, error)
|
||||
// BulkSetStorageQuota overwrites every tenant's storage_quota with
|
||||
@@ -82,25 +80,24 @@ type TenantAPIKeyRepository interface {
|
||||
GetAPIKeyByHash(ctx context.Context, hash string) (*types.TenantAPIKey, error)
|
||||
ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)
|
||||
RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error
|
||||
RevokeAllAPIKeys(ctx context.Context, tenantID uint64) error
|
||||
UpdateAPIKeyHash(ctx context.Context, id uint64, hash string) error
|
||||
UpdateAPIKeyLastUsed(ctx context.Context, id uint64, at time.Time) error
|
||||
// ListKeysWithPlaceholderHash returns keys whose key_hash is still the
|
||||
// migration placeholder (never authenticated since the 000065 upgrade),
|
||||
// so the real SHA-256 hash can be computed and backfilled.
|
||||
ListKeysWithPlaceholderHash(ctx context.Context) ([]*types.TenantAPIKey, error)
|
||||
// HasKeysWithPlaceholderHash is a cheap existence probe used at startup
|
||||
// to skip loading/decrypting api_key rows once backfill is complete.
|
||||
HasKeysWithPlaceholderHash(ctx context.Context) (bool, error)
|
||||
}
|
||||
|
||||
type TenantAPIKeyService interface {
|
||||
CreateAPIKey(ctx context.Context, req TenantAPIKeyCreateRequest) (*TenantAPIKeyCreateResult, error)
|
||||
AuthenticateAPIKey(ctx context.Context, token string) (*types.TenantAPIKey, error)
|
||||
AuthenticateTenantAPIKey(ctx context.Context, tenantID uint64, token string) (*types.TenantAPIKey, error)
|
||||
ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)
|
||||
RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error
|
||||
RevokeAllAPIKeys(ctx context.Context, tenantID uint64) error
|
||||
// BackfillMissingKeyHashes computes and persists the SHA-256 key_hash
|
||||
// for legacy keys still carrying the migration placeholder, so their
|
||||
// first authentication does not fall back to an O(n) plaintext scan.
|
||||
// for legacy keys still carrying the migration placeholder.
|
||||
// Returns the number of keys backfilled.
|
||||
BackfillMissingKeyHashes(ctx context.Context) (int, error)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user