Skip to content

Modern Docker Management, Designed for Everyone

fix: decrypting of notification tokens failing (#2850)

Kyle Mendella7a7be5d0a35
diff --git a/backend/api/handlers/notifications.go b/backend/api/handlers/notifications.go
index 9109ff65c..30f77e5b8 100644
--- a/backend/api/handlers/notifications.go
+++ b/backend/api/handlers/notifications.go
@@ -188,7 +188,7 @@ func (h *NotificationHandler) GetAllNotificationSettings(ctx context.Context, in
ID: setting.ID,
Provider: notification.Provider(setting.Provider),
Enabled: setting.Enabled,
- Config: base.JsonObject(setting.Config),
+ Config: base.JsonObject(services.RedactNotificationConfigCredentials(setting.Provider, setting.Config)),
}
}
@@ -210,7 +210,7 @@ func (h *NotificationHandler) GetNotificationSettings(ctx context.Context, input
ID: settings.ID,
Provider: notification.Provider(settings.Provider),
Enabled: settings.Enabled,
- Config: base.JsonObject(settings.Config),
+ Config: base.JsonObject(services.RedactNotificationConfigCredentials(settings.Provider, settings.Config)),
}
return &GetNotificationSettingsOutput{Body: response}, nil
@@ -239,7 +239,7 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Con
ID: settings.ID,
Provider: notification.Provider(settings.Provider),
Enabled: settings.Enabled,
- Config: base.JsonObject(settings.Config),
+ Config: base.JsonObject(services.RedactNotificationConfigCredentials(settings.Provider, settings.Config)),
}
return &CreateOrUpdateNotificationSettingsOutput{Body: response}, nil
diff --git a/backend/api/handlers/notifications_test.go b/backend/api/handlers/notifications_test.go
index dbdaaa08d..999f58ee3 100644
--- a/backend/api/handlers/notifications_test.go
+++ b/backend/api/handlers/notifications_test.go
@@ -11,6 +11,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/crypto"
notificationdto "github.com/getarcaneapp/arcane/types/v2/notification"
glsqlite "github.com/glebarez/sqlite"
"github.com/stretchr/testify/assert"
@@ -56,6 +57,41 @@ func TestNormalizeNotificationTestType(t *testing.T) {
assert.Equal(t, "auto-heal", normalizeNotificationTestType(" auto-heal "))
}
+func TestNotificationHandlerGetAllNotificationSettingsRedactsCredentialsInternal(t *testing.T) {
+ ctx := context.Background()
+ crypto.InitEncryption(&crypto.Config{
+ EncryptionKey: "test-encryption-key-for-testing-32bytes-min",
+ Environment: "test",
+ })
+
+ db, svc := setupNotificationHandlerTestService(t)
+ h := &NotificationHandler{
+ notificationService: svc,
+ config: &config.Config{},
+ }
+
+ _, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderDiscord, true, models.JSON{
+ "webhookId": "123456789",
+ "token": "discord-secret-token",
+ "username": "Arcane",
+ })
+ require.NoError(t, err)
+
+ output, err := h.GetAllNotificationSettings(ctx, &GetAllNotificationSettingsInput{EnvironmentID: "0"})
+ require.NoError(t, err)
+ require.Len(t, output.Body, 1)
+ require.Equal(t, "123456789", output.Body[0].Config["webhookId"])
+ require.Equal(t, "Arcane", output.Body[0].Config["username"])
+ require.Empty(t, output.Body[0].Config["token"])
+
+ var stored models.NotificationSettings
+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderDiscord).First(&stored).Error)
+ require.NotEqual(t, "discord-secret-token", stored.Config["token"])
+ decrypted, err := crypto.Decrypt(stored.Config["token"].(string))
+ require.NoError(t, err)
+ require.Equal(t, "discord-secret-token", decrypted)
+}
+
func TestDispatchNotification_RejectsAgentModeInternal(t *testing.T) {
h := &NotificationHandler{config: &config.Config{AgentMode: true}}
diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.go
index 97f0d5713..3db58d44f 100644
--- a/backend/internal/services/notification_service.go
+++ b/backend/internal/services/notification_service.go
@@ -3,11 +3,13 @@ package services
import (
"bytes"
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
+ "maps"
"net/http"
"net/mail"
"strings"
@@ -45,6 +47,18 @@ var supportedNotificationTestTypes = map[string]struct{}{
notificationTestTypeAutoHeal: {},
}
+var notificationCredentialFieldsByProviderInternal = map[models.NotificationProvider][]string{
+ models.NotificationProviderDiscord: {"token"},
+ models.NotificationProviderEmail: {"smtpPassword"},
+ models.NotificationProviderTelegram: {"botToken"},
+ models.NotificationProviderSignal: {"password", "token"},
+ models.NotificationProviderSlack: {"token"},
+ models.NotificationProviderNtfy: {"password"},
+ models.NotificationProviderPushover: {"token"},
+ models.NotificationProviderGotify: {"token"},
+ models.NotificationProviderMatrix: {"password"},
+}
+
var ErrUnauthorizedNotificationDispatch = errors.New("unauthorized notification dispatch")
var ErrUnsupportedDispatchKind = errors.New("unsupported notification dispatch kind")
@@ -264,12 +278,23 @@ func (s *NotificationService) GetSettingsByProvider(ctx context.Context, provide
func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provider models.NotificationProvider, enabled bool, config models.JSON) (*models.NotificationSettings, error) {
var setting models.NotificationSettings
+ err := s.db.WithContext(ctx).Where("provider = ?", provider).First(&setting).Error
+ existingConfig := models.JSON(nil)
+ if err == nil {
+ existingConfig = setting.Config
+ }
+
// Clear config if provider is disabled
if !enabled {
config = models.JSON{}
}
- err := s.db.WithContext(ctx).Where("provider = ?", provider).First(&setting).Error
+ encryptedConfig, encryptErr := encryptNotificationConfigCredentialsInternal(provider, config, existingConfig)
+ if encryptErr != nil {
+ return nil, encryptErr
+ }
+ config = encryptedConfig
+
if err != nil {
setting = models.NotificationSettings{
Provider: provider,
@@ -290,6 +315,82 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provid
return &setting, nil
}
+// RedactNotificationConfigCredentials returns a copy of config with provider credential fields blanked for API responses.
+func RedactNotificationConfigCredentials(provider models.NotificationProvider, config models.JSON) models.JSON {
+ redacted := cloneNotificationConfigInternal(config)
+ for _, field := range notificationCredentialFieldsByProviderInternal[provider] {
+ value, ok := redacted[field]
+ if !ok {
+ continue
+ }
+ if value == "" {
+ delete(redacted, field)
+ continue
+ }
+ redacted[field] = ""
+ }
+ return redacted
+}
+
+func encryptNotificationConfigCredentialsInternal(provider models.NotificationProvider, config models.JSON, existingConfig models.JSON) (models.JSON, error) {
+ encryptedConfig := cloneNotificationConfigInternal(config)
+ preserveConfig := existingConfig
+ if provider == models.NotificationProviderSignal {
+ preserveConfig = signalCredentialPreservationConfigInternal(config, existingConfig)
+ }
+ for _, field := range notificationCredentialFieldsByProviderInternal[provider] {
+ value, _ := encryptedConfig[field].(string)
+ if value == "" {
+ if existingValue, ok := preserveConfig[field].(string); ok && existingValue != "" {
+ encryptedConfig[field] = existingValue
+ }
+ continue
+ }
+
+ encrypted, err := encryptNotificationCredentialInternal(value)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encrypt notification credential %q: %w", field, err)
+ }
+ encryptedConfig[field] = encrypted
+ }
+ return encryptedConfig, nil
+}
+
+func signalCredentialPreservationConfigInternal(config models.JSON, existingConfig models.JSON) models.JSON {
+ preserveConfig := cloneNotificationConfigInternal(existingConfig)
+ user, _ := config["user"].(string)
+ password, _ := config["password"].(string)
+ token, _ := config["token"].(string)
+
+ if strings.TrimSpace(token) != "" {
+ delete(preserveConfig, "password")
+ }
+ if strings.TrimSpace(user) != "" || strings.TrimSpace(password) != "" {
+ delete(preserveConfig, "token")
+ }
+
+ return preserveConfig
+}
+
+func encryptNotificationCredentialInternal(value string) (string, error) {
+ if value == "" {
+ return "", nil
+ }
+ if _, err := crypto.Decrypt(value); err == nil {
+ return value, nil
+ }
+ return crypto.Encrypt(value)
+}
+
+func cloneNotificationConfigInternal(config models.JSON) models.JSON {
+ if config == nil {
+ return models.JSON{}
+ }
+ cloned := make(models.JSON, len(config))
+ maps.Copy(cloned, config)
+ return cloned
+}
+
func (s *NotificationService) DeleteSettings(ctx context.Context, provider models.NotificationProvider) error {
if err := s.db.WithContext(ctx).Where("provider = ?", provider).Delete(&models.NotificationSettings{}).Error; err != nil {
return fmt.Errorf("failed to delete notification settings: %w", err)
@@ -589,13 +690,8 @@ func (s *NotificationService) sendDiscordNotification(ctx context.Context, envir
return errors.New("discord webhook ID or token not configured")
}
- // Decrypt token if encrypted
- if discordConfig.Token != "" {
- decrypted, err := crypto.Decrypt(discordConfig.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- discordConfig.Token = decrypted
+ if err := decryptStringCredentialInternal(&discordConfig.Token); err != nil {
+ return err
}
message := notifications.BuildImageUpdateNotificationMessage(
@@ -629,13 +725,8 @@ func (s *NotificationService) sendTelegramNotification(ctx context.Context, envi
return errors.New("no telegram chat IDs configured")
}
- // Decrypt bot token if encrypted
- if telegramConfig.BotToken != "" {
- decrypted, err := crypto.Decrypt(telegramConfig.BotToken)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- telegramConfig.BotToken = decrypted
+ if err := decryptStringCredentialInternal(&telegramConfig.BotToken); err != nil {
+ return err
}
message := notifications.BuildImageUpdateNotificationMessage(
@@ -683,12 +774,8 @@ func (s *NotificationService) sendEmailNotification(ctx context.Context, environ
}
}
- if emailConfig.SMTPPassword != "" {
- decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- emailConfig.SMTPPassword = decrypted
+ if err := decryptStringCredentialInternal(&emailConfig.SMTPPassword); err != nil {
+ return err
}
htmlBody, _, err := s.renderEmailTemplate(environmentName, imageRef, updateInfo)
@@ -766,13 +853,8 @@ func (s *NotificationService) sendDiscordContainerUpdateNotification(ctx context
return errors.New("discord webhook ID or token not configured")
}
- // Decrypt token if encrypted
- if discordConfig.Token != "" {
- decrypted, err := crypto.Decrypt(discordConfig.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- discordConfig.Token = decrypted
+ if err := decryptStringCredentialInternal(&discordConfig.Token); err != nil {
+ return err
}
message := notifications.BuildContainerUpdateNotificationMessage(
@@ -808,13 +890,8 @@ func (s *NotificationService) sendTelegramContainerUpdateNotification(ctx contex
return errors.New("no telegram chat IDs configured")
}
- // Decrypt bot token if encrypted
- if telegramConfig.BotToken != "" {
- decrypted, err := crypto.Decrypt(telegramConfig.BotToken)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- telegramConfig.BotToken = decrypted
+ if err := decryptStringCredentialInternal(&telegramConfig.BotToken); err != nil {
+ return err
}
message := notifications.BuildContainerUpdateNotificationMessage(
@@ -864,12 +941,8 @@ func (s *NotificationService) sendEmailContainerUpdateNotification(ctx context.C
}
}
- if emailConfig.SMTPPassword != "" {
- decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- emailConfig.SMTPPassword = decrypted
+ if err := decryptStringCredentialInternal(&emailConfig.SMTPPassword); err != nil {
+ return err
}
htmlBody, _, err := s.renderContainerUpdateEmailTemplate(environmentName, containerName, imageRef, oldDigest, newDigest)
@@ -1224,12 +1297,8 @@ func (s *NotificationService) sendTestEmail(ctx context.Context, environmentName
}
}
- if emailConfig.SMTPPassword != "" {
- decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- emailConfig.SMTPPassword = decrypted
+ if err := decryptStringCredentialInternal(&emailConfig.SMTPPassword); err != nil {
+ return err
}
htmlBody, _, err := s.renderTestEmailTemplate(environmentName)
@@ -1416,13 +1485,8 @@ func (s *NotificationService) sendBatchTelegramNotification(ctx context.Context,
return fmt.Errorf("failed to unmarshal telegram config: %w", err)
}
- // Decrypt bot token
- if telegramConfig.BotToken != "" {
- decrypted, err := crypto.Decrypt(telegramConfig.BotToken)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- telegramConfig.BotToken = decrypted
+ if err := decryptStringCredentialInternal(&telegramConfig.BotToken); err != nil {
+ return err
}
message := notifications.BuildBatchImageUpdateNotificationMessage(
@@ -1469,12 +1533,8 @@ func (s *NotificationService) sendBatchEmailNotification(ctx context.Context, en
}
}
- if emailConfig.SMTPPassword != "" {
- decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- emailConfig.SMTPPassword = decrypted
+ if err := decryptStringCredentialInternal(&emailConfig.SMTPPassword); err != nil {
+ return err
}
htmlBody, _, err := s.renderBatchEmailTemplate(environmentName, updates)
@@ -1580,20 +1640,11 @@ func (s *NotificationService) sendSignalNotification(ctx context.Context, enviro
return errors.New("signal cannot use both basic auth and token authentication simultaneously")
}
- // Decrypt sensitive fields if encrypted
- if signalConfig.Password != "" {
- decrypted, err := crypto.Decrypt(signalConfig.Password)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- signalConfig.Password = decrypted
+ if err := decryptStringCredentialInternal(&signalConfig.Password); err != nil {
+ return err
}
- if signalConfig.Token != "" {
- decrypted, err := crypto.Decrypt(signalConfig.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- signalConfig.Token = decrypted
+ if err := decryptStringCredentialInternal(&signalConfig.Token); err != nil {
+ return err
}
message := notifications.BuildImageUpdateNotificationMessage(
@@ -1643,20 +1694,11 @@ func (s *NotificationService) sendSignalContainerUpdateNotification(ctx context.
return errors.New("signal cannot use both basic auth and token authentication simultaneously")
}
- // Decrypt sensitive fields if encrypted
- if signalConfig.Password != "" {
- decrypted, err := crypto.Decrypt(signalConfig.Password)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- signalConfig.Password = decrypted
+ if err := decryptStringCredentialInternal(&signalConfig.Password); err != nil {
+ return err
}
- if signalConfig.Token != "" {
- decrypted, err := crypto.Decrypt(signalConfig.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- signalConfig.Token = decrypted
+ if err := decryptStringCredentialInternal(&signalConfig.Token); err != nil {
+ return err
}
message := notifications.BuildContainerUpdateNotificationMessage(
@@ -1695,20 +1737,11 @@ func (s *NotificationService) sendBatchSignalNotification(ctx context.Context, e
return errors.New("signal cannot use both basic auth and token authentication simultaneously")
}
- // Decrypt sensitive fields if encrypted
- if signalConfig.Password != "" {
- decrypted, err := crypto.Decrypt(signalConfig.Password)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- signalConfig.Password = decrypted
+ if err := decryptStringCredentialInternal(&signalConfig.Password); err != nil {
+ return err
}
- if signalConfig.Token != "" {
- decrypted, err := crypto.Decrypt(signalConfig.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- signalConfig.Token = decrypted
+ if err := decryptStringCredentialInternal(&signalConfig.Token); err != nil {
+ return err
}
message := notifications.BuildBatchImageUpdateNotificationMessage(
@@ -2046,12 +2079,8 @@ func (s *NotificationService) sendEmailVulnerabilityNotification(ctx context.Con
return fmt.Errorf("invalid to address %s: %w", addr, err)
}
}
- if emailConfig.SMTPPassword != "" {
- decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- emailConfig.SMTPPassword = decrypted
+ if err := decryptStringCredentialInternal(&emailConfig.SMTPPassword); err != nil {
+ return err
}
htmlBody, _, err := s.renderVulnerabilitySummaryEmailTemplate(environmentName, payload)
if err != nil {
@@ -2076,12 +2105,8 @@ func (s *NotificationService) sendDiscordVulnerabilityNotification(ctx context.C
if discordConfig.WebhookID == "" || discordConfig.Token == "" {
return errors.New("discord webhook ID or token not configured")
}
- if discordConfig.Token != "" {
- decrypted, err := crypto.Decrypt(discordConfig.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- discordConfig.Token = decrypted
+ if err := decryptStringCredentialInternal(&discordConfig.Token); err != nil {
+ return err
}
message := notifications.BuildVulnerabilitySummaryNotificationMessage(
notifications.MessageFormatMarkdown,
@@ -2113,12 +2138,8 @@ func (s *NotificationService) sendTelegramVulnerabilityNotification(ctx context.
if len(telegramConfig.ChatIDs) == 0 {
return errors.New("no telegram chat IDs configured")
}
- if telegramConfig.BotToken != "" {
- decrypted, err := crypto.Decrypt(telegramConfig.BotToken)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- telegramConfig.BotToken = decrypted
+ if err := decryptStringCredentialInternal(&telegramConfig.BotToken); err != nil {
+ return err
}
if telegramConfig.ParseMode == "" {
telegramConfig.ParseMode = "HTML"
@@ -2150,19 +2171,11 @@ func (s *NotificationService) sendSignalVulnerabilityNotification(ctx context.Co
if signalConfig.Host == "" || signalConfig.Port == 0 || signalConfig.Source == "" || len(signalConfig.Recipients) == 0 {
return errors.New("signal not fully configured")
}
- if signalConfig.Password != "" {
- decrypted, err := crypto.Decrypt(signalConfig.Password)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- signalConfig.Password = decrypted
+ if err := decryptStringCredentialInternal(&signalConfig.Password); err != nil {
+ return err
}
- if signalConfig.Token != "" {
- decrypted, err := crypto.Decrypt(signalConfig.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- signalConfig.Token = decrypted
+ if err := decryptStringCredentialInternal(&signalConfig.Token); err != nil {
+ return err
}
message := notifications.BuildVulnerabilitySummaryNotificationMessage(
notifications.MessageFormatPlain,
@@ -2519,7 +2532,7 @@ func (s *NotificationService) sendDiscordPruneNotification(ctx context.Context,
return errors.New("discord webhook ID or token not configured")
}
- if err := s.decryptDiscordTokenInternal(&discordConfig); err != nil {
+ if err := decryptStringCredentialInternal(&discordConfig.Token); err != nil {
return err
}
@@ -2542,7 +2555,7 @@ func (s *NotificationService) sendTelegramPruneNotification(ctx context.Context,
return errors.New("telegram bot token or chat IDs not configured")
}
- if err := s.decryptTelegramTokenInternal(&telegramConfig); err != nil {
+ if err := decryptStringCredentialInternal(&telegramConfig.BotToken); err != nil {
return err
}
@@ -2569,7 +2582,7 @@ func (s *NotificationService) sendEmailPruneNotification(ctx context.Context, en
return err
}
- if err := s.decryptEmailPasswordInternal(&emailConfig); err != nil {
+ if err := decryptStringCredentialInternal(&emailConfig.SMTPPassword); err != nil {
return err
}
@@ -2657,12 +2670,8 @@ func (s *NotificationService) sendGotifyPruneNotification(ctx context.Context, e
if err := s.unmarshalConfigInternal(config, &gotifyConfig); err != nil {
return err
}
- if gotifyConfig.Token != "" {
- decrypted, err := crypto.Decrypt(gotifyConfig.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- gotifyConfig.Token = decrypted
+ if err := decryptStringCredentialInternal(&gotifyConfig.Token); err != nil {
+ return err
}
message := notifications.BuildPruneReportNotificationMessage(notifications.MessageFormatPlain, environmentName, result)
@@ -2761,7 +2770,7 @@ func (s *NotificationService) sendDiscordAutoHealNotification(ctx context.Contex
if discordConfig.WebhookID == "" || discordConfig.Token == "" {
return errors.New("discord webhook ID or token not configured")
}
- if err := s.decryptDiscordTokenInternal(&discordConfig); err != nil {
+ if err := decryptStringCredentialInternal(&discordConfig.Token); err != nil {
return err
}
message := notifications.BuildAutoHealNotificationMessage(notifications.MessageFormatMarkdown, environmentName, containerName)
@@ -2776,7 +2785,7 @@ func (s *NotificationService) sendEmailAutoHealNotification(ctx context.Context,
if err := s.validateEmailConfigInternal(&emailConfig); err != nil {
return err
}
- if err := s.decryptEmailPasswordInternal(&emailConfig); err != nil {
+ if err := decryptStringCredentialInternal(&emailConfig.SMTPPassword); err != nil {
return err
}
subject := notifications.BuildEmailSubject(environmentName, fmt.Sprintf("Auto Heal: Container '%s' Restarted", containerName))
@@ -2796,7 +2805,7 @@ func (s *NotificationService) sendTelegramAutoHealNotification(ctx context.Conte
if telegramConfig.BotToken == "" || len(telegramConfig.ChatIDs) == 0 {
return errors.New("telegram bot token or chat IDs not configured")
}
- if err := s.decryptTelegramTokenInternal(&telegramConfig); err != nil {
+ if err := decryptStringCredentialInternal(&telegramConfig.BotToken); err != nil {
return err
}
if telegramConfig.ParseMode == "" {
@@ -2850,12 +2859,8 @@ func (s *NotificationService) sendGotifyAutoHealNotification(ctx context.Context
if err := s.unmarshalConfigInternal(config, &gotifyConfig); err != nil {
return err
}
- if gotifyConfig.Token != "" {
- decrypted, err := crypto.Decrypt(gotifyConfig.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- gotifyConfig.Token = decrypted
+ if err := decryptStringCredentialInternal(&gotifyConfig.Token); err != nil {
+ return err
}
if gotifyConfig.Title == "" {
gotifyConfig.Title = notifications.BuildEmailSubject(environmentName, "Auto Heal")
@@ -2924,12 +2929,25 @@ func decryptStringCredentialInternal(value *string) error {
decrypted, err := crypto.Decrypt(*value)
if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
+ if isPlausibleEncryptedCredentialInternal(*value) {
+ return fmt.Errorf("failed to decrypt notification credential: %w", err)
+ }
+ slog.Warn("Failed to decrypt notification credential, using raw legacy value", "error", err)
+ return nil
}
*value = decrypted
return nil
}
+func isPlausibleEncryptedCredentialInternal(value string) bool {
+ data, err := base64.StdEncoding.DecodeString(value)
+ if err != nil {
+ return false
+ }
+ const minAESGCMCiphertextSize = 12 + 16
+ return len(data) >= minAESGCMCiphertextSize
+}
+
func prepareSlackConfigInternal(config models.JSON, providerName string, requireToken bool) (models.SlackConfig, error) {
slackConfig, err := decodeNotificationConfigInternal[models.SlackConfig](config, providerName)
if err != nil {
@@ -3003,39 +3021,6 @@ func buildVulnerabilitySummaryMessageInternal(format notifications.MessageFormat
)
}
-func (s *NotificationService) decryptDiscordTokenInternal(config *models.DiscordConfig) error {
- if config.Token != "" {
- decrypted, err := crypto.Decrypt(config.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- config.Token = decrypted
- }
- return nil
-}
-
-func (s *NotificationService) decryptTelegramTokenInternal(config *models.TelegramConfig) error {
- if config.BotToken != "" {
- decrypted, err := crypto.Decrypt(config.BotToken)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- config.BotToken = decrypted
- }
- return nil
-}
-
-func (s *NotificationService) decryptEmailPasswordInternal(config *models.EmailConfig) error {
- if config.SMTPPassword != "" {
- decrypted, err := crypto.Decrypt(config.SMTPPassword)
- if err != nil {
- return fmt.Errorf("failed to decrypt notification credential: %w", err)
- }
- config.SMTPPassword = decrypted
- }
- return nil
-}
-
func (s *NotificationService) renderTemplatesInternal(name string, data any) (string, string, error) {
htmlContent, err := resources.FS.ReadFile(fmt.Sprintf("email-templates/%s_html.tmpl", name))
if err != nil {
diff --git a/backend/internal/services/notification_service_test.go b/backend/internal/services/notification_service_test.go
index 741b97ff8..bad4abd89 100644
--- a/backend/internal/services/notification_service_test.go
+++ b/backend/internal/services/notification_service_test.go
@@ -3,6 +3,7 @@ package services
import (
"bytes"
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"log/slog"
@@ -436,6 +437,130 @@ func TestBuildAutoHealNotificationMessageInternal_IncludesEnvironment(t *testing
require.Equal(t, 1, strings.Count(message, "Environment"))
}
+func TestNotificationCredentialInternal_KeepsPlaintextLegacyValues(t *testing.T) {
+ setupNotificationTestDB(t)
+
+ value := "discord-webhook-token/plaintext"
+
+ require.NoError(t, decryptStringCredentialInternal(&value))
+ require.Equal(t, "discord-webhook-token/plaintext", value)
+}
+
+func TestNotificationCredentialInternal_DecryptsEncryptedValues(t *testing.T) {
+ setupNotificationTestDB(t)
+
+ encrypted, err := crypto.Encrypt("gotify-application-token")
+ require.NoError(t, err)
+
+ require.NoError(t, decryptStringCredentialInternal(&encrypted))
+ require.Equal(t, "gotify-application-token", encrypted)
+}
+
+func TestNotificationCredentialInternal_ReturnsErrorForCorruptedCiphertext(t *testing.T) {
+ setupNotificationTestDB(t)
+
+ encrypted, err := crypto.Encrypt("gotify-application-token")
+ require.NoError(t, err)
+
+ ciphertext, err := base64.StdEncoding.DecodeString(encrypted)
+ require.NoError(t, err)
+ ciphertext[len(ciphertext)-1] ^= 0xff
+ corrupted := base64.StdEncoding.EncodeToString(ciphertext)
+
+ require.Error(t, decryptStringCredentialInternal(&corrupted))
+}
+
+func TestNotificationCredentialInternal_LeavesEmptyValuesEmpty(t *testing.T) {
+ setupNotificationTestDB(t)
+
+ value := ""
+
+ require.NoError(t, decryptStringCredentialInternal(&value))
+ require.Empty(t, value)
+}
+
+func TestNotificationService_CreateOrUpdateSettingsEncryptsCredentialFieldsInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ svc := NewNotificationService(db, &config.Config{}, nil)
+
+ _, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderDiscord, true, models.JSON{
+ "webhookId": "123456789",
+ "token": "discord-secret-token",
+ "username": "Arcane",
+ })
+ require.NoError(t, err)
+
+ var stored models.NotificationSettings
+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderDiscord).First(&stored).Error)
+ require.Equal(t, "123456789", stored.Config["webhookId"])
+ require.Equal(t, "Arcane", stored.Config["username"])
+ require.NotEqual(t, "discord-secret-token", stored.Config["token"])
+
+ decrypted, err := crypto.Decrypt(stored.Config["token"].(string))
+ require.NoError(t, err)
+ require.Equal(t, "discord-secret-token", decrypted)
+}
+
+func TestNotificationService_CreateOrUpdateSettingsPreservesStoredCredentialWhenEmptyInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ svc := NewNotificationService(db, &config.Config{}, nil)
+
+ _, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{
+ "host": "gotify.example",
+ "token": "initial-gotify-token",
+ "title": "Initial",
+ })
+ require.NoError(t, err)
+
+ _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{
+ "host": "gotify.example",
+ "token": "",
+ "title": "Updated",
+ })
+ require.NoError(t, err)
+
+ var stored models.NotificationSettings
+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderGotify).First(&stored).Error)
+ require.Equal(t, "Updated", stored.Config["title"])
+
+ decrypted, err := crypto.Decrypt(stored.Config["token"].(string))
+ require.NoError(t, err)
+ require.Equal(t, "initial-gotify-token", decrypted)
+}
+
+func TestNotificationService_CreateOrUpdateSettingsPreservesCredentialAcrossDisableInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ svc := NewNotificationService(db, &config.Config{}, nil)
+
+ _, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{
+ "host": "gotify.example",
+ "token": "initial-gotify-token",
+ "title": "Initial",
+ })
+ require.NoError(t, err)
+
+ _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, false, models.JSON{})
+ require.NoError(t, err)
+
+ _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{
+ "host": "gotify.example",
+ "token": "",
+ "title": "Re-enabled",
+ })
+ require.NoError(t, err)
+
+ var stored models.NotificationSettings
+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderGotify).First(&stored).Error)
+ require.Equal(t, "Re-enabled", stored.Config["title"])
+
+ decrypted, err := crypto.Decrypt(stored.Config["token"].(string))
+ require.NoError(t, err)
+ require.Equal(t, "initial-gotify-token", decrypted)
+}
+
func TestSupportedNotificationTestTypes_IncludesAutoHeal(t *testing.T) {
expected := []string{
notificationTestTypeSimple,
diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.go
index 62212a6f7..f25a1edb5 100644
--- a/backend/internal/services/version_service.go
+++ b/backend/internal/services/version_service.go
@@ -129,6 +129,10 @@ func (s *VersionService) normalizeVersion(ver string) string {
if ver == "" {
return "v0.0.0"
}
+ trimmed := strings.TrimPrefix(ver, "v")
+ if trimmed == "" || trimmed[0] < '0' || trimmed[0] > '9' {
+ return ver
+ }
if !strings.HasPrefix(ver, "v") {
ver = "v" + ver
}
diff --git a/backend/internal/services/version_service_test.go b/backend/internal/services/version_service_test.go
index f30925041..8fef78217 100644
--- a/backend/internal/services/version_service_test.go
+++ b/backend/internal/services/version_service_test.go
@@ -106,3 +106,14 @@ func TestVersionService_GetAppVersionInfoDoesNotUseStoredDigestUpdateForSemverBu
assert.Equal(t, latestDigest, info.NewestDigest)
assert.Equal(t, currentDigest, info.CurrentDigest)
}
+
+func TestVersionService_GetAppVersionInfoPreservesDevVersionInternal(t *testing.T) {
+ svc := NewVersionService(nil, true, "dev", "unknown", nil, nil, nil)
+
+ info := svc.GetAppVersionInfo(context.Background())
+
+ require.NotNil(t, info)
+ assert.Equal(t, "dev", info.CurrentVersion)
+ assert.Equal(t, "dev", info.DisplayVersion)
+ assert.False(t, info.IsSemverVersion)
+}
diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelte
index 6e56e01bf..e209e7d2a 100644
--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte
@@ -139,6 +139,10 @@
genericHasChanges
);
+ function hasSavedCredential(settings: NotificationSettings | null, field: string) {
+ return settings?.config ? Object.prototype.hasOwnProperty.call(settings.config, field) : false;
+ }
+
// Sync with settings form context
$effect(() => {
if (formState) {
@@ -268,8 +272,7 @@
if (signalHasChanges) {
try {
const settings = signalFormValuesToSettings(signalValues);
- await notificationService.updateSettings('signal', settings);
- savedSettings.signal = settings;
+ savedSettings.signal = await notificationService.updateSettings('signal', settings);
signalBaseline = { ...signalValues };
} catch (error: any) {
const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
@@ -438,6 +441,7 @@
bind:values={emailValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.email !== null}
onTest={(testType) => testNotification('email', testType)}
/>
</Tabs.Content>
@@ -449,6 +453,7 @@
bind:values={discordValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.discord !== null}
onTest={(testType) => testNotification('discord', testType)}
/>
</Tabs.Content>
@@ -460,6 +465,7 @@
bind:values={telegramValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.telegram !== null}
onTest={(testType) => testNotification('telegram', testType)}
/>
</Tabs.Content>
@@ -471,6 +477,9 @@
bind:values={signalValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.signal !== null}
+ hasExistingPassword={hasSavedCredential(savedSettings.signal, 'password')}
+ hasExistingToken={hasSavedCredential(savedSettings.signal, 'token')}
onTest={(testType) => testNotification('signal', testType)}
/>
</Tabs.Content>
@@ -482,6 +491,7 @@
bind:values={slackValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.slack !== null}
onTest={(testType) => testNotification('slack', testType)}
/>
</Tabs.Content>
@@ -493,6 +503,7 @@
bind:values={ntfyValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.ntfy !== null}
onTest={(testType) => testNotification('ntfy', testType)}
/>
</Tabs.Content>
@@ -504,6 +515,7 @@
bind:values={pushoverValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.pushover !== null}
onTest={(testType) => testNotification('pushover', testType)}
/>
</Tabs.Content>
@@ -515,6 +527,7 @@
bind:values={gotifyValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.gotify !== null}
onTest={(testType) => testNotification('gotify', testType)}
/>
</Tabs.Content>
@@ -526,6 +539,7 @@
bind:values={matrixValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.matrix !== null}
onTest={(testType) => testNotification('matrix', testType)}
/>
</Tabs.Content>
@@ -537,6 +551,7 @@
bind:values={genericValues}
disabled={isReadOnly}
{isTesting}
+ hasExistingCredentials={savedSettings.generic !== null}
onTest={(testType) => testNotification('generic', testType)}
/>
</Tabs.Content>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte
index 239e23ecd..982cd03ec 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte
@@ -16,10 +16,22 @@
values: AnyBuiltInValues;
disabled?: boolean;
isTesting?: boolean;
+ hasExistingCredentials?: boolean;
+ hasExistingPassword?: boolean;
+ hasExistingToken?: boolean;
onTest?: (testType?: string) => void;
}
- let { provider, values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
+ let {
+ provider,
+ values = $bindable(),
+ disabled = false,
+ isTesting = false,
+ hasExistingCredentials = false,
+ hasExistingPassword = false,
+ hasExistingToken = false,
+ onTest
+ }: Props = $props();
const providerMeta: Record<NotificationProviderKey, { title: string; description: string }> = {
discord: {
@@ -82,6 +94,12 @@
}
}
+ function addRequiredCredentialIssue(ctx: z.RefinementCtx, value: string, path: string, message: string) {
+ if (!value.trim() && !hasExistingCredentials) {
+ addCustomFieldIssue(ctx, path, message);
+ }
+ }
+
const providerSchemas: Record<NotificationProviderKey, z.ZodTypeAny> = {
discord: z
.object({
@@ -95,7 +113,7 @@
.superRefine((d, ctx) => {
if (!d.enabled) return;
addRequiredTrimmedFieldIssue(ctx, d.webhookId, 'webhookId', 'Webhook ID is required when Discord is enabled');
- addRequiredTrimmedFieldIssue(ctx, d.token, 'token', 'Webhook Token is required when Discord is enabled');
+ addRequiredCredentialIssue(ctx, d.token, 'token', 'Webhook Token is required when Discord is enabled');
}),
email: z
.object({
@@ -160,7 +178,7 @@
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- addRequiredTrimmedFieldIssue(ctx, d.botToken, 'botToken', 'Bot Token is required when Telegram is enabled');
+ addRequiredCredentialIssue(ctx, d.botToken, 'botToken', 'Bot Token is required when Telegram is enabled');
if (!d.chatIds.trim()) {
ctx.addIssue({
code: 'custom',
@@ -203,8 +221,16 @@
ctx.addIssue({ code: 'custom', message: m.notifications_signal_recipients_required(), path: ['recipients'] });
}
- const hasBasicAuth = d.user.trim() && d.password.trim();
- const hasTokenAuth = d.token.trim();
+ const wantsBasicAuth = Boolean(d.user.trim() || d.password.trim());
+ const hasBasicAuth = Boolean(d.user.trim() && (d.password.trim() || hasExistingPassword));
+ const hasTokenAuth = Boolean(d.token.trim() || (!wantsBasicAuth && hasExistingToken));
+ if (d.user.trim() && !d.password.trim() && !hasExistingPassword) {
+ ctx.addIssue({
+ code: 'custom',
+ message: m.notifications_signal_auth_required(),
+ path: ['password']
+ });
+ }
if (!hasBasicAuth && !hasTokenAuth) {
ctx.addIssue({
code: 'custom',
@@ -234,7 +260,7 @@
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- addRequiredTrimmedFieldIssue(ctx, d.token, 'token', m.notifications_slack_token_required());
+ addRequiredCredentialIssue(ctx, d.token, 'token', m.notifications_slack_token_required());
}),
ntfy: z
.object({
@@ -272,7 +298,7 @@
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- addRequiredTrimmedFieldIssue(ctx, d.token, 'token', m.common_required());
+ addRequiredCredentialIssue(ctx, d.token, 'token', m.common_required());
addRequiredTrimmedFieldIssue(ctx, d.user, 'user', m.common_required());
}),
gotify: z
@@ -290,7 +316,7 @@
.superRefine((d, ctx) => {
if (!d.enabled) return;
addRequiredTrimmedFieldIssue(ctx, d.host, 'host', m.common_required());
- addRequiredTrimmedFieldIssue(ctx, d.token, 'token', m.common_required());
+ addRequiredCredentialIssue(ctx, d.token, 'token', m.common_required());
}),
matrix: z
.object({