fix(tenant): prevent api_key encryption loss on tenant settings update
When a tenant setting is updated via PUT /tenants/kv/{key} (e.g.,
retrieval-config, parser-engine-config), the GORM AfterFind-decrypted
plaintext api_key was silently written back to the database because
db.Updates() does not trigger the BeforeSave hook.
Guard the repository's UpdateTenant to skip writing plaintext api_key
back to the database. Pre-encrypted values (enc:v1:… from CreateTenant
/ UpdateAPIKey) are written as-is; AfterFind-decrypted plaintext is
blanked so GORM skips the column entirely.
Closes #798
This commit is contained in:
@@ -3,10 +3,12 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"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"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
@@ -93,9 +95,28 @@ func (r *tenantRepository) SearchTenants(ctx context.Context, keyword string, te
|
||||
return tenants, total, nil
|
||||
}
|
||||
|
||||
// UpdateTenant updates tenant
|
||||
// UpdateTenant updates tenant.
|
||||
// Handles api_key carefully because db.Updates() does not trigger the BeforeSave
|
||||
// GORM hook. Without this guard, AfterFind-decrypted plaintext would silently
|
||||
// overwrite the encrypted value in the database.
|
||||
//
|
||||
// Strategy:
|
||||
// - enc:v1:… (pre-encrypted by CreateTenant / UpdateAPIKey): write as-is.
|
||||
// - plaintext (decrypted by AfterFind): blank it so GORM skips the column.
|
||||
// - SYSTEM_AES_KEY not set: write as-is (encryption disabled).
|
||||
//
|
||||
// The caller's in-memory struct is always restored after the write.
|
||||
func (r *tenantRepository) UpdateTenant(ctx context.Context, tenant *types.Tenant) error {
|
||||
return r.db.WithContext(ctx).Model(&types.Tenant{}).Where("id = ?", tenant.ID).Updates(tenant).Error
|
||||
origAPIKey := tenant.APIKey
|
||||
if key := utils.GetAESKey(); key != nil && tenant.APIKey != "" &&
|
||||
!strings.HasPrefix(tenant.APIKey, utils.EncPrefix) {
|
||||
// Plaintext from AfterFind — do not write back; let the DB keep its
|
||||
// existing encrypted value untouched.
|
||||
tenant.APIKey = ""
|
||||
}
|
||||
err := r.db.WithContext(ctx).Model(&types.Tenant{}).Where("id = ?", tenant.ID).Updates(tenant).Error
|
||||
tenant.APIKey = origAPIKey
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteTenant deletes tenant
|
||||
|
||||
Reference in New Issue
Block a user