PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (notifiers): Add Mattermost with incoming webhook and bot modes (issue #720)
Rostislav Dugine327fbc9739d
diff --git a/README.md b/README.mdindex abb488bf..df50c41a 100644--- a/README.md+++ b/README.md@@ -75,7 +75,7 @@ Databasus performs a real restore to confirm backups are usable, not just intact### 📱 **Notifications** <a href="https://databasus.com/notifiers">(view supported)</a>-- **Multiple channels**: Email, Telegram, Slack, Discord, webhooks+- **Multiple channels**: Email, Telegram, Slack, Discord, Teams, Mattermost, webhooks- **Real-time updates**: Success and failure notifications- **Team integration**: Perfect for DevOps workflows@@ -244,7 +244,7 @@ For more options (NodePort, TLS, HTTPRoute for Gateway API), see the [Helm chart4. **Set database connection**: Enter your database credentials and connection details5. **Choose storage**: Select where to store your backups (local, S3, Google Drive, etc.)6. **Configure retention policy**: Choose time period, count or GFS to control how long backups are kept-7. **Add notifications** (optional): Configure email, Telegram, Slack, or webhook notifications+7. **Add notifications** (optional): Configure email, Telegram, Slack, Mattermost or webhook notifications8. **Save and start**: Databasus will validate settings and begin the backup schedule### 🔑 Resetting password <a href="https://databasus.com/password">(docs)</a>diff --git a/backend/internal/features/notifiers/controller_test.go b/backend/internal/features/notifiers/controller_test.goindex b4fa26b4..bf396fc3 100644--- a/backend/internal/features/notifiers/controller_test.go+++ b/backend/internal/features/notifiers/controller_test.go@@ -12,6 +12,7 @@ import (audit_logs "databasus-backend/internal/features/audit_logs"discord_notifier "databasus-backend/internal/features/notifiers/models/discord"email_notifier "databasus-backend/internal/features/notifiers/models/email_notifier"+ mattermost_notifier "databasus-backend/internal/features/notifiers/models/mattermost"slack_notifier "databasus-backend/internal/features/notifiers/models/slack"teams_notifier "databasus-backend/internal/features/notifiers/models/teams"telegram_notifier "databasus-backend/internal/features/notifiers/models/telegram"@@ -682,6 +683,98 @@ func Test_NotifierSensitiveDataLifecycle_AllTypes(t *testing.T) {assert.Equal(t, "", notifier.TeamsNotifier.WebhookURL)},},+ {+ name: "Mattermost Notifier - incoming webhook mode",+ notifierType: NotifierTypeMattermost,+ createNotifier: func(workspaceID uuid.UUID) *Notifier {+ return &Notifier{+ WorkspaceID: workspaceID,+ Name: "Test Mattermost Webhook Notifier",+ NotifierType: NotifierTypeMattermost,+ MattermostNotifier: &mattermost_notifier.MattermostNotifier{+ DeliveryMode: mattermost_notifier.DeliveryModeWebhook,+ WebhookURL: "https://mattermost.example.com/hooks/original-key",+ TargetChannelName: "town-square",+ },+ }+ },+ updateNotifier: func(workspaceID, notifierID uuid.UUID) *Notifier {+ return &Notifier{+ ID: notifierID,+ WorkspaceID: workspaceID,+ Name: "Updated Mattermost Webhook Notifier",+ NotifierType: NotifierTypeMattermost,+ MattermostNotifier: &mattermost_notifier.MattermostNotifier{+ DeliveryMode: mattermost_notifier.DeliveryModeWebhook,+ WebhookURL: "",+ TargetChannelName: "off-topic",+ },+ }+ },+ verifySensitiveData: func(t *testing.T, notifier *Notifier) {+ assert.True(+ t,+ isEncrypted(notifier.MattermostNotifier.WebhookURL),+ "WebhookURL should be encrypted in DB",+ )+ decrypted := decryptField(t, notifier.MattermostNotifier.WebhookURL)+ assert.Equal(t, "https://mattermost.example.com/hooks/original-key", decrypted)+ assert.Equal(t, "off-topic", notifier.MattermostNotifier.TargetChannelName)+ },+ verifyHiddenData: func(t *testing.T, notifier *Notifier) {+ assert.Equal(t, "", notifier.MattermostNotifier.WebhookURL)+ assert.NotEmpty(t, notifier.MattermostNotifier.TargetChannelName)+ },+ },+ {+ name: "Mattermost Notifier - bot account mode",+ notifierType: NotifierTypeMattermost,+ createNotifier: func(workspaceID uuid.UUID) *Notifier {+ return &Notifier{+ WorkspaceID: workspaceID,+ Name: "Test Mattermost Bot Notifier",+ NotifierType: NotifierTypeMattermost,+ MattermostNotifier: &mattermost_notifier.MattermostNotifier{+ DeliveryMode: mattermost_notifier.DeliveryModeBot,+ ServerURL: "https://mattermost.example.com",+ BotToken: "original-mattermost-bot-token",+ TargetChannelID: "abcdefghijklmnopqrstuvwxyz",+ },+ }+ },+ updateNotifier: func(workspaceID, notifierID uuid.UUID) *Notifier {+ return &Notifier{+ ID: notifierID,+ WorkspaceID: workspaceID,+ Name: "Updated Mattermost Bot Notifier",+ NotifierType: NotifierTypeMattermost,+ MattermostNotifier: &mattermost_notifier.MattermostNotifier{+ DeliveryMode: mattermost_notifier.DeliveryModeBot,+ ServerURL: "https://mattermost.internal.example.com",+ BotToken: "",+ TargetChannelID: "zyxwvutsrqponmlkjihgfedcba",+ },+ }+ },+ verifySensitiveData: func(t *testing.T, notifier *Notifier) {+ assert.True(+ t,+ isEncrypted(notifier.MattermostNotifier.BotToken),+ "BotToken should be encrypted in DB",+ )+ decrypted := decryptField(t, notifier.MattermostNotifier.BotToken)+ assert.Equal(t, "original-mattermost-bot-token", decrypted)+ assert.Equal(+ t,+ "https://mattermost.internal.example.com",+ notifier.MattermostNotifier.ServerURL,+ )+ },+ verifyHiddenData: func(t *testing.T, notifier *Notifier) {+ assert.Equal(t, "", notifier.MattermostNotifier.BotToken)+ assert.NotEmpty(t, notifier.MattermostNotifier.ServerURL)+ },+ },{name: "Webhook Notifier",notifierType: NotifierTypeWebhook,@@ -960,6 +1053,60 @@ func Test_CreateNotifier_AllSensitiveFieldsEncryptedInDB(t *testing.T) {assert.Equal(t, "https://outlook.office.com/webhook/test123", decrypted)},},+ {+ name: "Mattermost Notifier - incoming webhook URL encrypted",+ createNotifier: func(workspaceID uuid.UUID) *Notifier {+ return &Notifier{+ WorkspaceID: workspaceID,+ Name: "Test Mattermost Webhook",+ NotifierType: NotifierTypeMattermost,+ MattermostNotifier: &mattermost_notifier.MattermostNotifier{+ DeliveryMode: mattermost_notifier.DeliveryModeWebhook,+ WebhookURL: "https://mattermost.example.com/hooks/plain-key-123",+ },+ }+ },+ verifySensitiveEncryption: func(t *testing.T, notifier *Notifier) {+ assert.True(+ t,+ isEncrypted(notifier.MattermostNotifier.WebhookURL),+ "WebhookURL should be encrypted",+ )+ decrypted := decryptField(t, notifier.MattermostNotifier.WebhookURL)+ assert.Equal(t, "https://mattermost.example.com/hooks/plain-key-123", decrypted)+ },+ },+ {+ name: "Mattermost Notifier - BotToken encrypted, ServerURL not encrypted",+ createNotifier: func(workspaceID uuid.UUID) *Notifier {+ return &Notifier{+ WorkspaceID: workspaceID,+ Name: "Test Mattermost Bot",+ NotifierType: NotifierTypeMattermost,+ MattermostNotifier: &mattermost_notifier.MattermostNotifier{+ DeliveryMode: mattermost_notifier.DeliveryModeBot,+ ServerURL: "https://mattermost.example.com",+ BotToken: "plain-mattermost-token-321",+ TargetChannelID: "abcdefghijklmnopqrstuvwxyz",+ },+ }+ },+ verifySensitiveEncryption: func(t *testing.T, notifier *Notifier) {+ assert.True(+ t,+ isEncrypted(notifier.MattermostNotifier.BotToken),+ "BotToken should be encrypted",+ )+ decrypted := decryptField(t, notifier.MattermostNotifier.BotToken)+ assert.Equal(t, "plain-mattermost-token-321", decrypted)++ assert.False(+ t,+ isEncrypted(notifier.MattermostNotifier.ServerURL),+ "ServerURL should NOT be encrypted",+ )+ },+ },{name: "Webhook Notifier - Header values encrypted, URL not encrypted",createNotifier: func(workspaceID uuid.UUID) *Notifier {diff --git a/backend/internal/features/notifiers/enums.go b/backend/internal/features/notifiers/enums.goindex 5dc38e81..006c22b2 100644--- a/backend/internal/features/notifiers/enums.go+++ b/backend/internal/features/notifiers/enums.go@@ -3,10 +3,11 @@ package notifierstype NotifierType stringconst (- NotifierTypeEmail NotifierType = "EMAIL"- NotifierTypeTelegram NotifierType = "TELEGRAM"- NotifierTypeWebhook NotifierType = "WEBHOOK"- NotifierTypeSlack NotifierType = "SLACK"- NotifierTypeDiscord NotifierType = "DISCORD"- NotifierTypeTeams NotifierType = "TEAMS"+ NotifierTypeEmail NotifierType = "EMAIL"+ NotifierTypeTelegram NotifierType = "TELEGRAM"+ NotifierTypeWebhook NotifierType = "WEBHOOK"+ NotifierTypeSlack NotifierType = "SLACK"+ NotifierTypeDiscord NotifierType = "DISCORD"+ NotifierTypeTeams NotifierType = "TEAMS"+ NotifierTypeMattermost NotifierType = "MATTERMOST")diff --git a/backend/internal/features/notifiers/model.go b/backend/internal/features/notifiers/model.goindex b5bb1fb4..7d0ca826 100644--- a/backend/internal/features/notifiers/model.go+++ b/backend/internal/features/notifiers/model.go@@ -9,6 +9,7 @@ import (notifier_models "databasus-backend/internal/features/notifiers/models"discord_notifier "databasus-backend/internal/features/notifiers/models/discord""databasus-backend/internal/features/notifiers/models/email_notifier"+ mattermost_notifier "databasus-backend/internal/features/notifiers/models/mattermost"slack_notifier "databasus-backend/internal/features/notifiers/models/slack"teams_notifier "databasus-backend/internal/features/notifiers/models/teams"telegram_notifier "databasus-backend/internal/features/notifiers/models/telegram"@@ -24,12 +25,13 @@ type Notifier struct {LastSendError *string `json:"lastSendError" gorm:"column:last_send_error;type:text"`// specific notifier- TelegramNotifier *telegram_notifier.TelegramNotifier `json:"telegramNotifier" gorm:"foreignKey:NotifierID"`- EmailNotifier *email_notifier.EmailNotifier `json:"emailNotifier" gorm:"foreignKey:NotifierID"`- WebhookNotifier *webhook_notifier.WebhookNotifier `json:"webhookNotifier" gorm:"foreignKey:NotifierID"`- SlackNotifier *slack_notifier.SlackNotifier `json:"slackNotifier" gorm:"foreignKey:NotifierID"`- DiscordNotifier *discord_notifier.DiscordNotifier `json:"discordNotifier" gorm:"foreignKey:NotifierID"`- TeamsNotifier *teams_notifier.TeamsNotifier `json:"teamsNotifier,omitzero" gorm:"foreignKey:NotifierID;constraint:OnDelete:CASCADE"`+ TelegramNotifier *telegram_notifier.TelegramNotifier `json:"telegramNotifier" gorm:"foreignKey:NotifierID"`+ EmailNotifier *email_notifier.EmailNotifier `json:"emailNotifier" gorm:"foreignKey:NotifierID"`+ WebhookNotifier *webhook_notifier.WebhookNotifier `json:"webhookNotifier" gorm:"foreignKey:NotifierID"`+ SlackNotifier *slack_notifier.SlackNotifier `json:"slackNotifier" gorm:"foreignKey:NotifierID"`+ DiscordNotifier *discord_notifier.DiscordNotifier `json:"discordNotifier" gorm:"foreignKey:NotifierID"`+ TeamsNotifier *teams_notifier.TeamsNotifier `json:"teamsNotifier,omitzero" gorm:"foreignKey:NotifierID;constraint:OnDelete:CASCADE"`+ MattermostNotifier *mattermost_notifier.MattermostNotifier `json:"mattermostNotifier" gorm:"foreignKey:NotifierID"`}func (n *Notifier) TableName() string {@@ -98,6 +100,10 @@ func (n *Notifier) Update(incoming *Notifier) {if n.TeamsNotifier != nil && incoming.TeamsNotifier != nil {n.TeamsNotifier.Update(incoming.TeamsNotifier)}+ case NotifierTypeMattermost:+ if n.MattermostNotifier != nil && incoming.MattermostNotifier != nil {+ n.MattermostNotifier.Update(incoming.MattermostNotifier)+ }}}@@ -115,6 +121,8 @@ func (n *Notifier) getSpecificNotifier() NotificationSender {return n.DiscordNotifiercase NotifierTypeTeams:return n.TeamsNotifier+ case NotifierTypeMattermost:+ return n.MattermostNotifierdefault:panic("unknown notifier type: " + string(n.NotifierType))}diff --git a/backend/internal/features/notifiers/models/mattermost/constants.go b/backend/internal/features/notifiers/models/mattermost/constants.gonew file mode 100644index 00000000..328da2db--- /dev/null+++ b/backend/internal/features/notifiers/models/mattermost/constants.go@@ -0,0 +1,19 @@+package mattermost_notifier++import "time"++const (+ // Mattermost rejects longer posts on the REST API and silently splits them on incoming webhooks.+ maxPostLength = 16383++ // Mattermost IDs are always 26 characters, which is how a pasted channel *name* is caught.+ channelIDLength = 26++ // A failed send surfaces the response body to the caller of the test-send endpoint, so a+ // misbehaving server must not be able to push an arbitrarily large body through it.+ maxErrorBodyBytes = 8 * 1024++ sendTimeout = 30 * time.Second++ createPostPath = "/api/v4/posts"+)diff --git a/backend/internal/features/notifiers/models/mattermost/enums.go b/backend/internal/features/notifiers/models/mattermost/enums.gonew file mode 100644index 00000000..e6377f58--- /dev/null+++ b/backend/internal/features/notifiers/models/mattermost/enums.go@@ -0,0 +1,8 @@+package mattermost_notifier++type DeliveryMode string++const (+ DeliveryModeWebhook DeliveryMode = "WEBHOOK"+ DeliveryModeBot DeliveryMode = "BOT"+)diff --git a/backend/internal/features/notifiers/models/mattermost/model.go b/backend/internal/features/notifiers/models/mattermost/model.gonew file mode 100644index 00000000..08f08c2a--- /dev/null+++ b/backend/internal/features/notifiers/models/mattermost/model.go@@ -0,0 +1,362 @@+package mattermost_notifier++import (+ "bytes"+ "context"+ "crypto/tls"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/url"+ "strings"++ "github.com/google/uuid"++ notifier_models "databasus-backend/internal/features/notifiers/models"+ "databasus-backend/internal/util/encryption"+)++type MattermostNotifier struct {+ NotifierID uuid.UUID `json:"notifierId" gorm:"type:uuid;primaryKey;column:notifier_id"`+ DeliveryMode DeliveryMode `json:"deliveryMode" gorm:"type:text;not null;column:delivery_mode"`++ WebhookURL string `json:"webhookUrl" gorm:"type:text;not null;default:'';column:webhook_url"`++ ServerURL string `json:"serverUrl" gorm:"type:text;not null;default:'';column:server_url"`+ BotToken string `json:"botToken" gorm:"type:text;not null;default:'';column:bot_token"`++ TargetChannelName string `json:"targetChannelName" gorm:"type:text;not null;default:'';column:target_channel_name"`+ TargetChannelID string `json:"targetChannelId" gorm:"type:text;not null;default:'';column:target_channel_id"`++ OverrideUsername string `json:"overrideUsername" gorm:"type:text;not null;default:'';column:override_username"`+ OverrideIconURL string `json:"overrideIconUrl" gorm:"type:text;not null;default:'';column:override_icon_url"`++ IsInsecureSkipVerify bool `json:"isInsecureSkipVerify" gorm:"not null;default:false;column:is_insecure_skip_verify"`+}++type mattermostRequest struct {+ URL string+ IsURLSecret bool+ BotToken string+ Payload map[string]any+}++func (m *MattermostNotifier) TableName() string {+ return "mattermost_notifiers"+}++func (m *MattermostNotifier) Validate(encryptor encryption.FieldEncryptor) error {+ if m.OverrideIconURL != "" && !isHTTPURL(m.OverrideIconURL) {+ return errors.New("override icon URL must be an http or https URL")+ }++ switch m.DeliveryMode {+ case DeliveryModeWebhook:+ return m.validateWebhookMode(encryptor)+ case DeliveryModeBot:+ return m.validateBotMode()+ default:+ return fmt.Errorf("delivery mode must be %s or %s", DeliveryModeWebhook, DeliveryModeBot)+ }+}++func (m *MattermostNotifier) Send(+ encryptor encryption.FieldEncryptor,+ logger *slog.Logger,+ notification notifier_models.Notification,+) error {+ postText := buildPost(notification)++ switch m.DeliveryMode {+ case DeliveryModeWebhook:+ return m.sendViaIncomingWebhook(encryptor, logger, postText)+ case DeliveryModeBot:+ return m.sendViaBotAPI(encryptor, logger, postText)+ default:+ return fmt.Errorf("unknown delivery mode: %s", m.DeliveryMode)+ }+}++func (m *MattermostNotifier) HideSensitiveData() {+ m.WebhookURL = ""+ m.BotToken = ""+}++func (m *MattermostNotifier) Update(incoming *MattermostNotifier) {+ m.DeliveryMode = incoming.DeliveryMode+ m.ServerURL = incoming.ServerURL+ m.TargetChannelName = incoming.TargetChannelName+ m.TargetChannelID = incoming.TargetChannelID+ m.OverrideUsername = incoming.OverrideUsername+ m.OverrideIconURL = incoming.OverrideIconURL+ m.IsInsecureSkipVerify = incoming.IsInsecureSkipVerify++ if incoming.WebhookURL != "" {+ m.WebhookURL = incoming.WebhookURL+ }++ if incoming.BotToken != "" {+ m.BotToken = incoming.BotToken+ }+}++func (m *MattermostNotifier) EncryptSensitiveData(encryptor encryption.FieldEncryptor) error {+ if m.WebhookURL != "" {+ encrypted, err := encryptor.Encrypt(m.WebhookURL)+ if err != nil {+ return fmt.Errorf("failed to encrypt incoming webhook URL: %w", err)+ }++ m.WebhookURL = encrypted+ }++ if m.BotToken != "" {+ encrypted, err := encryptor.Encrypt(m.BotToken)+ if err != nil {+ return fmt.Errorf("failed to encrypt bot token: %w", err)+ }++ m.BotToken = encrypted+ }++ return nil+}++func (m *MattermostNotifier) validateWebhookMode(encryptor encryption.FieldEncryptor) error {+ if m.WebhookURL == "" {+ return errors.New("incoming webhook URL is required")+ }++ webhookURL, err := encryptor.Decrypt(m.WebhookURL)+ if err != nil {+ return fmt.Errorf("failed to decrypt incoming webhook URL: %w", err)+ }++ if !isHTTPURL(webhookURL) {+ return errors.New("incoming webhook URL must be an http or https URL")+ }++ return nil+}++func (m *MattermostNotifier) validateBotMode() error {+ if m.ServerURL == "" {+ return errors.New("server URL is required")+ }++ if !isHTTPURL(m.ServerURL) {+ return errors.New("server URL must be an http or https URL")+ }++ if m.BotToken == "" {+ return errors.New("bot token is required")+ }++ if m.TargetChannelID == "" {+ return errors.New("target channel ID is required")+ }++ if len([]rune(m.TargetChannelID)) != channelIDLength {+ return fmt.Errorf(+ "target channel ID must be the %d-character Mattermost channel ID, not the channel name",+ channelIDLength,+ )+ }++ return nil+}++func (m *MattermostNotifier) sendViaIncomingWebhook(+ encryptor encryption.FieldEncryptor,+ logger *slog.Logger,+ postText string,+) error {+ webhookURL, err := encryptor.Decrypt(m.WebhookURL)+ if err != nil {+ return fmt.Errorf("failed to decrypt incoming webhook URL: %w", err)+ }++ payload := map[string]any{"text": postText}++ if m.TargetChannelName != "" {+ payload["channel"] = m.TargetChannelName+ }++ if m.OverrideUsername != "" {+ payload["username"] = m.OverrideUsername+ }++ if m.OverrideIconURL != "" {+ payload["icon_url"] = m.OverrideIconURL+ }++ request := mattermostRequest{URL: webhookURL, IsURLSecret: true, Payload: payload}++ if err := m.sendRequest(request, logger); err != nil {+ return err+ }++ logger.Info("mattermost message sent via incoming webhook")++ return nil+}++func (m *MattermostNotifier) sendViaBotAPI(+ encryptor encryption.FieldEncryptor,+ logger *slog.Logger,+ postText string,+) error {+ botToken, err := encryptor.Decrypt(m.BotToken)+ if err != nil {+ return fmt.Errorf("failed to decrypt bot token: %w", err)+ }++ payload := map[string]any{+ "channel_id": m.TargetChannelID,+ "message": postText,+ }++ props := map[string]any{}++ if m.OverrideUsername != "" {+ props["override_username"] = m.OverrideUsername+ }++ if m.OverrideIconURL != "" {+ props["override_icon_url"] = m.OverrideIconURL+ }++ if len(props) > 0 {+ payload["props"] = props+ }++ createPostURL := strings.TrimSuffix(m.ServerURL, "/") + createPostPath++ request := mattermostRequest{URL: createPostURL, BotToken: botToken, Payload: payload}++ if err := m.sendRequest(request, logger); err != nil {+ return err+ }++ logger.Info("mattermost message sent via bot account", "channel_id", m.TargetChannelID)++ return nil+}++func (m *MattermostNotifier) sendRequest(request mattermostRequest, logger *slog.Logger) error {+ jsonPayload, err := json.Marshal(request.Payload)+ if err != nil {+ return fmt.Errorf("failed to marshal Mattermost payload: %w", err)+ }++ httpRequest, err := http.NewRequestWithContext(+ context.Background(),+ http.MethodPost,+ request.URL,+ bytes.NewReader(jsonPayload),+ )+ if err != nil {+ return fmt.Errorf("failed to create request: %w", request.withoutSecretURL(err))+ }++ httpRequest.Header.Set("Content-Type", "application/json")++ if request.BotToken != "" {+ httpRequest.Header.Set("Authorization", "Bearer "+request.BotToken)+ }++ response, err := m.newHTTPClient().Do(httpRequest)+ if err != nil {+ return fmt.Errorf("failed to send Mattermost message: %w", request.withoutSecretURL(err))+ }++ defer func() {+ if closeErr := response.Body.Close(); closeErr != nil {+ logger.Warn("failed to close response body", "error", closeErr)+ }+ }()++ responseBody, _ := io.ReadAll(io.LimitReader(response.Body, maxErrorBodyBytes))++ if response.StatusCode < 200 || response.StatusCode >= 300 {+ return fmt.Errorf(+ "mattermost returned non-OK status: %s. Error: %s",+ response.Status,+ describeError(responseBody),+ )+ }++ return nil+}++func (m *MattermostNotifier) newHTTPClient() *http.Client {+ client := &http.Client{Timeout: sendTimeout}++ if m.IsInsecureSkipVerify {+ client.Transport = &http.Transport{+ TLSClientConfig: &tls.Config{+ MinVersion: tls.VersionTLS12,+ InsecureSkipVerify: true,+ },+ }+ }++ return client+}++// An incoming webhook URL is itself a credential, and net/http wraps the request URL into every+// transport error, which the test-send endpoints (POST /notifiers/{id}/test and+// POST /notifiers/direct-test) return verbatim to the caller. A bot mode server URL is not a+// secret, so it stays in the error to keep failures diagnosable.+func (r mattermostRequest) withoutSecretURL(err error) error {+ if !r.IsURLSecret {+ return err+ }++ var urlError *url.Error+ if errors.As(err, &urlError) {+ return urlError.Err+ }++ return err+}++func isHTTPURL(candidate string) bool {+ parsed, err := url.Parse(candidate)+ if err != nil {+ return false+ }++ return (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != ""+}++func buildPost(notification notifier_models.Notification) string {+ postText := fmt.Sprintf("**%s**", notification.Heading)++ if notification.Message != "" {+ postText = fmt.Sprintf("%s\n\n%s", postText, notification.Message)+ }++ runes := []rune(postText)+ if len(runes) > maxPostLength {+ return string(runes[:maxPostLength])+ }++ return postText+}++func describeError(responseBody []byte) string {+ var mattermostError struct {+ Message string `json:"message"`+ }++ if err := json.Unmarshal(responseBody, &mattermostError); err == nil &&+ mattermostError.Message != "" {+ return mattermostError.Message+ }++ return string(responseBody)+}diff --git a/backend/internal/features/notifiers/models/mattermost/model_test.go b/backend/internal/features/notifiers/models/mattermost/model_test.gonew file mode 100644index 00000000..28a7d3e7--- /dev/null+++ b/backend/internal/features/notifiers/models/mattermost/model_test.go@@ -0,0 +1,364 @@+package mattermost_notifier++import (+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ notifier_models "databasus-backend/internal/features/notifiers/models"+)++func send(t *testing.T, notifier *MattermostNotifier, notification notifier_models.Notification) error {+ t.Helper()++ return notifier.Send(+ notifier_models.PassthroughEncryptor{},+ slog.New(slog.NewTextHandler(io.Discard, nil)),+ notification,+ )+}++func backupFailedNotification() notifier_models.Notification {+ return notifier_models.Notification{+ Type: notifier_models.NotificationTypeBackupFailed,+ Heading: "Backup failed",+ Message: "mydb: connection refused",+ }+}++func decodeBody(t *testing.T, body string) map[string]any {+ t.Helper()++ var decoded map[string]any++ require.NoError(t, json.Unmarshal([]byte(body), &decoded))++ return decoded+}++func Test_Send_WithWebhookMode_PostsMarkdownTextToHookURL(t *testing.T) {+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK, Body: "ok"},+ )+ notifier := &MattermostNotifier{DeliveryMode: DeliveryModeWebhook, WebhookURL: webhookURL}++ require.NoError(t, send(t, notifier, backupFailedNotification()))++ require.Equal(t, 1, recorder.GetRequestCount())+ request := recorder.GetLastRequest()+ assert.Equal(t, http.MethodPost, request.Method)+ assert.Equal(t, "application/json", request.Headers.Get("Content-Type"))+ assert.Empty(t, request.Headers.Get("Authorization"))++ body := decodeBody(t, request.Body)+ assert.Equal(t, "**Backup failed**\n\nmydb: connection refused", body["text"])+ assert.NotContains(t, body, "channel")+ assert.NotContains(t, body, "username")+ assert.NotContains(t, body, "icon_url")+}++func Test_Send_WithWebhookModeAndOverrides_PostsChannelAndIdentityFields(t *testing.T) {+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK, Body: "ok"},+ )+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeWebhook,+ WebhookURL: webhookURL,+ TargetChannelName: "town-square",+ OverrideUsername: "Databasus",+ OverrideIconURL: "https://databasus.com/icon.png",+ }++ require.NoError(t, send(t, notifier, backupFailedNotification()))++ body := decodeBody(t, recorder.GetLastRequest().Body)+ assert.Equal(t, "town-square", body["channel"])+ assert.Equal(t, "Databasus", body["username"])+ assert.Equal(t, "https://databasus.com/icon.png", body["icon_url"])+}++func Test_Send_WithHeadingOnly_PostsBoldHeadingWithoutTrailingNewlines(t *testing.T) {+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK, Body: "ok"},+ )+ notifier := &MattermostNotifier{DeliveryMode: DeliveryModeWebhook, WebhookURL: webhookURL}++ require.NoError(t, send(t, notifier, notifier_models.Notification{+ Type: notifier_models.NotificationTypeBackupSuccess,+ Heading: "Backup completed",+ }))++ body := decodeBody(t, recorder.GetLastRequest().Body)+ assert.Equal(t, "**Backup completed**", body["text"])+}++func Test_Send_WhenPostExceedsMattermostLimit_TruncatesText(t *testing.T) {+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK, Body: "ok"},+ )+ notifier := &MattermostNotifier{DeliveryMode: DeliveryModeWebhook, WebhookURL: webhookURL}++ require.NoError(t, send(t, notifier, notifier_models.Notification{+ Type: notifier_models.NotificationTypeBackupFailed,+ Heading: "Backup failed",+ Message: strings.Repeat("é", maxPostLength),+ }))++ body := decodeBody(t, recorder.GetLastRequest().Body)+ assert.Equal(t, maxPostLength, len([]rune(body["text"].(string))))+}++func Test_Send_WithBotMode_PostsToCreatePostEndpointWithBearerToken(t *testing.T) {+ serverURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusCreated, Body: `{"id":"post123"}`},+ )+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ ServerURL: serverURL + "/",+ BotToken: "bot-token",+ TargetChannelID: strings.Repeat("c", channelIDLength),+ }++ require.NoError(t, send(t, notifier, backupFailedNotification()))++ request := recorder.GetLastRequest()+ assert.Equal(t, http.MethodPost, request.Method)+ assert.Equal(t, createPostPath, request.Path)+ assert.Equal(t, "Bearer bot-token", request.Headers.Get("Authorization"))++ body := decodeBody(t, request.Body)+ assert.Equal(t, strings.Repeat("c", channelIDLength), body["channel_id"])+ assert.Equal(t, "**Backup failed**\n\nmydb: connection refused", body["message"])+ assert.NotContains(t, body, "props")+}++func Test_Send_WithBotModeAndOverrides_PostsIdentityFieldsInProps(t *testing.T) {+ serverURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusCreated, Body: `{"id":"post123"}`},+ )+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ ServerURL: serverURL,+ BotToken: "bot-token",+ TargetChannelID: strings.Repeat("c", channelIDLength),+ OverrideUsername: "Databasus",+ OverrideIconURL: "https://databasus.com/icon.png",+ }++ require.NoError(t, send(t, notifier, backupFailedNotification()))++ props := decodeBody(t, recorder.GetLastRequest().Body)["props"].(map[string]any)+ assert.Equal(t, "Databasus", props["override_username"])+ assert.Equal(t, "https://databasus.com/icon.png", props["override_icon_url"])+}++func Test_Send_WhenServerReturnsNon2xx_ReturnsError(t *testing.T) {+ webhookURL, _ := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusInternalServerError, Body: "boom"},+ )+ notifier := &MattermostNotifier{DeliveryMode: DeliveryModeWebhook, WebhookURL: webhookURL}++ err := send(t, notifier, backupFailedNotification())++ require.Error(t, err)+ assert.Contains(t, err.Error(), "boom")+}++func Test_Send_WhenServerReturnsMattermostErrorBody_ReturnsItsMessage(t *testing.T) {+ serverURL, _ := notifier_models.StartRecordingServer(t, notifier_models.StubResponse{+ StatusCode: http.StatusForbidden,+ Body: `{"id":"api.context.permissions.app_error","message":"You do not have the appropriate permissions."}`,+ })+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ ServerURL: serverURL,+ BotToken: "bot-token",+ TargetChannelID: strings.Repeat("c", channelIDLength),+ }++ err := send(t, notifier, backupFailedNotification())++ require.Error(t, err)+ assert.Contains(t, err.Error(), "You do not have the appropriate permissions.")+}++func Test_Send_WhenServerUnreachable_ReturnsErrorWithoutTheWebhookURL(t *testing.T) {+ webhookURL, _ := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )+ unreachableURL := webhookURL + "-gone/hooks/secret-key"+ notifier := &MattermostNotifier{DeliveryMode: DeliveryModeWebhook, WebhookURL: unreachableURL}++ err := send(t, notifier, backupFailedNotification())++ require.Error(t, err)+ assert.NotContains(t, err.Error(), "secret-key")+}++func Test_Send_WithBotModeWhenServerUnreachable_KeepsServerURLInError(t *testing.T) {+ serverURL, _ := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ ServerURL: serverURL + "-gone",+ BotToken: "bot-token",+ TargetChannelID: strings.Repeat("c", channelIDLength),+ }++ err := send(t, notifier, backupFailedNotification())++ require.Error(t, err)+ assert.Contains(t, err.Error(), serverURL+"-gone")+}++func Test_Send_WhenErrorBodyExceedsTheReadLimit_TruncatesIt(t *testing.T) {+ serverURL, _ := notifier_models.StartRecordingServer(t, notifier_models.StubResponse{+ StatusCode: http.StatusInternalServerError,+ Body: strings.Repeat("x", 10*maxErrorBodyBytes),+ })+ notifier := &MattermostNotifier{DeliveryMode: DeliveryModeWebhook, WebhookURL: serverURL}++ err := send(t, notifier, backupFailedNotification())++ require.Error(t, err)+ assert.NotContains(t, err.Error(), strings.Repeat("x", maxErrorBodyBytes+1))+}++func Test_Validate_WithUnknownDeliveryMode_ReturnsError(t *testing.T) {+ notifier := &MattermostNotifier{DeliveryMode: "CARRIER_PIGEON", WebhookURL: "https://mm.example.com/hooks/key"}++ require.ErrorContains(t, notifier.Validate(notifier_models.PassthroughEncryptor{}), "delivery mode")+}++func Test_Validate_WithWebhookModeAndValidURL_ReturnsNoError(t *testing.T) {+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeWebhook,+ WebhookURL: "https://mm.example.com/hooks/abc123",+ }++ require.NoError(t, notifier.Validate(notifier_models.PassthroughEncryptor{}))+}++func Test_Validate_WithWebhookModeAndMissingURL_ReturnsError(t *testing.T) {+ notifier := &MattermostNotifier{DeliveryMode: DeliveryModeWebhook}++ require.ErrorContains(t,+ notifier.Validate(notifier_models.PassthroughEncryptor{}),+ "incoming webhook URL is required",+ )+}++func Test_Validate_WithWebhookModeAndNonHTTPURL_ReturnsError(t *testing.T) {+ notifier := &MattermostNotifier{DeliveryMode: DeliveryModeWebhook, WebhookURL: "mm.example.com/hooks/abc"}++ require.ErrorContains(t,+ notifier.Validate(notifier_models.PassthroughEncryptor{}),+ "http or https",+ )+}++func Test_Validate_WithBotModeAndFullCredentials_ReturnsNoError(t *testing.T) {+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ ServerURL: "https://mm.example.com",+ BotToken: "bot-token",+ TargetChannelID: strings.Repeat("c", channelIDLength),+ }++ require.NoError(t, notifier.Validate(notifier_models.PassthroughEncryptor{}))+}++func Test_Validate_WithBotModeAndMissingToken_ReturnsError(t *testing.T) {+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ ServerURL: "https://mm.example.com",+ TargetChannelID: strings.Repeat("c", channelIDLength),+ }++ require.ErrorContains(t,+ notifier.Validate(notifier_models.PassthroughEncryptor{}),+ "bot token is required",+ )+}++func Test_Validate_WhenChannelIDIsAChannelName_ReturnsError(t *testing.T) {+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ ServerURL: "https://mm.example.com",+ BotToken: "bot-token",+ TargetChannelID: "town-square",+ }++ require.ErrorContains(t,+ notifier.Validate(notifier_models.PassthroughEncryptor{}),+ "not the channel name",+ )+}++func Test_Validate_WithNonHTTPOverrideIconURL_ReturnsError(t *testing.T) {+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeWebhook,+ WebhookURL: "https://mm.example.com/hooks/abc123",+ OverrideIconURL: "javascript:alert(1)",+ }++ require.ErrorContains(t,+ notifier.Validate(notifier_models.PassthroughEncryptor{}),+ "override icon URL",+ )+}++func Test_HideSensitiveData_BlanksBothCredentials(t *testing.T) {+ notifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ WebhookURL: "https://mm.example.com/hooks/abc123",+ BotToken: "bot-token",+ ServerURL: "https://mm.example.com",+ TargetChannelID: strings.Repeat("c", channelIDLength),+ }++ notifier.HideSensitiveData()++ assert.Empty(t, notifier.WebhookURL)+ assert.Empty(t, notifier.BotToken)+ assert.Equal(t, "https://mm.example.com", notifier.ServerURL)+}++func Test_Update_WithBlankCredentials_KeepsStoredOnes(t *testing.T) {+ storedNotifier := &MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ ServerURL: "https://mm.example.com",+ BotToken: "stored-token",+ WebhookURL: "https://mm.example.com/hooks/stored",+ TargetChannelID: strings.Repeat("c", channelIDLength),+ }++ storedNotifier.Update(&MattermostNotifier{+ DeliveryMode: DeliveryModeBot,+ ServerURL: "https://mm.internal.example.com",+ TargetChannelID: strings.Repeat("d", channelIDLength),+ OverrideUsername: "Databasus",+ })++ assert.Equal(t, "stored-token", storedNotifier.BotToken)+ assert.Equal(t, "https://mm.example.com/hooks/stored", storedNotifier.WebhookURL)+ assert.Equal(t, "https://mm.internal.example.com", storedNotifier.ServerURL)+ assert.Equal(t, strings.Repeat("d", channelIDLength), storedNotifier.TargetChannelID)+ assert.Equal(t, "Databasus", storedNotifier.OverrideUsername)+}diff --git a/backend/internal/features/notifiers/models/telegram/model_test.go b/backend/internal/features/notifiers/models/telegram/model_test.goindex b136904d..c89671ac 100644--- a/backend/internal/features/notifiers/models/telegram/model_test.go+++ b/backend/internal/features/notifiers/models/telegram/model_test.go@@ -5,17 +5,9 @@ import ("github.com/stretchr/testify/assert""github.com/stretchr/testify/require"-)--type passthroughEncryptor struct{}--func (p passthroughEncryptor) Encrypt(plaintext string) (string, error) {- return plaintext, nil-}-func (p passthroughEncryptor) Decrypt(ciphertext string) (string, error) {- return ciphertext, nil-}+ notifier_models "databasus-backend/internal/features/notifiers/models"+)func Test_Validate_WhenProxyEnabledWithoutURL_ReturnsError(t *testing.T) {notifier := &TelegramNotifier{@@ -24,7 +16,7 @@ func Test_Validate_WhenProxyEnabledWithoutURL_ReturnsError(t *testing.T) {IsProxyEnabled: true,}- err := notifier.Validate(passthroughEncryptor{})+ err := notifier.Validate(notifier_models.PassthroughEncryptor{})require.Error(t, err)assert.Contains(t, err.Error(), "proxy URL is required")@@ -38,7 +30,7 @@ func Test_Validate_WhenProxyURLSchemeUnsupported_ReturnsError(t *testing.T) {ProxyURL: "ftp://proxy.example.com:3128",}- err := notifier.Validate(passthroughEncryptor{})+ err := notifier.Validate(notifier_models.PassthroughEncryptor{})require.Error(t, err)assert.Contains(t, err.Error(), "http/https/socks5/socks5h")@@ -52,7 +44,7 @@ func Test_Validate_WhenProxyURLIsSocks5_ReturnsNoError(t *testing.T) {ProxyURL: "socks5://user:[email protected]:1080",}- err := notifier.Validate(passthroughEncryptor{})+ err := notifier.Validate(notifier_models.PassthroughEncryptor{})require.NoError(t, err)}diff --git a/backend/internal/features/notifiers/models/telegram/proxies_test.go b/backend/internal/features/notifiers/models/telegram/proxies_test.goindex 4ece9b85..434197b6 100644--- a/backend/internal/features/notifiers/models/telegram/proxies_test.go+++ b/backend/internal/features/notifiers/models/telegram/proxies_test.go@@ -6,6 +6,8 @@ import ("github.com/stretchr/testify/assert""github.com/stretchr/testify/require"++ notifier_models "databasus-backend/internal/features/notifiers/models")func Test_BuildHTTPClient_WhenProxyEnabled_UsesConfiguredProxy(t *testing.T) {@@ -20,7 +22,7 @@ func Test_BuildHTTPClient_WhenProxyEnabled_UsesConfiguredProxy(t *testing.T) {ProxyURL: proxyURL,}- client, err := notifier.buildHTTPClient(passthroughEncryptor{})+ client, err := notifier.buildHTTPClient(notifier_models.PassthroughEncryptor{})require.NoError(t, err)transport, ok := client.Transport.(*http.Transport)@@ -40,7 +42,7 @@ func Test_BuildHTTPClient_WhenProxyEnabled_UsesConfiguredProxy(t *testing.T) {func Test_BuildHTTPClient_WhenProxyDisabled_UsesDefaultTransport(t *testing.T) {notifier := &TelegramNotifier{}- client, err := notifier.buildHTTPClient(passthroughEncryptor{})+ client, err := notifier.buildHTTPClient(notifier_models.PassthroughEncryptor{})require.NoError(t, err)assert.Nil(t, client.Transport)diff --git a/backend/internal/features/notifiers/models/testing.go b/backend/internal/features/notifiers/models/testing.gonew file mode 100644index 00000000..22cc2b38--- /dev/null+++ b/backend/internal/features/notifiers/models/testing.go@@ -0,0 +1,87 @@+package notifier_models++import (+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "sync"+ "testing"+)++// PassthroughEncryptor lets provider tests assert on plaintext credentials without wiring the real+// key material of encryption.FieldEncryptor.+type PassthroughEncryptor struct{}++func (p PassthroughEncryptor) Encrypt(plaintext string) (string, error) {+ return plaintext, nil+}++func (p PassthroughEncryptor) Decrypt(ciphertext string) (string, error) {+ return ciphertext, nil+}++type StubResponse struct {+ StatusCode int+ Body string+}++type CapturedRequest struct {+ Method string+ Path string+ Query url.Values+ Headers http.Header+ Body string+}++type RequestRecorder struct {+ mu sync.Mutex+ requests []CapturedRequest+}++func (r *RequestRecorder) GetRequestCount() int {+ r.mu.Lock()+ defer r.mu.Unlock()++ return len(r.requests)+}++func (r *RequestRecorder) GetLastRequest() CapturedRequest {+ r.mu.Lock()+ defer r.mu.Unlock()++ return r.requests[len(r.requests)-1]+}++func StartRecordingServer(t *testing.T, response StubResponse) (string, *RequestRecorder) {+ t.Helper()++ recorder := &RequestRecorder{}++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ body, _ := io.ReadAll(request.Body)+ recorder.add(CapturedRequest{+ Method: request.Method,+ Path: request.URL.Path,+ Query: request.URL.Query(),+ Headers: request.Header.Clone(),+ Body: string(body),+ })++ w.WriteHeader(response.StatusCode)++ if response.Body != "" {+ _, _ = w.Write([]byte(response.Body))+ }+ }))+ t.Cleanup(server.Close)++ return server.URL, recorder+}++func (r *RequestRecorder) add(request CapturedRequest) {+ r.mu.Lock()+ defer r.mu.Unlock()++ r.requests = append(r.requests, request)+}diff --git a/backend/internal/features/notifiers/models/webhook/model_test.go b/backend/internal/features/notifiers/models/webhook/model_test.goindex 1e98530b..d11de255 100644--- a/backend/internal/features/notifiers/models/webhook/model_test.go+++ b/backend/internal/features/notifiers/models/webhook/model_test.go@@ -6,8 +6,6 @@ import ("log/slog""net/http""net/http/httptest"- "net/url"- "sync""testing""github.com/stretchr/testify/assert"@@ -16,73 +14,11 @@ import (notifier_models "databasus-backend/internal/features/notifiers/models")-type passthroughEncryptor struct{}--func (p passthroughEncryptor) Encrypt(plaintext string) (string, error) {- return plaintext, nil-}--func (p passthroughEncryptor) Decrypt(ciphertext string) (string, error) {- return ciphertext, nil-}--type capturedRequest struct {- method string- query url.Values- headers http.Header- body string-}--type requestRecorder struct {- mu sync.Mutex- requests []capturedRequest-}--func (r *requestRecorder) add(request capturedRequest) {- r.mu.Lock()- defer r.mu.Unlock()-- r.requests = append(r.requests, request)-}--func (r *requestRecorder) GetRequestCount() int {- r.mu.Lock()- defer r.mu.Unlock()-- return len(r.requests)-}--func (r *requestRecorder) GetLastRequest() capturedRequest {- r.mu.Lock()- defer r.mu.Unlock()-- return r.requests[len(r.requests)-1]-}--func startRecordingWebhook(t *testing.T, statusCode int) (string, *requestRecorder) {- recorder := &requestRecorder{}-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {- body, _ := io.ReadAll(req.Body)- recorder.add(capturedRequest{- method: req.Method,- query: req.URL.Query(),- headers: req.Header.Clone(),- body: string(body),- })-- w.WriteHeader(statusCode)- }))- t.Cleanup(server.Close)-- return server.URL, recorder-}-func send(t *testing.T, notifier *WebhookNotifier, notificationType notifier_models.NotificationType) error {t.Helper()return notifier.Send(- passthroughEncryptor{},+ notifier_models.PassthroughEncryptor{},slog.New(slog.NewTextHandler(io.Discard, nil)),notifier_models.Notification{Type: notificationType,@@ -97,7 +33,10 @@ func acceptAll() []notifier_models.NotificationType {}func Test_Send_WithPOSTAndNoBodyTemplate_SendsDefaultJSONBody(t *testing.T) {- webhookURL, recorder := startRecordingWebhook(t, http.StatusOK)+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )notifier := &WebhookNotifier{WebhookURL: webhookURL,WebhookMethod: WebhookMethodPOST,@@ -108,17 +47,20 @@ func Test_Send_WithPOSTAndNoBodyTemplate_SendsDefaultJSONBody(t *testing.T) {require.Equal(t, 1, recorder.GetRequestCount())request := recorder.GetLastRequest()- assert.Equal(t, http.MethodPost, request.method)- assert.Equal(t, "application/json", request.headers.Get("Content-Type"))+ assert.Equal(t, http.MethodPost, request.Method)+ assert.Equal(t, "application/json", request.Headers.Get("Content-Type"))var payload map[string]string- require.NoError(t, json.Unmarshal([]byte(request.body), &payload))+ require.NoError(t, json.Unmarshal([]byte(request.Body), &payload))assert.Equal(t, "Backup completed", payload["heading"])assert.Equal(t, "All good", payload["message"])}func Test_Send_WithPOSTAndBodyTemplate_SubstitutesAndEscapesPlaceholders(t *testing.T) {- webhookURL, recorder := startRecordingWebhook(t, http.StatusOK)+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )template := `{"title":"{{heading}}","text":"{{message}}"}`notifier := &WebhookNotifier{WebhookURL: webhookURL,@@ -128,7 +70,7 @@ func Test_Send_WithPOSTAndBodyTemplate_SubstitutesAndEscapesPlaceholders(t *test}err := notifier.Send(- passthroughEncryptor{},+ notifier_models.PassthroughEncryptor{},slog.New(slog.NewTextHandler(io.Discard, nil)),notifier_models.Notification{Type: notifier_models.NotificationTypeBackupSuccess,@@ -139,13 +81,16 @@ func Test_Send_WithPOSTAndBodyTemplate_SubstitutesAndEscapesPlaceholders(t *testrequire.NoError(t, err)var payload map[string]string- require.NoError(t, json.Unmarshal([]byte(recorder.GetLastRequest().body), &payload))+ require.NoError(t, json.Unmarshal([]byte(recorder.GetLastRequest().Body), &payload))assert.Equal(t, `He said "hi"`, payload["title"])assert.Equal(t, "line1\nline2", payload["text"])}func Test_Send_WithCustomContentTypeHeader_DoesNotOverrideIt(t *testing.T) {- webhookURL, recorder := startRecordingWebhook(t, http.StatusOK)+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )notifier := &WebhookNotifier{WebhookURL: webhookURL,WebhookMethod: WebhookMethodPOST,@@ -155,11 +100,14 @@ func Test_Send_WithCustomContentTypeHeader_DoesNotOverrideIt(t *testing.T) {require.NoError(t, send(t, notifier, notifier_models.NotificationTypeBackupSuccess))- assert.Equal(t, "application/xml", recorder.GetLastRequest().headers.Get("Content-Type"))+ assert.Equal(t, "application/xml", recorder.GetLastRequest().Headers.Get("Content-Type"))}func Test_Send_WithGET_SendsHeadingAndMessageAsQueryParams(t *testing.T) {- webhookURL, recorder := startRecordingWebhook(t, http.StatusOK)+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )notifier := &WebhookNotifier{WebhookURL: webhookURL,WebhookMethod: WebhookMethodGET,@@ -169,14 +117,17 @@ func Test_Send_WithGET_SendsHeadingAndMessageAsQueryParams(t *testing.T) {require.NoError(t, send(t, notifier, notifier_models.NotificationTypeBackupSuccess))request := recorder.GetLastRequest()- assert.Equal(t, http.MethodGet, request.method)- assert.Equal(t, "Backup completed", request.query.Get("heading"))- assert.Equal(t, "All good", request.query.Get("message"))- assert.Empty(t, request.body)+ assert.Equal(t, http.MethodGet, request.Method)+ assert.Equal(t, "Backup completed", request.Query.Get("heading"))+ assert.Equal(t, "All good", request.Query.Get("message"))+ assert.Empty(t, request.Body)}func Test_Send_WithCustomHeaders_AppliesThemToRequest(t *testing.T) {- webhookURL, recorder := startRecordingWebhook(t, http.StatusOK)+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )notifier := &WebhookNotifier{WebhookURL: webhookURL,WebhookMethod: WebhookMethodPOST,@@ -186,11 +137,14 @@ func Test_Send_WithCustomHeaders_AppliesThemToRequest(t *testing.T) {require.NoError(t, send(t, notifier, notifier_models.NotificationTypeBackupSuccess))- assert.Equal(t, "secret-value", recorder.GetLastRequest().headers.Get("X-Api-Key"))+ assert.Equal(t, "secret-value", recorder.GetLastRequest().Headers.Get("X-Api-Key"))}func Test_Send_WhenServerReturnsNon2xx_ReturnsError(t *testing.T) {- webhookURL, _ := startRecordingWebhook(t, http.StatusInternalServerError)+ webhookURL, _ := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusInternalServerError},+ )notifier := &WebhookNotifier{WebhookURL: webhookURL,WebhookMethod: WebhookMethodPOST,@@ -215,7 +169,10 @@ func Test_Send_WhenURLUnreachable_ReturnsError(t *testing.T) {}func Test_Send_WhenAcceptTypesEmpty_SendsEveryType(t *testing.T) {- webhookURL, recorder := startRecordingWebhook(t, http.StatusOK)+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )notifier := &WebhookNotifier{WebhookURL: webhookURL,WebhookMethod: WebhookMethodPOST,@@ -228,7 +185,10 @@ func Test_Send_WhenAcceptTypesEmpty_SendsEveryType(t *testing.T) {}func Test_Send_WhenAcceptContainsAll_SendsEveryType(t *testing.T) {- webhookURL, recorder := startRecordingWebhook(t, http.StatusOK)+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )notifier := &WebhookNotifier{WebhookURL: webhookURL,WebhookMethod: WebhookMethodPOST,@@ -242,7 +202,10 @@ func Test_Send_WhenAcceptContainsAll_SendsEveryType(t *testing.T) {}func Test_Send_WhenNarrowedToBackupSuccess_SkipsOtherTypes(t *testing.T) {- webhookURL, recorder := startRecordingWebhook(t, http.StatusOK)+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )notifier := &WebhookNotifier{WebhookURL: webhookURL,WebhookMethod: WebhookMethodPOST,@@ -258,7 +221,10 @@ func Test_Send_WhenNarrowedToBackupSuccess_SkipsOtherTypes(t *testing.T) {}func Test_Send_WhenNarrowed_StillSendsWildcardTestNotification(t *testing.T) {- webhookURL, recorder := startRecordingWebhook(t, http.StatusOK)+ webhookURL, recorder := notifier_models.StartRecordingServer(+ t,+ notifier_models.StubResponse{StatusCode: http.StatusOK},+ )notifier := &WebhookNotifier{WebhookURL: webhookURL,WebhookMethod: WebhookMethodPOST,diff --git a/backend/internal/features/notifiers/repository.go b/backend/internal/features/notifiers/repository.goindex 4a4df741..26c6b9cf 100644--- a/backend/internal/features/notifiers/repository.go+++ b/backend/internal/features/notifiers/repository.go@@ -38,6 +38,10 @@ func (r *NotifierRepository) Save(notifier *Notifier) (*Notifier, error) {if notifier.TeamsNotifier != nil {notifier.TeamsNotifier.NotifierID = notifier.ID}+ case NotifierTypeMattermost:+ if notifier.MattermostNotifier != nil {+ notifier.MattermostNotifier.NotifierID = notifier.ID+ }}if notifier.ID == uuid.Nil {@@ -49,6 +53,7 @@ func (r *NotifierRepository) Save(notifier *Notifier) (*Notifier, error) {"SlackNotifier","DiscordNotifier","TeamsNotifier",+ "MattermostNotifier",).Create(notifier).Error; err != nil {return err@@ -62,6 +67,7 @@ func (r *NotifierRepository) Save(notifier *Notifier) (*Notifier, error) {"SlackNotifier","DiscordNotifier","TeamsNotifier",+ "MattermostNotifier",).Save(notifier).Error; err != nil {return err@@ -111,6 +117,13 @@ func (r *NotifierRepository) Save(notifier *Notifier) (*Notifier, error) {return err}}+ case NotifierTypeMattermost:+ if notifier.MattermostNotifier != nil {+ notifier.MattermostNotifier.NotifierID = notifier.ID+ if err := tx.Save(notifier.MattermostNotifier).Error; err != nil {+ return err+ }+ }}return nil@@ -133,6 +146,7 @@ func (r *NotifierRepository) FindByID(id uuid.UUID) (*Notifier, error) {Preload("SlackNotifier").Preload("DiscordNotifier").Preload("TeamsNotifier").+ Preload("MattermostNotifier").Where("id = ?", id).First(¬ifier).Error; err != nil {return nil, err@@ -162,6 +176,7 @@ func (r *NotifierRepository) FindByWorkspaceID(workspaceID uuid.UUID) ([]*NotifiPreload("SlackNotifier").Preload("DiscordNotifier").Preload("TeamsNotifier").+ Preload("MattermostNotifier").Where("workspace_id = ?", workspaceID).Order("name ASC").Find(¬ifiers).Error; err != nil {@@ -210,6 +225,12 @@ func (r *NotifierRepository) Delete(notifier *Notifier) error {return err}}+ case NotifierTypeMattermost:+ if notifier.MattermostNotifier != nil {+ if err := tx.Delete(notifier.MattermostNotifier).Error; err != nil {+ return err+ }+ }}return tx.Delete(notifier).Errordiff --git a/backend/migrations/20260811190434_add_mattermost_notifier.sql b/backend/migrations/20260811190434_add_mattermost_notifier.sqlnew file mode 100644index 00000000..2a342656--- /dev/null+++ b/backend/migrations/20260811190434_add_mattermost_notifier.sql@@ -0,0 +1,28 @@+-- +goose Up+-- +goose StatementBegin++CREATE TABLE mattermost_notifiers (+ notifier_id UUID PRIMARY KEY,+ delivery_mode TEXT NOT NULL,+ webhook_url TEXT NOT NULL DEFAULT '',+ server_url TEXT NOT NULL DEFAULT '',+ bot_token TEXT NOT NULL DEFAULT '',+ target_channel_name TEXT NOT NULL DEFAULT '',+ target_channel_id TEXT NOT NULL DEFAULT '',+ override_username TEXT NOT NULL DEFAULT '',+ override_icon_url TEXT NOT NULL DEFAULT '',+ is_insecure_skip_verify BOOLEAN NOT NULL DEFAULT FALSE+);++ALTER TABLE mattermost_notifiers+ ADD CONSTRAINT fk_mattermost_notifiers_notifier+ FOREIGN KEY (notifier_id)+ REFERENCES notifiers (id)+ ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED;++-- +goose StatementEnd++-- +goose Down+-- +goose StatementBegin+DROP TABLE IF EXISTS mattermost_notifiers;+-- +goose StatementEnddiff --git a/frontend/public/icons/notifiers/mattermost.svg b/frontend/public/icons/notifiers/mattermost.svgnew file mode 100644index 00000000..fe79a4f4--- /dev/null+++ b/frontend/public/icons/notifiers/mattermost.svg@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="UTF-8"?>+<svg width="800px" height="800px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Mattermost</title><path fill="#0058CC" d="M12.081 0C7.048-.034 2.339 3.125.637 8.153c-2.125 6.276 1.24 13.086 7.516 15.21 6.276 2.125 13.086-1.24 15.21-7.516 1.727-5.1-.172-10.552-4.311-13.557l.126 2.547c2.065 2.282 2.88 5.512 1.852 8.549-1.534 4.532-6.594 6.915-11.3 5.321-4.708-1.593-7.28-6.559-5.745-11.092 1.031-3.046 3.655-5.121 6.694-5.67l1.642-1.94A4.87 4.87 0 0 0 12.08 0zm3.528 1.094a.284.284 0 0 0-.123.024l-.004.001a.33.33 0 0 0-.109.071c-.145.142-.657.828-.657.828L13.6 3.4l-1.3 1.585-2.232 2.776s-1.024 1.278-.798 2.851c.226 1.574 1.396 2.34 2.304 2.648.907.307 2.302.408 3.438-.704 1.135-1.112 1.098-2.75 1.098-2.75l-.087-3.56-.07-2.05-.047-1.775s.01-.856-.02-1.057a.33.33 0 0 0-.035-.107l-.006-.012-.007-.011a.277.277 0 0 0-.229-.14z"/></svg>diff --git a/frontend/src/entity/notifiers/index.ts b/frontend/src/entity/notifiers/index.tsindex 4143817f..cf1f1aca 100644--- a/frontend/src/entity/notifiers/index.ts+++ b/frontend/src/entity/notifiers/index.ts@@ -22,3 +22,7 @@ export { validateDiscordNotifier } from './models/discord/validateDiscordNotifieexport type { TeamsNotifier } from './models/teams/TeamsNotifier';export { validateTeamsNotifier } from './models/teams/validateTeamsNotifier';++export type { MattermostNotifier } from './models/mattermost/MattermostNotifier';+export { MattermostDeliveryMode } from './models/mattermost/MattermostDeliveryMode';+export { validateMattermostNotifier } from './models/mattermost/validateMattermostNotifier';diff --git a/frontend/src/entity/notifiers/models/Notifier.ts b/frontend/src/entity/notifiers/models/Notifier.tsindex e09a74fb..76d3b959 100644--- a/frontend/src/entity/notifiers/models/Notifier.ts+++ b/frontend/src/entity/notifiers/models/Notifier.ts@@ -1,6 +1,7 @@import type { NotifierType } from './NotifierType';import type { DiscordNotifier } from './discord/DiscordNotifier';import type { EmailNotifier } from './email/EmailNotifier';+import type { MattermostNotifier } from './mattermost/MattermostNotifier';import type { SlackNotifier } from './slack/SlackNotifier';import type { TeamsNotifier } from './teams/TeamsNotifier';import type { TelegramNotifier } from './telegram/TelegramNotifier';@@ -20,4 +21,5 @@ export interface Notifier {slackNotifier?: SlackNotifier;discordNotifier?: DiscordNotifier;teamsNotifier?: TeamsNotifier;+ mattermostNotifier?: MattermostNotifier;}diff --git a/frontend/src/entity/notifiers/models/NotifierType.ts b/frontend/src/entity/notifiers/models/NotifierType.tsindex 23368dda..f202259b 100644--- a/frontend/src/entity/notifiers/models/NotifierType.ts+++ b/frontend/src/entity/notifiers/models/NotifierType.ts@@ -5,4 +5,5 @@ export enum NotifierType {SLACK = 'SLACK',DISCORD = 'DISCORD',TEAMS = 'TEAMS',+ MATTERMOST = 'MATTERMOST',}diff --git a/frontend/src/entity/notifiers/models/getNotifierLogoFromType.ts b/frontend/src/entity/notifiers/models/getNotifierLogoFromType.tsindex 98e80e41..8038efdd 100644--- a/frontend/src/entity/notifiers/models/getNotifierLogoFromType.ts+++ b/frontend/src/entity/notifiers/models/getNotifierLogoFromType.ts@@ -14,6 +14,8 @@ export const getNotifierLogoFromType = (type: NotifierType) => {return '/icons/notifiers/discord.svg';case NotifierType.TEAMS:return '/icons/notifiers/teams.svg';+ case NotifierType.MATTERMOST:+ return '/icons/notifiers/mattermost.svg';default:return '';}diff --git a/frontend/src/entity/notifiers/models/getNotifierNameFromType.ts b/frontend/src/entity/notifiers/models/getNotifierNameFromType.tsindex 7c24cb75..6b1674db 100644--- a/frontend/src/entity/notifiers/models/getNotifierNameFromType.ts+++ b/frontend/src/entity/notifiers/models/getNotifierNameFromType.ts@@ -14,6 +14,8 @@ export const getNotifierNameFromType = (type: NotifierType) => {return 'Discord';case NotifierType.TEAMS:return 'Teams';+ case NotifierType.MATTERMOST:+ return 'Mattermost';default:return '';}diff --git a/frontend/src/entity/notifiers/models/mattermost/MattermostDeliveryMode.ts b/frontend/src/entity/notifiers/models/mattermost/MattermostDeliveryMode.tsnew file mode 100644index 00000000..f7aa8962--- /dev/null+++ b/frontend/src/entity/notifiers/models/mattermost/MattermostDeliveryMode.ts@@ -0,0 +1,4 @@+export enum MattermostDeliveryMode {+ WEBHOOK = 'WEBHOOK',+ BOT = 'BOT',+}diff --git a/frontend/src/entity/notifiers/models/mattermost/MattermostNotifier.ts b/frontend/src/entity/notifiers/models/mattermost/MattermostNotifier.tsnew file mode 100644index 00000000..9a28a6c6--- /dev/null+++ b/frontend/src/entity/notifiers/models/mattermost/MattermostNotifier.ts@@ -0,0 +1,18 @@+import type { MattermostDeliveryMode } from './MattermostDeliveryMode';++export interface MattermostNotifier {+ deliveryMode: MattermostDeliveryMode;++ webhookUrl: string;++ serverUrl: string;+ botToken: string;++ targetChannelName: string;+ targetChannelId: string;++ overrideUsername: string;+ overrideIconUrl: string;++ isInsecureSkipVerify: boolean;+}diff --git a/frontend/src/entity/notifiers/models/mattermost/validateMattermostNotifier.test.ts b/frontend/src/entity/notifiers/models/mattermost/validateMattermostNotifier.test.tsnew file mode 100644index 00000000..14d2fadb--- /dev/null+++ b/frontend/src/entity/notifiers/models/mattermost/validateMattermostNotifier.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from 'vitest';++import { MattermostDeliveryMode } from './MattermostDeliveryMode';+import type { MattermostNotifier } from './MattermostNotifier';+import { validateMattermostNotifier } from './validateMattermostNotifier';++const emptyNotifier: MattermostNotifier = {+ deliveryMode: MattermostDeliveryMode.WEBHOOK,+ webhookUrl: '',+ serverUrl: '',+ botToken: '',+ targetChannelName: '',+ targetChannelId: '',+ overrideUsername: '',+ overrideIconUrl: '',+ isInsecureSkipVerify: false,+};++const channelId = 'abcdefghijklmnopqrstuvwxyz';++describe('validateMattermostNotifier', () => {+ it('requires a webhook URL on create in webhook mode', () => {+ expect(validateMattermostNotifier(true, emptyNotifier)).toBe(false);+ expect(+ validateMattermostNotifier(true, {+ ...emptyNotifier,+ webhookUrl: 'https://mattermost.example.com/hooks/key',+ }),+ ).toBe(true);+ });++ it('allows a blank webhook URL on edit', () => {+ expect(validateMattermostNotifier(false, emptyNotifier)).toBe(true);+ });++ it('requires server URL, token and channel ID on create in bot mode', () => {+ const botNotifier: MattermostNotifier = {+ ...emptyNotifier,+ deliveryMode: MattermostDeliveryMode.BOT,+ serverUrl: 'https://mattermost.example.com',+ botToken: 'token',+ targetChannelId: channelId,+ };++ expect(validateMattermostNotifier(true, botNotifier)).toBe(true);+ expect(validateMattermostNotifier(true, { ...botNotifier, serverUrl: '' })).toBe(false);+ expect(validateMattermostNotifier(true, { ...botNotifier, botToken: '' })).toBe(false);+ expect(validateMattermostNotifier(false, { ...botNotifier, botToken: '' })).toBe(true);+ });++ it('rejects a channel name pasted into the channel ID field', () => {+ expect(+ validateMattermostNotifier(true, {+ ...emptyNotifier,+ deliveryMode: MattermostDeliveryMode.BOT,+ serverUrl: 'https://mattermost.example.com',+ botToken: 'token',+ targetChannelId: 'town-square',+ }),+ ).toBe(false);+ });+});diff --git a/frontend/src/entity/notifiers/models/mattermost/validateMattermostNotifier.ts b/frontend/src/entity/notifiers/models/mattermost/validateMattermostNotifier.tsnew file mode 100644index 00000000..4c906800--- /dev/null+++ b/frontend/src/entity/notifiers/models/mattermost/validateMattermostNotifier.ts@@ -0,0 +1,27 @@+import { MattermostDeliveryMode } from './MattermostDeliveryMode';+import type { MattermostNotifier } from './MattermostNotifier';++const MATTERMOST_CHANNEL_ID_LENGTH = 26;++export const validateMattermostNotifier = (+ isCreate: boolean,+ notifier: MattermostNotifier,+): boolean => {+ if (notifier.deliveryMode === MattermostDeliveryMode.WEBHOOK) {+ return !isCreate || !!notifier.webhookUrl;+ }++ if (notifier.deliveryMode === MattermostDeliveryMode.BOT) {+ if (!notifier.serverUrl) {+ return false;+ }++ if (isCreate && !notifier.botToken) {+ return false;+ }++ return notifier.targetChannelId.length === MATTERMOST_CHANNEL_ID_LENGTH;+ }++ return false;+};diff --git a/frontend/src/features/notifiers/ui/edit/EditNotifierComponent.tsx b/frontend/src/features/notifiers/ui/edit/EditNotifierComponent.tsxindex 11ea56fe..a1ed8d05 100644--- a/frontend/src/features/notifiers/ui/edit/EditNotifierComponent.tsx+++ b/frontend/src/features/notifiers/ui/edit/EditNotifierComponent.tsx@@ -2,12 +2,14 @@ import { Button, Input, Select } from 'antd';import { useEffect, useState } from 'react';import {+ MattermostDeliveryMode,type Notifier,NotifierType,WebhookMethod,notifierApi,validateDiscordNotifier,validateEmailNotifier,+ validateMattermostNotifier,validateSlackNotifier,validateTeamsNotifier,validateTelegramNotifier,@@ -17,6 +19,7 @@ import { getNotifierLogoFromType } from '../../../../entity/notifiers/models/getimport { ToastHelper } from '../../../../shared/toast';import { EditDiscordNotifierComponent } from './notifiers/EditDiscordNotifierComponent';import { EditEmailNotifierComponent } from './notifiers/EditEmailNotifierComponent';+import { EditMattermostNotifierComponent } from './notifiers/EditMattermostNotifierComponent';import { EditSlackNotifierComponent } from './notifiers/EditSlackNotifierComponent';import { EditTeamsNotifierComponent } from './notifiers/EditTeamsNotifierComponent';import { EditTelegramNotifierComponent } from './notifiers/EditTelegramNotifierComponent';@@ -96,6 +99,10 @@ export function EditNotifierComponent({notifier.emailNotifier = undefined;notifier.telegramNotifier = undefined;notifier.teamsNotifier = undefined;+ notifier.webhookNotifier = undefined;+ notifier.slackNotifier = undefined;+ notifier.discordNotifier = undefined;+ notifier.mattermostNotifier = undefined;if (type === NotifierType.TELEGRAM) {notifier.telegramNotifier = {@@ -141,6 +148,20 @@ export function EditNotifierComponent({notifier.teamsNotifier = { powerAutomateUrl: '' };}+ if (type === NotifierType.MATTERMOST) {+ notifier.mattermostNotifier = {+ deliveryMode: MattermostDeliveryMode.WEBHOOK,+ webhookUrl: '',+ serverUrl: '',+ botToken: '',+ targetChannelName: '',+ targetChannelId: '',+ overrideUsername: '',+ overrideIconUrl: '',+ isInsecureSkipVerify: false,+ };+ }+setNotifier(JSON.parse(JSON.stringify({@@ -202,6 +223,10 @@ export function EditNotifierComponent({return validateTeamsNotifier(!notifier.id, notifier.teamsNotifier);}+ if (notifier.notifierType === NotifierType.MATTERMOST && notifier.mattermostNotifier) {+ return validateMattermostNotifier(!notifier.id, notifier.mattermostNotifier);+ }+return false;};@@ -239,6 +264,7 @@ export function EditNotifierComponent({{ label: 'Slack', value: NotifierType.SLACK },{ label: 'Discord', value: NotifierType.DISCORD },{ label: 'Teams', value: NotifierType.TEAMS },+ { label: 'Mattermost', value: NotifierType.MATTERMOST },]}onChange={(value) => {setNotifierType(value);@@ -319,6 +345,17 @@ export function EditNotifierComponent({}}/>)}++ {notifier?.notifierType === NotifierType.MATTERMOST && (+ <EditMattermostNotifierComponent+ notifier={notifier}+ setNotifier={setNotifier}+ setUnsaved={() => {+ setIsUnsaved(true);+ setIsTestNotificationSuccess(false);+ }}+ />+ )}</div><div className="mt-3 flex">diff --git a/frontend/src/features/notifiers/ui/edit/notifiers/EditMattermostNotifierComponent.tsx b/frontend/src/features/notifiers/ui/edit/notifiers/EditMattermostNotifierComponent.tsxnew file mode 100644index 00000000..c14f4c00--- /dev/null+++ b/frontend/src/features/notifiers/ui/edit/notifiers/EditMattermostNotifierComponent.tsx@@ -0,0 +1,258 @@+import { InfoCircleOutlined } from '@ant-design/icons';+import { Checkbox, Input, Select, Tooltip } from 'antd';+import { useState } from 'react';++import {+ MattermostDeliveryMode,+ type MattermostNotifier,+ type Notifier,+} from '../../../../../entity/notifiers';++interface Props {+ notifier: Notifier;+ setNotifier: (notifier: Notifier) => void;+ setUnsaved: () => void;+}++export function EditMattermostNotifierComponent({ notifier, setNotifier, setUnsaved }: Props) {+ const mattermostNotifier = notifier.mattermostNotifier;++ const [isShowOptional, setIsShowOptional] = useState(+ () =>+ !!(+ mattermostNotifier?.targetChannelName ||+ mattermostNotifier?.overrideUsername ||+ mattermostNotifier?.overrideIconUrl ||+ mattermostNotifier?.isInsecureSkipVerify+ ),+ );++ if (!mattermostNotifier) return <div />;++ const updateMattermostNotifier = (changes: Partial<MattermostNotifier>) => {+ setNotifier({+ ...notifier,+ mattermostNotifier: { ...mattermostNotifier, ...changes },+ });+ setUnsaved();+ };++ const isWebhookMode = mattermostNotifier.deliveryMode === MattermostDeliveryMode.WEBHOOK;++ return (+ <>+ <div className="mb-1 max-w-[250px] sm:ml-[150px]" style={{ lineHeight: 1 }}>+ <a+ className="text-xs !text-blue-600"+ href="https://databasus.com/notifiers/mattermost"+ target="_blank"+ rel="noreferrer"+ >+ How to connect Mattermost?+ </a>+ </div>++ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0">Connect via</div>+ <Select+ value={mattermostNotifier.deliveryMode}+ options={[+ { label: 'Incoming webhook', value: MattermostDeliveryMode.WEBHOOK },+ { label: 'Bot account', value: MattermostDeliveryMode.BOT },+ ]}+ onChange={(deliveryMode) => updateMattermostNotifier({ deliveryMode })}+ size="small"+ className="w-full max-w-[250px]"+ />+ </div>++ {isWebhookMode ? (+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0">Incoming webhook URL</div>+ <Input+ value={mattermostNotifier.webhookUrl}+ onChange={(e) => updateMattermostNotifier({ webhookUrl: e.target.value.trim() })}+ size="small"+ className="w-full max-w-[250px]"+ placeholder="https://mattermost.example.com/hooks/xxxxxxxx"+ />+ </div>+ ) : (+ <>+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0">Server URL</div>+ <Input+ value={mattermostNotifier.serverUrl}+ onChange={(e) => updateMattermostNotifier({ serverUrl: e.target.value.trim() })}+ size="small"+ className="w-full max-w-[250px]"+ placeholder="https://mattermost.example.com"+ />+ </div>++ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0">Bot token</div>+ <Input+ value={mattermostNotifier.botToken}+ onChange={(e) => updateMattermostNotifier({ botToken: e.target.value.trim() })}+ size="small"+ className="w-full max-w-[250px]"+ placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxx"+ />+ </div>++ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0">Channel ID</div>+ <div className="flex items-center">+ <Input+ value={mattermostNotifier.targetChannelId}+ onChange={(e) =>+ updateMattermostNotifier({ targetChannelId: e.target.value.trim() })+ }+ size="small"+ className="w-full max-w-[250px]"+ placeholder="8f4ycxjmztbwmcy1o3xasjrxha"+ />++ <Tooltip+ className="cursor-pointer"+ title="26-character channel ID, not the channel name. Open the channel, click its name and choose View Info."+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ </div>+ </>+ )}++ <div className="mb-1 max-w-[250px] sm:ml-[150px]">+ <button+ type="button"+ onClick={() => setIsShowOptional(!isShowOptional)}+ className="text-xs text-blue-600 hover:underline"+ >+ {isShowOptional ? 'Hide optional settings' : 'Show optional settings'}+ </button>+ </div>++ {isShowOptional && (+ <>+ {isWebhookMode && (+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0">Channel override</div>+ <div className="flex items-center">+ <Input+ value={mattermostNotifier.targetChannelName}+ onChange={(e) =>+ updateMattermostNotifier({ targetChannelName: e.target.value.trim() })+ }+ size="small"+ className="w-full max-w-[250px]"+ placeholder="town-square"+ />++ <Tooltip+ className="cursor-pointer"+ title="Post to this channel instead of the one the webhook was created for. Mattermost ignores it when the webhook is locked to a channel."+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ </div>+ )}++ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0">Post as username</div>+ <div className="flex items-center">+ <Input+ value={mattermostNotifier.overrideUsername}+ onChange={(e) =>+ updateMattermostNotifier({ overrideUsername: e.target.value.trim() })+ }+ size="small"+ className="w-full max-w-[250px]"+ placeholder="Databasus"+ />++ <Tooltip+ className="cursor-pointer"+ title="Requires Enable integrations to override usernames in the Mattermost system console, otherwise it is ignored."+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ </div>++ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0">Post as icon URL</div>+ <div className="flex items-center">+ <Input+ value={mattermostNotifier.overrideIconUrl}+ onChange={(e) =>+ updateMattermostNotifier({ overrideIconUrl: e.target.value.trim() })+ }+ size="small"+ className="w-full max-w-[250px]"+ placeholder="https://databasus.com/icon.png"+ />++ <Tooltip+ className="cursor-pointer"+ title="Requires Enable integrations to override profile picture icons in the Mattermost system console, otherwise it is ignored."+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ </div>++ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0">Skip TLS verify</div>+ <div className="flex items-center">+ <Checkbox+ checked={mattermostNotifier.isInsecureSkipVerify}+ onChange={(e) =>+ updateMattermostNotifier({ isInsecureSkipVerify: e.target.checked })+ }+ >+ Skip TLS+ </Checkbox>++ <Tooltip+ className="cursor-pointer"+ title="Skip TLS certificate verification. Enable this if your Mattermost server uses a self-signed certificate. Warning: this reduces security."+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ </div>+ </>+ )}++ <div className="mt-1 max-w-[250px] text-xs text-gray-500 sm:ml-[150px] dark:text-gray-400">+ {isWebhookMode ? (+ <>+ <strong>How to get an incoming webhook URL:</strong>+ <br />+ <br />+ 1. Main menu - Integrations - Incoming Webhooks+ <br />+ 2. Add Incoming Webhook, pick the channel+ <br />+ 3. Copy the generated URL+ </>+ ) : (+ <>+ <strong>How to get a bot token:</strong>+ <br />+ <br />+ 1. Integrations - Bot Accounts - Add Bot Account+ <br />+ 2. Copy the token shown once after creation+ <br />+ 3. Add the bot to the team and to the channel+ </>+ )}+ </div>+ </>+ );+}diff --git a/frontend/src/features/notifiers/ui/show/ShowNotifierComponent.tsx b/frontend/src/features/notifiers/ui/show/ShowNotifierComponent.tsxindex e730ee0e..9d0334f3 100644--- a/frontend/src/features/notifiers/ui/show/ShowNotifierComponent.tsx+++ b/frontend/src/features/notifiers/ui/show/ShowNotifierComponent.tsx@@ -3,6 +3,7 @@ import { getNotifierLogoFromType } from '../../../../entity/notifiers/models/getimport { getNotifierNameFromType } from '../../../../entity/notifiers/models/getNotifierNameFromType';import { ShowDiscordNotifierComponent } from './notifier/ShowDiscordNotifierComponent';import { ShowEmailNotifierComponent } from './notifier/ShowEmailNotifierComponent';+import { ShowMattermostNotifierComponent } from './notifier/ShowMattermostNotifierComponent';import { ShowSlackNotifierComponent } from './notifier/ShowSlackNotifierComponent';import { ShowTeamsNotifierComponent } from './notifier/ShowTeamsNotifierComponent';import { ShowTelegramNotifierComponent } from './notifier/ShowTelegramNotifierComponent';@@ -46,6 +47,10 @@ export function ShowNotifierComponent({ notifier }: Props) {{notifier?.notifierType === NotifierType.TEAMS && (<ShowTeamsNotifierComponent notifier={notifier} />)}++ {notifier?.notifierType === NotifierType.MATTERMOST && (+ <ShowMattermostNotifierComponent notifier={notifier} />+ )}</div></div>);diff --git a/frontend/src/features/notifiers/ui/show/notifier/ShowDiscordNotifierComponent.tsx b/frontend/src/features/notifiers/ui/show/notifier/ShowDiscordNotifierComponent.tsxindex 7f29dd4c..0b393b33 100644--- a/frontend/src/features/notifiers/ui/show/notifier/ShowDiscordNotifierComponent.tsx+++ b/frontend/src/features/notifiers/ui/show/notifier/ShowDiscordNotifierComponent.tsx@@ -10,7 +10,7 @@ export function ShowDiscordNotifierComponent({ notifier }: Props) {<div className="flex"><div className="max-w-[110px] min-w-[110px] pr-3">Channel webhook URL</div>- <div>{notifier.webhookNotifier?.webhookUrl.slice(0, 10)}*******</div>+ <div>{notifier.discordNotifier?.channelWebhookUrl?.slice(0, 10)}*******</div></div></>);diff --git a/frontend/src/features/notifiers/ui/show/notifier/ShowMattermostNotifierComponent.tsx b/frontend/src/features/notifiers/ui/show/notifier/ShowMattermostNotifierComponent.tsxnew file mode 100644index 00000000..8a553bbe--- /dev/null+++ b/frontend/src/features/notifiers/ui/show/notifier/ShowMattermostNotifierComponent.tsx@@ -0,0 +1,54 @@+import { MattermostDeliveryMode, type Notifier } from '../../../../../entity/notifiers';++interface Props {+ notifier: Notifier;+}++export function ShowMattermostNotifierComponent({ notifier }: Props) {+ const mattermostNotifier = notifier.mattermostNotifier;++ if (!mattermostNotifier) return <div />;++ const isWebhookMode = mattermostNotifier.deliveryMode === MattermostDeliveryMode.WEBHOOK;++ return (+ <>+ <div className="flex">+ <div className="max-w-[110px] min-w-[110px] pr-3">Connect via</div>+ <div>{isWebhookMode ? 'Incoming webhook' : 'Bot account'}</div>+ </div>++ {isWebhookMode ? (+ <>+ <div className="flex">+ <div className="max-w-[110px] min-w-[110px] pr-3">Webhook URL</div>+ <div className="break-all">+ {mattermostNotifier.webhookUrl+ ? `${mattermostNotifier.webhookUrl}*******`+ : '*******'}+ </div>+ </div>++ {mattermostNotifier.targetChannelName && (+ <div className="flex">+ <div className="max-w-[110px] min-w-[110px] pr-3">Channel</div>+ <div className="break-all">{mattermostNotifier.targetChannelName}</div>+ </div>+ )}+ </>+ ) : (+ <>+ <div className="flex">+ <div className="max-w-[110px] min-w-[110px] pr-3">Server URL</div>+ <div className="break-all">{mattermostNotifier.serverUrl}</div>+ </div>++ <div className="flex">+ <div className="max-w-[110px] min-w-[110px] pr-3">Channel ID</div>+ <div className="break-all">{mattermostNotifier.targetChannelId}</div>+ </div>+ </>+ )}+ </>+ );+}