Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Make notification destination updates durable

pulse-triage[bot]5f6bfefa5603
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index df94344337..ff1fbca173 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -6706,3 +6706,14 @@ mobile notification action resolves to the existing alert detail route rather
than an agent lifecycle operation. The ordinary-alert and probe-specific
payload proofs in `internal/api/alerting/external_probe_notifications_test.go`
pin this boundary.
+
+### Destination configuration failure cannot alter agent authority
+
+Notification destination API writes persist their complete configuration
+before publishing it to the live manager and return `500` without runtime
+mutation when persistence fails. This ordering may retain or reject email,
+webhook, or Apprise delivery state, but it cannot enroll, revoke, command,
+relink, or otherwise mutate an agent. The serialized write boundary in
+`internal/api/alerting/notifications.go` therefore prevents an uncommitted
+notification change from being mistaken for an agent lifecycle transition;
+its failure coverage lives in `internal/api/alerting/notifications_test.go`.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index e7be5ffba2..5a3f85ad61 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -9996,3 +9996,18 @@ when persistence fails. `TestHandleEnroll_Success`,
`TestMintBootstrapTokenForTarget_RollsBackWhenPersistenceFails` in
`internal/api/deploy_handlers_test.go` prove the persisted success state and
both failed-commit responses.
+
+### Notification destination writes report committed truth
+
+`PUT /api/notifications/email`, `PUT /api/notifications/apprise`, and webhook
+create, update, and delete routes publish destination changes only after the
+complete encrypted configuration write succeeds. A persistence failure returns
+`500` with a generic configuration-save error and does not mutate the live
+notification manager. Webhook writes are serialized around the inventory
+snapshot so concurrent API requests cannot build candidates from the same
+stale list. Update or delete publication failure after a committed write
+attempts to restore the prior durable inventory and returns `500`; it is never
+reported as success. Handler failure proofs live in
+`internal/api/alerting/notifications_test.go`, and
+`TestContract_NotificationDestinationWritesPublishOnlyAfterPersistence` pins
+the API publication ordering.
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index c0759d13b0..7b12484a4f 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -459,3 +459,16 @@ are bounded text POSTs containing Pulse health and UTC timing only—never alert
content, infrastructure names, destination credentials, or tenant data. This
watchdog path is deliberately independent of notification queue activation,
quiet hours, grouping, and escalation routing.
+
+### Destination configuration publishes only committed state
+
+Email, Apprise, and webhook create, update, and delete handlers treat encrypted
+configuration persistence as the publication boundary. They serialize
+destination writes, build complete webhook candidate inventories, persist the
+candidate first, and only then update the live notification manager. A failed
+write returns `500` and leaves the live destination inventory unchanged, so an
+operator cannot receive success for routing state that a restart would undo or
+have queued delivery cancelled by an uncommitted disable action. The forced
+failure paths are pinned in
+`internal/api/alerting/notifications_test.go`; the API ordering proof lives in
+`internal/api/contract_test.go`.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 49ba6acb02..d9642eb5ad 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -5669,3 +5669,18 @@ orphaned recovery. The canonical occurrence and receipt remain notification
queue identities; the alert ID carried by a mobile push is navigation state,
not a new persistence or recovery key. Restart and retry semantics therefore
remain owned by the existing notification queue and config persistence paths.
+
+### Destination runtime state follows durable configuration
+
+Email, Apprise, and webhook API mutations now commit their encrypted
+configuration before changing the live notification manager. Forced write
+failure returns `500` and leaves runtime routing unchanged; webhook handlers
+serialize the snapshot, candidate write, and publication sequence. This avoids
+restart divergence and prevents an uncommitted disable request from cancelling
+queued delivery. If the in-memory webhook publication unexpectedly fails after
+the durable candidate is written, the handler attempts to restore the prior
+inventory and reports failure rather than claiming success. These semantics add
+no backup or restore authority; they make the existing configuration file the
+explicit commit boundary. Persistence-failure proofs live in
+`internal/api/alerting/notifications_test.go` with API ordering pinned by
+`internal/api/contract_test.go`.
diff --git a/internal/api/alerting/notifications.go b/internal/api/alerting/notifications.go
index 6f4188eb4b..d443185501 100644
--- a/internal/api/alerting/notifications.go
+++ b/internal/api/alerting/notifications.go
@@ -70,6 +70,7 @@ type NotificationMonitor interface {
// NotificationHandlers handles notification-related HTTP endpoints
type NotificationHandlers struct {
stateMu sync.RWMutex
+ configMu sync.Mutex
mtMonitor *monitoring.MultiTenantMonitor
defaultMonitor NotificationMonitor
readState unifiedresources.ReadState
@@ -179,6 +180,9 @@ func (h *NotificationHandlers) GetEmailConfig(w http.ResponseWriter, r *http.Req
// UpdateEmailConfig updates the email configuration
func (h *NotificationHandlers) UpdateEmailConfig(w http.ResponseWriter, r *http.Request) {
+ h.configMu.Lock()
+ defer h.configMu.Unlock()
+
// Limit request body to 32KB to prevent memory exhaustion
r.Body = http.MaxBytesReader(w, r.Body, 32*1024)
@@ -211,7 +215,9 @@ func (h *NotificationHandlers) UpdateEmailConfig(w http.ResponseWriter, r *http.
return
}
- existingConfig := h.getMonitor(r.Context()).GetNotificationManager().GetEmailConfig()
+ monitor := h.getMonitor(r.Context())
+ manager := monitor.GetNotificationManager()
+ existingConfig := manager.GetEmailConfig()
// If password is empty, preserve the existing password
if config.Password == "" {
@@ -241,13 +247,15 @@ func (h *NotificationHandlers) UpdateEmailConfig(w http.ResponseWriter, r *http.
Int("rateLimit", config.RateLimit).
Msg("Parsed email config")
- h.getMonitor(r.Context()).GetNotificationManager().SetEmailConfig(config)
-
- // Save to persistent storage
- if err := h.getMonitor(r.Context()).GetConfigPersistence().SaveEmailConfig(config); err != nil {
- // Log error but don't fail the request
+ // Durable state is the publication boundary. Applying the live config first
+ // can cancel queued deliveries or change routing even when the update cannot
+ // survive a restart.
+ if err := monitor.GetConfigPersistence().SaveEmailConfig(config); err != nil {
log.Error().Err(err).Msg("Failed to save email configuration")
+ http.Error(w, "failed to save email configuration", http.StatusInternalServerError)
+ return
}
+ manager.SetEmailConfig(config)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
@@ -279,6 +287,9 @@ func (h *NotificationHandlers) GetAppriseConfig(w http.ResponseWriter, r *http.R
// UpdateAppriseConfig updates the Apprise configuration.
func (h *NotificationHandlers) UpdateAppriseConfig(w http.ResponseWriter, r *http.Request) {
+ h.configMu.Lock()
+ defer h.configMu.Unlock()
+
// Limit request body to 64KB to prevent memory exhaustion
r.Body = http.MaxBytesReader(w, r.Body, 64*1024)
@@ -297,7 +308,9 @@ func (h *NotificationHandlers) UpdateAppriseConfig(w http.ResponseWriter, r *htt
MinimumSeverity *string `json:"minimumSeverity"`
}
_ = json.Unmarshal(body, &presenceCheck)
- existingConfig := h.getMonitor(r.Context()).GetNotificationManager().GetAppriseConfig()
+ monitor := h.getMonitor(r.Context())
+ manager := monitor.GetNotificationManager()
+ existingConfig := manager.GetAppriseConfig()
// An empty API key means "keep the saved key": responses never include the
// stored value, so the settings form cannot round-trip it.
@@ -321,13 +334,14 @@ func (h *NotificationHandlers) UpdateAppriseConfig(w http.ResponseWriter, r *htt
Int("timeoutSeconds", config.TimeoutSeconds).
Msg("Parsed Apprise configuration update")
- h.getMonitor(r.Context()).GetNotificationManager().SetAppriseConfig(config)
-
- if err := h.getMonitor(r.Context()).GetConfigPersistence().SaveAppriseConfig(config); err != nil {
+ if err := monitor.GetConfigPersistence().SaveAppriseConfig(config); err != nil {
log.Error().Err(err).Msg("Failed to save Apprise configuration")
+ http.Error(w, "failed to save Apprise configuration", http.StatusInternalServerError)
+ return
}
+ manager.SetAppriseConfig(config)
- normalized := h.getMonitor(r.Context()).GetNotificationManager().GetAppriseConfig()
+ normalized := manager.GetAppriseConfig()
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(redactAppriseConfig(normalized)); err != nil {
@@ -399,6 +413,9 @@ func (h *NotificationHandlers) GetWebhooks(w http.ResponseWriter, r *http.Reques
// CreateWebhook creates a new webhook
func (h *NotificationHandlers) CreateWebhook(w http.ResponseWriter, r *http.Request) {
+ h.configMu.Lock()
+ defer h.configMu.Unlock()
+
// Limit request body to 64KB to prevent memory exhaustion
r.Body = http.MaxBytesReader(w, r.Body, 64*1024)
@@ -416,8 +433,11 @@ func (h *NotificationHandlers) CreateWebhook(w http.ResponseWriter, r *http.Requ
}
webhook = notifications.NormalizeWebhookConfig(webhook)
+ monitor := h.getMonitor(r.Context())
+ manager := monitor.GetNotificationManager()
+
// Validate webhook URL
- if err := h.getMonitor(r.Context()).GetNotificationManager().ValidateWebhookURL(webhook.URL); err != nil {
+ if err := manager.ValidateWebhookURL(webhook.URL); err != nil {
http.Error(w, fmt.Sprintf("Invalid webhook URL: %v", err), http.StatusBadRequest)
return
}
@@ -427,13 +447,15 @@ func (h *NotificationHandlers) CreateWebhook(w http.ResponseWriter, r *http.Requ
webhook.ID = utils.GenerateID("webhook")
}
- h.getMonitor(r.Context()).GetNotificationManager().AddWebhook(webhook)
-
- // Save webhooks to persistent storage with all fields
- webhooks := h.getMonitor(r.Context()).GetNotificationManager().GetWebhooks()
- if err := h.getMonitor(r.Context()).GetConfigPersistence().SaveWebhooks(webhooks); err != nil {
+ // Persist the complete candidate inventory before exposing the destination
+ // to live alert delivery.
+ webhooks := append(manager.GetWebhooks(), webhook)
+ if err := monitor.GetConfigPersistence().SaveWebhooks(webhooks); err != nil {
log.Error().Err(err).Msg("Failed to save webhooks")
+ http.Error(w, "failed to save webhook configuration", http.StatusInternalServerError)
+ return
}
+ manager.AddWebhook(webhook)
// Return the full webhook data including any extra fields like 'service'
var responseData map[string]interface{}
@@ -454,6 +476,9 @@ func (h *NotificationHandlers) CreateWebhook(w http.ResponseWriter, r *http.Requ
// UpdateWebhook updates an existing webhook
func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Request) {
+ h.configMu.Lock()
+ defer h.configMu.Unlock()
+
// Extract webhook ID from URL path
// Path is like /api/notifications/webhooks/{id} after routing
path := strings.TrimPrefix(r.URL.Path, "/api/notifications/webhooks/")
@@ -487,11 +512,16 @@ func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Requ
_ = json.Unmarshal(bodyBytes, &routingPresence)
webhook = notifications.NormalizeWebhookConfig(webhook)
+ monitor := h.getMonitor(r.Context())
+ manager := monitor.GetNotificationManager()
+
// Preserve original headers/customFields if the incoming values are redacted
// This happens when the frontend sends back masked values from GetWebhooks
- existingWebhooks := h.getMonitor(r.Context()).GetNotificationManager().GetWebhooks()
+ existingWebhooks := manager.GetWebhooks()
+ found := false
for _, existing := range existingWebhooks {
if existing.ID == webhookID {
+ found = true
if routingPresence.TagFilter == nil {
webhook.TagFilter = existing.TagFilter
}
@@ -534,23 +564,40 @@ func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Requ
break
}
}
+ if !found {
+ http.Error(w, fmt.Sprintf("webhook not found: %s", webhookID), http.StatusNotFound)
+ return
+ }
// Validate webhook URL
- if err := h.getMonitor(r.Context()).GetNotificationManager().ValidateWebhookURL(webhook.URL); err != nil {
+ if err := manager.ValidateWebhookURL(webhook.URL); err != nil {
http.Error(w, fmt.Sprintf("Invalid webhook URL: %v", err), http.StatusBadRequest)
return
}
webhook.ID = webhookID
- if err := h.getMonitor(r.Context()).GetNotificationManager().UpdateWebhook(webhookID, webhook); err != nil {
- http.Error(w, err.Error(), http.StatusNotFound)
- return
+ candidateWebhooks := make([]notifications.WebhookConfig, len(existingWebhooks))
+ copy(candidateWebhooks, existingWebhooks)
+ for i := range candidateWebhooks {
+ if candidateWebhooks[i].ID == webhookID {
+ candidateWebhooks[i] = webhook
+ break
+ }
}
-
- // Save webhooks to persistent storage
- webhooks := h.getMonitor(r.Context()).GetNotificationManager().GetWebhooks()
- if err := h.getMonitor(r.Context()).GetConfigPersistence().SaveWebhooks(webhooks); err != nil {
+ if err := monitor.GetConfigPersistence().SaveWebhooks(candidateWebhooks); err != nil {
log.Error().Err(err).Msg("Failed to save webhooks")
+ http.Error(w, "failed to save webhook configuration", http.StatusInternalServerError)
+ return
+ }
+ if err := manager.UpdateWebhook(webhookID, webhook); err != nil {
+ // The handler serializes destination writes, so this indicates an
+ // out-of-band mutation. Restore the prior durable inventory rather than
+ // leave restart-time state ahead of the live manager.
+ if rollbackErr := monitor.GetConfigPersistence().SaveWebhooks(existingWebhooks); rollbackErr != nil {
+ log.Error().Err(rollbackErr).Msg("Failed to roll back webhook configuration")
+ }
+ http.Error(w, "failed to publish webhook configuration", http.StatusInternalServerError)
+ return
}
// Return the full webhook data including any extra fields like 'service'
@@ -572,6 +619,9 @@ func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Requ
// DeleteWebhook deletes a webhook
func (h *NotificationHandlers) DeleteWebhook(w http.ResponseWriter, r *http.Request) {
+ h.configMu.Lock()
+ defer h.configMu.Unlock()
+
// Extract webhook ID from URL path
// Path is like /api/notifications/webhooks/{id} after routing
path := strings.TrimPrefix(r.URL.Path, "/api/notifications/webhooks/")
@@ -582,15 +632,34 @@ func (h *NotificationHandlers) DeleteWebhook(w http.ResponseWriter, r *http.Requ
return
}
- if err := h.getMonitor(r.Context()).GetNotificationManager().DeleteWebhook(webhookID); err != nil {
- http.Error(w, err.Error(), http.StatusNotFound)
+ monitor := h.getMonitor(r.Context())
+ manager := monitor.GetNotificationManager()
+ existingWebhooks := manager.GetWebhooks()
+ candidateWebhooks := make([]notifications.WebhookConfig, 0, len(existingWebhooks))
+ found := false
+ for _, webhook := range existingWebhooks {
+ if webhook.ID == webhookID {
+ found = true
+ continue
+ }
+ candidateWebhooks = append(candidateWebhooks, webhook)
+ }
+ if !found {
+ http.Error(w, fmt.Sprintf("webhook not found: %s", webhookID), http.StatusNotFound)
return
}
- // Save webhooks to persistent storage
- webhooks := h.getMonitor(r.Context()).GetNotificationManager().GetWebhooks()
- if err := h.getMonitor(r.Context()).GetConfigPersistence().SaveWebhooks(webhooks); err != nil {
+ if err := monitor.GetConfigPersistence().SaveWebhooks(candidateWebhooks); err != nil {
log.Error().Err(err).Msg("Failed to save webhooks")
+ http.Error(w, "failed to save webhook configuration", http.StatusInternalServerError)
+ return
+ }
+ if err := manager.DeleteWebhook(webhookID); err != nil {
+ if rollbackErr := monitor.GetConfigPersistence().SaveWebhooks(existingWebhooks); rollbackErr != nil {
+ log.Error().Err(rollbackErr).Msg("Failed to roll back webhook configuration")
+ }
+ http.Error(w, "failed to publish webhook configuration", http.StatusInternalServerError)
+ return
}
if err := utils.WriteJSONResponse(w, map[string]string{"status": "success"}); err != nil {
diff --git a/internal/api/alerting/notifications_contract_test.go b/internal/api/alerting/notifications_contract_test.go
index 4f37877f56..0af3a20f8b 100644
--- a/internal/api/alerting/notifications_contract_test.go
+++ b/internal/api/alerting/notifications_contract_test.go
@@ -52,7 +52,6 @@ func TestContract_WebhookSigningSecretMaskedAndPreserved(t *testing.T) {
mockManager.On("UpdateWebhook", "wh-signed", tmock.MatchedBy(func(w notifications.WebhookConfig) bool {
return w.SigningSecret == "stored-secret"
})).Return(nil).Once()
- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{stored}).Once()
mockPersistence.On("SaveWebhooks", tmock.Anything).Return(nil).Once()
update := stored
diff --git a/internal/api/alerting/notifications_test.go b/internal/api/alerting/notifications_test.go
index 84de96a0df..62a0429cb5 100644
--- a/internal/api/alerting/notifications_test.go
+++ b/internal/api/alerting/notifications_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -411,19 +412,6 @@ func TestNotificationHandlers(t *testing.T) {
assert.Equal(t, 400, w.Code)
})
- t.Run("UpdateEmailConfig_SaveError", func(t *testing.T) {
- cfg := notifications.EmailConfig{Enabled: true}
- mockManager.On("GetEmailConfig").Return(notifications.EmailConfig{}).Once()
- mockManager.On("SetEmailConfig", mock.Anything).Return().Once()
- mockPersistence.On("SaveEmailConfig", mock.Anything).Return(fmt.Errorf("save error")).Once()
-
- body, _ := json.Marshal(cfg)
- req := httptest.NewRequest("PUT", "/api/notifications/email", bytes.NewReader(body))
- w := httptest.NewRecorder()
- h.UpdateEmailConfig(w, req)
- assert.Equal(t, 200, w.Code) // Matches implementation: logs error but returns success
- })
-
t.Run("GetWebhooks", func(t *testing.T) {
webhooks := []notifications.WebhookConfig{
{
@@ -590,7 +578,6 @@ func TestNotificationHandlers(t *testing.T) {
mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{{ID: "wh1"}}).Once()
mockManager.On("ValidateWebhookURL", mock.Anything).Return(nil).Once()
mockManager.On("UpdateWebhook", "wh1", mock.Anything).Return(nil).Once()
- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{webhook}).Once()
mockPersistence.On("SaveWebhooks", mock.Anything).Return(nil).Once()
body, _ := json.Marshal(webhook)
@@ -621,7 +608,6 @@ func TestNotificationHandlers(t *testing.T) {
) && cfg.TagMode == "any" && cfg.MinimumSeverity == "critical"
}),
).Return(nil).Once()
- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{existing}).Once()
mockPersistence.On("SaveWebhooks", mock.Anything).Return(nil).Once()
req := httptest.NewRequest(
@@ -642,7 +628,7 @@ func TestNotificationHandlers(t *testing.T) {
t.Run("DeleteWebhook", func(t *testing.T) {
mockManager.On("DeleteWebhook", "wh1").Return(nil).Once()
- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{}).Once()
+ mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{{ID: "wh1"}}).Once()
mockPersistence.On("SaveWebhooks", mock.Anything).Return(nil).Once()
req := httptest.NewRequest("DELETE", "/api/notifications/webhooks/wh1", nil)
@@ -725,12 +711,11 @@ func TestNotificationHandlers(t *testing.T) {
mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{{ID: "wh1"}}).Once()
mockManager.On("ValidateWebhookURL", mock.Anything).Return(nil).Once()
mockManager.On("UpdateWebhook", "wh1", mock.Anything).Return(nil).Once()
- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{{ID: "wh1"}}).Once()
mockPersistence.On("SaveWebhooks", mock.Anything).Return(nil).Once()
}},
{"DELETE", "/api/notifications/webhooks/wh1", func() {
mockManager.On("DeleteWebhook", "wh1").Return(nil).Once()
- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{}).Once()
+ mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{{ID: "wh1"}}).Once()
mockPersistence.On("SaveWebhooks", mock.Anything).Return(nil).Once()
}},
{"GET", "/api/notifications/webhook-templates", func() {}},
@@ -944,7 +929,6 @@ func TestNotificationHandlers(t *testing.T) {
mockManager.On("UpdateWebhook", "wh1", mock.MatchedBy(func(w notifications.WebhookConfig) bool {
return w.Headers["Auth"] == "secret" && w.CustomFields["Key"] == "value"
})).Return(nil).Once()
- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{updated}).Once()
mockPersistence.On("SaveWebhooks", mock.Anything).Return(nil).Once()
body, _ := json.Marshal(updated)
@@ -976,7 +960,6 @@ func TestNotificationHandlers(t *testing.T) {
w.CustomFields["app_token"] == "" &&
w.CustomFields["user_token"] == ""
})).Return(nil).Once()
- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{existing}).Once()
mockPersistence.On("SaveWebhooks", mock.Anything).Return(nil).Once()
body, _ := json.Marshal(map[string]interface{}{
@@ -1031,6 +1014,100 @@ func TestNotificationHandlers(t *testing.T) {
})
}
+func TestNotificationConfigPersistenceFailureDoesNotPublishRuntimeState(t *testing.T) {
+ newHandlers := func() (*NotificationHandlers, *MockNotificationManager, *MockNotificationConfigPersistence) {
+ monitor := new(MockNotificationMonitor)
+ manager := new(MockNotificationManager)
+ persistence := new(MockNotificationConfigPersistence)
+ monitor.On("GetNotificationManager").Return(manager)
+ monitor.On("GetConfigPersistence").Return(persistence)
+ return NewNotificationHandlers(nil, monitor), manager, persistence
+ }
+
+ t.Run("email", func(t *testing.T) {
+ h, manager, persistence := newHandlers()
+ manager.On("GetEmailConfig").Return(notifications.EmailConfig{Enabled: true}).Once()
+ persistence.On("SaveEmailConfig", mock.MatchedBy(func(cfg notifications.EmailConfig) bool {
+ return !cfg.Enabled
+ })).Return(errors.New("storage unavailable")).Once()
+
+ req := httptest.NewRequest(http.MethodPut, "/api/notifications/email", strings.NewReader(`{"enabled":false}`))
+ rec := httptest.NewRecorder()
+ h.UpdateEmailConfig(rec, req)
+
+ assert.Equal(t, http.StatusInternalServerError, rec.Code)
+ manager.AssertNotCalled(t, "SetEmailConfig", mock.Anything)
+ persistence.AssertExpectations(t)
+ })
+
+ t.Run("apprise", func(t *testing.T) {
+ h, manager, persistence := newHandlers()
+ manager.On("GetAppriseConfig").Return(notifications.AppriseConfig{Enabled: true}).Once()
+ persistence.On("SaveAppriseConfig", mock.MatchedBy(func(cfg notifications.AppriseConfig) bool {
+ return !cfg.Enabled
+ })).Return(errors.New("storage unavailable")).Once()
+
+ req := httptest.NewRequest(http.MethodPut, "/api/notifications/apprise", strings.NewReader(`{"enabled":false}`))
+ rec := httptest.NewRecorder()
+ h.UpdateAppriseConfig(rec, req)
+
+ assert.Equal(t, http.StatusInternalServerError, rec.Code)
+ manager.AssertNotCalled(t, "SetAppriseConfig", mock.Anything)
+ persistence.AssertExpectations(t)
+ })
+
+ t.Run("webhook create", func(t *testing.T) {
+ h, manager, persistence := newHandlers()
+ manager.On("ValidateWebhookURL", "https://example.com/new").Return(nil).Once()
+ manager.On("GetWebhooks").Return([]notifications.WebhookConfig{{ID: "existing"}}).Once()
+ persistence.On("SaveWebhooks", mock.MatchedBy(func(webhooks []notifications.WebhookConfig) bool {
+ return len(webhooks) == 2 && webhooks[1].Name == "new"
+ })).Return(errors.New("storage unavailable")).Once()
+
+ req := httptest.NewRequest(http.MethodPost, "/api/notifications/webhooks", strings.NewReader(`{"name":"new","url":"https://example.com/new"}`))
+ rec := httptest.NewRecorder()
+ h.CreateWebhook(rec, req)
+
+ assert.Equal(t, http.StatusInternalServerError, rec.Code)
+ manager.AssertNotCalled(t, "AddWebhook", mock.Anything)
+ persistence.AssertExpectations(t)
+ })
+
+ t.Run("webhook update", func(t *testing.T) {
+ h, manager, persistence := newHandlers()
+ existing := notifications.WebhookConfig{ID: "wh1", Name: "old", URL: "https://example.com/hook"}
+ manager.On("GetWebhooks").Return([]notifications.WebhookConfig{existing}).Once()
+ manager.On("ValidateWebhookURL", existing.URL).Return(nil).Once()
+ persistence.On("SaveWebhooks", mock.MatchedBy(func(webhooks []notifications.WebhookConfig) bool {
+ return len(webhooks) == 1 && webhooks[0].Name == "new"
+ })).Return(errors.New("storage unavailable")).Once()
+
+ req := httptest.NewRequest(http.MethodPut, "/api/notifications/webhooks/wh1", strings.NewReader(`{"name":"new","url":"https://example.com/hook"}`))
+ rec := httptest.NewRecorder()
+ h.UpdateWebhook(rec, req)
+
+ assert.Equal(t, http.StatusInternalServerError, rec.Code)
+ manager.AssertNotCalled(t, "UpdateWebhook", mock.Anything, mock.Anything)
+ persistence.AssertExpectations(t)
+ })
+
+ t.Run("webhook delete", func(t *testing.T) {
+ h, manager, persistence := newHandlers()
+ manager.On("GetWebhooks").Return([]notifications.WebhookConfig{{ID: "wh1"}}).Once()
+ persistence.On("SaveWebhooks", mock.MatchedBy(func(webhooks []notifications.WebhookConfig) bool {
+ return len(webhooks) == 0
+ })).Return(errors.New("storage unavailable")).Once()
+
+ req := httptest.NewRequest(http.MethodDelete, "/api/notifications/webhooks/wh1", nil)
+ rec := httptest.NewRecorder()
+ h.DeleteWebhook(rec, req)
+
+ assert.Equal(t, http.StatusInternalServerError, rec.Code)
+ manager.AssertNotCalled(t, "DeleteWebhook", mock.Anything)
+ persistence.AssertExpectations(t)
+ })
+}
+
func TestClassifyNotificationError(t *testing.T) {
tests := []struct {
name string
@@ -1218,7 +1295,6 @@ func TestNotificationHandlersWebhookSigningSecretLifecycle(t *testing.T) {
mockManager.On("UpdateWebhook", "wh-signed", mock.MatchedBy(func(w notifications.WebhookConfig) bool {
return w.SigningSecret == "stored-secret"
})).Return(nil).Once()
- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{stored}).Once()
mockPersistence.On("SaveWebhooks", mock.Anything).Return(nil).Once()
update := stored
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index e375650414..30080cec5c 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -24487,3 +24487,49 @@ func TestContract_NodeTestTelemetryRecordsOnlyAfterTargetValidation(t *testing.T
}
}
}
+
+func TestContract_NotificationDestinationWritesPublishOnlyAfterPersistence(t *testing.T) {
+ source, err := os.ReadFile(filepath.Clean("alerting/notifications.go"))
+ if err != nil {
+ t.Fatalf("read notification handlers: %v", err)
+ }
+ handlers := string(source)
+
+ for _, tc := range []struct {
+ name string
+ function string
+ persistCall string
+ publishCall string
+ }{
+ {name: "email", function: "UpdateEmailConfig", persistCall: "SaveEmailConfig(config)", publishCall: "manager.SetEmailConfig(config)"},
+ {name: "apprise", function: "UpdateAppriseConfig", persistCall: "SaveAppriseConfig(config)", publishCall: "manager.SetAppriseConfig(config)"},
+ {name: "webhook create", function: "CreateWebhook", persistCall: "SaveWebhooks(webhooks)", publishCall: "manager.AddWebhook(webhook)"},
+ {name: "webhook update", function: "UpdateWebhook", persistCall: "SaveWebhooks(candidateWebhooks)", publishCall: "manager.UpdateWebhook(webhookID, webhook)"},
+ {name: "webhook delete", function: "DeleteWebhook", persistCall: "SaveWebhooks(candidateWebhooks)", publishCall: "manager.DeleteWebhook(webhookID)"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ marker := "func (h *NotificationHandlers) " + tc.function + "("
+ start := strings.Index(handlers, marker)
+ if start < 0 {
+ t.Fatalf("%s not found", tc.function)
+ }
+ body := handlers[start:]
+ if end := strings.Index(body[1:], "\nfunc "); end >= 0 {
+ body = body[:end+1]
+ }
+
+ persistAt := strings.Index(body, tc.persistCall)
+ publishAt := strings.Index(body, tc.publishCall)
+ if persistAt < 0 || publishAt < 0 {
+ t.Fatalf("%s missing persistence/publication boundary: persist=%d publish=%d", tc.function, persistAt, publishAt)
+ }
+ if persistAt > publishAt {
+ t.Fatalf("%s publishes live destination state before persistence", tc.function)
+ }
+ failurePath := body[persistAt:publishAt]
+ if !strings.Contains(failurePath, "http.StatusInternalServerError") || !strings.Contains(failurePath, "return") {
+ t.Fatalf("%s does not stop publication after persistence failure", tc.function)
+ }
+ })
+ }
+}