feat(security): add AES-256-GCM encryption for API keys at rest
- Add crypto utility (internal/utils/crypto.go) with AES-256-GCM encrypt/decrypt using SYSTEM_AES_KEY env var, with "enc:v1:" prefix for versioned ciphertext - Encrypt tenant API key via GORM BeforeSave/AfterFind hooks and manual encryption in CreateTenant/UpdateAPIKey (db.Updates bypasses hooks) - Encrypt model API key in ModelParameters Value/Scan (driver.Valuer) - Widen api_key column from varchar(64) to varchar(256) across all DB dialects (MySQL, ParadeDB, SQLite) and add versioned migration 000018 - Propagate SYSTEM_AES_KEY through docker-compose, Helm secrets and values - Fix migration 000017 PL/pgSQL dollar-quoting syntax ($ -> $$)
This commit is contained in:
@@ -16,6 +16,7 @@ import (
|
||||
"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"
|
||||
)
|
||||
|
||||
var apiKeySecret = func() []byte {
|
||||
@@ -67,6 +68,14 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant)
|
||||
|
||||
logger.Infof(ctx, "Tenant created successfully, ID: %d, generating official API Key", tenant.ID)
|
||||
tenant.APIKey = s.generateApiKey(tenant.ID)
|
||||
|
||||
// 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,
|
||||
@@ -196,6 +205,13 @@ func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, er
|
||||
logger.Infof(ctx, "Generating new API Key for tenant, ID: %d", id)
|
||||
tenant.APIKey = s.generateApiKey(tenant.ID)
|
||||
|
||||
// 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,
|
||||
|
||||
Reference in New Issue
Block a user