feat(message): add message encryption with batch decryption optimization

- Add encryption configuration with environment variable support
- Implement batch parallel decryption for improved query performance
- Integrate message encryptor via wire dependency injection
- Add explicit Decrypt() method for single message decryption
- Optimize AfterFind hook to defer decryption for batch processing
This commit is contained in:
lafay
2026-03-17 10:10:49 +08:00
parent 5d6c982c9c
commit 8a2b0e0a5e
7 changed files with 445 additions and 2 deletions

View File

@@ -6,6 +6,7 @@ import (
"carrot_bbs/internal/cache"
"carrot_bbs/internal/config"
"carrot_bbs/internal/model"
"carrot_bbs/internal/pkg/crypto"
"carrot_bbs/internal/pkg/email"
"carrot_bbs/internal/pkg/gorse"
"carrot_bbs/internal/pkg/openai"
@@ -45,6 +46,9 @@ var InfrastructureSet = wire.NewSet(
ProvideOpenAIClient,
ProvideEmailClient,
ProvideS3Client,
// 消息加密器
ProvideMessageEncryptor,
)
// ProvideConfig 加载配置
@@ -125,6 +129,31 @@ func ProvideTransactionManager(db *gorm.DB) repository.TransactionManager {
return repository.NewTransactionManager(db)
}
// ProvideMessageEncryptor 提供消息加密器
func ProvideMessageEncryptor(cfg *config.Config) error {
if !cfg.Encryption.Enabled {
zap.L().Info("Message encryption is disabled")
return nil
}
if len(cfg.Encryption.Key) != 32 {
zap.L().Error("Encryption key must be 32 bytes for AES-256",
zap.Int("actual_length", len(cfg.Encryption.Key)),
)
return nil
}
if err := crypto.InitMessageEncryptor(cfg.Encryption.Key, cfg.Encryption.KeyVersion); err != nil {
zap.L().Error("Failed to initialize message encryptor", zap.Error(err))
return err
}
zap.L().Info("Message encryption initialized successfully",
zap.Int("key_version", cfg.Encryption.KeyVersion),
)
return nil
}
// ProvideLogger 提供 Zap Logger
func ProvideLogger() *zap.Logger {
logger, err := zap.NewProduction()