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.

Fix SMTP provider authentication and isolate delivery envelopes

rcourtmanbec3a10019af
diff --git a/docs/release-control/v6/internal/records/notification-smtp-delivery-reliability-2026-10-17.md b/docs/release-control/v6/internal/records/notification-smtp-delivery-reliability-2026-10-17.md
new file mode 100644
index 0000000000..e5584dfe98
--- /dev/null
+++ b/docs/release-control/v6/internal/records/notification-smtp-delivery-reliability-2026-10-17.md
@@ -0,0 +1,83 @@
+# SMTP notification delivery reliability
+
+## Scope and baseline
+
+The 17 October 2026 production aggregate retrieved at 22:01:16 UTC contains
+8,553 clean rotating installation IDs. Of 8,474 IDs with terminal notification
+failure coverage, 503 report at least one failure. The rolling seven-day sums
+include 121,418 terminal failures, with 37,480 classified as connectivity and
+30,847 as authentication. Class coverage differs by sender schema. These are
+latest-ping rolling reports, not distinct customers or new incidents since an
+earlier read. The aggregate does not identify the notification transport or
+provider responsible for those failures.
+
+Baseline source is `8f10dfa9438151db41ea01ccf19e58b669601e96`.
+Real loopback SMTP regression tests against that source reproduce two defects:
+
+- Supported provider-default usernames pass configuration validation but do
+ not enable authentication in the delivery manager. SendGrid, Postmark,
+ SparkPost and Resend default-username controls all receive SMTP 530 because
+ Pulse sends MAIL without AUTH, for both saved and standalone managers.
+- Acquiring two delivery configurations before sending either overwrites the
+ first delivery's sender and recipients. The receiver accepts the second
+ envelope for the first message.
+
+## Current boundary
+
+`NewEnhancedEmailManager` resolves provider identity and authentication once
+and owns a copy of the email configuration. The notification manager prepares
+independent per-delivery configurations while retaining shared rate-limit state
+for the cached transport. It does not rewrite admitted queue configuration,
+refresh old credentials, replay retained failures or change transport retries.
+The notification contract owns this rule; the reporting API contract references
+that shared delivery boundary.
+
+`email_delivery_isolation_test.go` exercises real SMTP authentication, accepted
+envelopes, overlapping preparation, eight concurrent sends, the shared rate
+budget and persistent queue/audit readback after restart. A rejected-credential
+control remains one authentication dead letter with no successful receipt.
+Existing grouped, direct and recovery tests now inspect the SMTP envelope
+instead of requiring mutation of another delivery's cached configuration.
+
+## Verification
+
+Verification uses the exact source copy on `pulse-dev`, selected Go toolchain
+`go1.26.9`, through the normal `pulse-dev-validate` admission wrapper.
+
+- Focused SMTP controls passed, including provider-default authentication,
+ independent envelopes, concurrent sends, shared rate limits, queue restart,
+ and the existing grouped/direct/recovery envelope paths.
+- `go test ./internal/notifications -count=1 -timeout=15m` passed in 192.179s.
+- The same focused controls with `go test -race` passed in 1.628s.
+
+The focused selection for both ordinary and race execution was:
+
+```text
+^(TestEmailDelivery|TestQueuedEmailProviderAuthentication|TestSendGroupedEmail_UsesFromAsRecipient$|TestSendEmail_UsesSharedDeliveryExecutor$|TestSendResolvedNotificationsDirectDispatchesEnabledTargets$|TestSendHTMLEmailWithError_ExistingEmailManager$)
+```
+
+Both commands used `./internal/notifications`, `-count=1`, and respective
+timeouts of 90s and 180s. The ordinary focused run used `-json`. Retained logs
+are `focused.jsonl`, `notifications.log` and `race.log` under
+`/opt/pulse-release-worker/task-proofs/notification-failures-20261017/` on
+`pulse-dev`. The verification wrapper exited zero.
+
+Runtime source SHA-256 bindings:
+
+```text
+e8550b65718c0c6456bc0a0811bf5886c9c1bc8ff5fa3ff1165b62c180e1f0d5 internal/notifications/email_enhanced.go
+981c8c445ed885f93c4eafc7ff8772da5b3e06c19af5c74f2c65b14f71a6c705 internal/notifications/notifications.go
+```
+
+## Limits and residual work
+
+Synthetic SMTP acceptance proves the sender's protocol and queue verdict. It
+does not establish delivery to a real mailbox, native provider compatibility,
+release inclusion or the proportion of fleet failures caused by either defect.
+The production aggregate cannot attribute those counts to these SMTP paths.
+
+The existing `notification-delivery-terminal-failure-diagnosis` coverage gap
+remains open for destination-level repeated-failure handling and recovery
+guidance. Invalid destination credentials and external connectivity failures
+remain real failures. Historical audits and telemetry are not rewritten, and
+these source corrections do not establish fleet recovery.
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index b344c7174c..37a5253116 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -10030,7 +10030,7 @@
},
{
"id": "notification-delivery-terminal-failure-diagnosis",
- "summary": "Terminal notification failures are 36% of resolved delivery outcomes fleet-wide (126,337 dead-lettered against 224,692 delivered, week to 2026-09-03, 6,668 clean installs), and the failure breakdown could not explain why. Two causes, one fixed here. First, the delivery failure class was inferred from Go error prose, so any failure whose text carried no recognised token fell to unknown (31,218, the modal bucket) and the destination's own response body could steer the class, letting a 500 whose body says 'rate limit' be recorded as rate_limited; senders now declare the class and SMTP reply codes, DNS, x509 and timeout errors classify structurally. Second, the shape is concentration, not breadth: only 400 of 6,668 installs report any failure, the top 10 carry 73,276 (58%), the median failing install has 13, and 72 installs that delivered nothing at all in seven days account for 62,615 failures (50%). Pulse retries a permanently broken destination three times per notification forever and never tells the operator the destination has never once succeeded, so the worst install burned 20,312 dead letters against 36 deliveries. Still open: back off or disable a destination with no successful delivery, surface that state on the destinations surface, and add server_error guidance to the delivery health card, which currently falls through to the unknown copy for a class the client already emits.",
+ "summary": "The 17 October 2026 production clean weekly cohort has 503 of 8,474 covered rotating IDs reporting terminal notification failures, with rolling totals of 121,418 failures and 245,982 deliveries. The largest classified failure sums are connectivity (37,480) and authentication (30,847), with schema-dependent coverage. These aggregates do not identify a transport/provider or prove a release regression. Typed failure classification, deterministic-failure short circuiting and explicit retained-queue recovery already exist. This source slice repairs independently reproduced SMTP defects: provider-default usernames could pass validation without enabling AUTH, and preparing concurrent deliveries could overwrite an earlier sender/recipient envelope. Real SMTP controls cover accepted messages, concurrent delivery isolation, shared rate limits and persistent queue verdicts; bad credentials still produce an authentication dead letter. Remaining work is destination-level repeated-failure handling, evidence of destination recovery, and precise delivery-health guidance. The source fixes do not establish how much fleet failure they explain or that the production fleet has recovered.",
"owner": "project-owner",
"status": "triaged",
"recorded_at": "2026-09-03",
@@ -10043,6 +10043,11 @@
],
"proposed_resolution": "lane-expansion",
"evidence": [
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/records/notification-smtp-delivery-reliability-2026-10-17.md",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "frontend-modern/src/utils/alertDestinationsPresentation.ts",
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index f137680bcc..8f58276558 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -12136,8 +12136,12 @@ and repeatable customer outcomes.
### Report email shares the canonical SMTP retry verdict
Attachment delivery through `internal/notifications/email_enhanced.go` uses
-notifications-owned `sendEmailWithOptions`; reporting must not introduce a
-separate retry classification. That transport stops on authentication,
+notifications-owned `sendEmailWithOptions`. Reporting must not introduce a
+separate retry classification. Reporting also inherits the notification-owned
+[provider authentication and per-delivery envelope boundary](notifications.md#smtp-authentication-and-envelopes-belong-to-each-delivery).
+It must not suppress a supported provider's default SMTP username or mutate
+another delivery's configuration when preparing a report.
+That transport stops on authentication,
configuration, or rejection failures and preserves temporary-failure retries.
Its returned failure retains the structured cause and actual attempt count.
SMTP acceptance proves only that the configured server accepted the message,
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index 9fffc000fb..a7b8d978e1 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -150,6 +150,21 @@ monitor startup test retains saved-destination restoration and its audit check.
This changes callback sequencing only: no SQLite driver, schema/SQL, provider
policy, credential, SSRF boundary or notification payload is changed.
+### SMTP authentication and envelopes belong to each delivery
+
+SMTP managers resolve the provider identity and any supported default username
+before deciding whether credentials require authentication. Explicit usernames
+take precedence. Validation, connection tests and real sends use the same
+resolved credentials without replacing the saved username. Invalid credentials
+retain the existing authentication failure and immediate dead-letter policy.
+
+Each email delivery owns its configuration snapshot, including its sender and
+recipients. Preparing a concurrent alert or report cannot change an in-flight
+delivery's envelope or retry policy. Deliveries using the cached SMTP transport
+share its rate-limit state without mutating its configuration. Saved settings
+and already-admitted queue snapshots remain independent. This does not refresh
+retained destinations or credentials after an edit, or add automatic replay.
+
### Delivery verdicts survive session cleanup and interrupted diagnostics
A successful final SMTP DATA reply establishes server acceptance. Plain SMTP,
diff --git a/internal/notifications/email_delivery_isolation_test.go b/internal/notifications/email_delivery_isolation_test.go
new file mode 100644
index 0000000000..df13a36f37
--- /dev/null
+++ b/internal/notifications/email_delivery_isolation_test.go
@@ -0,0 +1,274 @@
+package notifications
+
+import (
+ "encoding/base64"
+ "fmt"
+ "net"
+ "net/textproto"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/stretchr/testify/require"
+)
+
+type isolatedSMTPReceipt struct {
+ from string
+ recipients []string
+}
+
+func awaitIsolatedSMTPReceipt(t *testing.T, receipts <-chan isolatedSMTPReceipt) isolatedSMTPReceipt {
+ t.Helper()
+ select {
+ case receipt := <-receipts:
+ return receipt
+ case <-time.After(5 * time.Second):
+ t.Fatal("missing accepted SMTP envelope")
+ return isolatedSMTPReceipt{}
+ }
+}
+
+// Only synthetic mail reaches this loopback receiver. It requires the exact
+// AUTH PLAIN exchange when credentials are supplied, and records envelopes
+// only after accepting DATA so configuration isolation is tested on the wire.
+func isolatedSMTPReceiver(t *testing.T, username, password string) (EmailConfig, <-chan isolatedSMTPReceipt) {
+ t.Helper()
+ listener, err := net.Listen("tcp4", "127.0.0.1:0")
+ require.NoError(t, err)
+ receipts := make(chan isolatedSMTPReceipt, 16)
+ done := make(chan struct{})
+ var sessions sync.WaitGroup
+ go func() {
+ defer close(done)
+ for {
+ raw, err := listener.Accept()
+ if err != nil {
+ return
+ }
+ sessions.Add(1)
+ go func() {
+ defer sessions.Done()
+ defer raw.Close()
+ _ = raw.SetDeadline(time.Now().Add(5 * time.Second))
+ conn := textproto.NewConn(raw)
+ if conn.PrintfLine("220 localhost ESMTP") != nil {
+ return
+ }
+ authenticated := username == ""
+ var receipt isolatedSMTPReceipt
+ for {
+ line, err := conn.ReadLine()
+ if err != nil {
+ return
+ }
+ command, argument, _ := strings.Cut(line, " ")
+ switch command {
+ case "EHLO", "HELO":
+ err = conn.PrintfLine("250-localhost\r\n250 AUTH PLAIN")
+ case "AUTH":
+ want := "PLAIN " + base64.StdEncoding.EncodeToString([]byte("\x00"+username+"\x00"+password))
+ if argument == want {
+ authenticated = true
+ err = conn.PrintfLine("235 Authenticated")
+ } else {
+ err = conn.PrintfLine("535 Invalid credentials")
+ }
+ case "MAIL":
+ if !authenticated {
+ err = conn.PrintfLine("530 Authentication required")
+ } else {
+ receipt = isolatedSMTPReceipt{from: argument}
+ err = conn.PrintfLine("250 OK")
+ }
+ case "RCPT":
+ receipt.recipients = append(receipt.recipients, argument)
+ err = conn.PrintfLine("250 OK")
+ case "DATA":
+ if conn.PrintfLine("354 Send message") != nil {
+ return
+ }
+ if _, err = conn.ReadDotBytes(); err != nil {
+ return
+ }
+ if err = conn.PrintfLine("250 Accepted"); err == nil {
+ receipts <- receipt
+ }
+ case "QUIT":
+ _ = conn.PrintfLine("221 Bye")
+ return
+ default:
+ err = conn.PrintfLine("500 Unsupported command")
+ }
+ if err != nil {
+ return
+ }
+ }
+ }()
+ }
+ }()
+ t.Cleanup(func() { _ = listener.Close(); <-done; sessions.Wait() })
+ _, rawPort, err := net.SplitHostPort(listener.Addr().String())
+ require.NoError(t, err)
+ port, err := strconv.Atoi(rawPort)
+ require.NoError(t, err)
+ return EmailConfig{Enabled: true, SMTPHost: "127.0.0.1", SMTPPort: port,
+ From: "[email protected]", To: []string{"[email protected]"}, RateLimit: 100}, receipts
+}
+
+func TestEmailDeliveryAuthenticatesProviderDefaultUsername(t *testing.T) {
+ const password = "synthetic-provider-key"
+ for _, tc := range []struct{ provider, username string }{
+ {"SendGrid", "apikey"}, {"Postmark", password},
+ {"SparkPost", "SMTP_Injection"}, {"Resend", "resend"},
+ } {
+ for _, saved := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/saved=%t", tc.provider, saved), func(t *testing.T) {
+ cfg, receipts := isolatedSMTPReceiver(t, tc.username, password)
+ cfg.Provider, cfg.Password = tc.provider, password
+ var delivery *EnhancedEmailManager
+ if saved {
+ manager := NewNotificationManagerWithDataDir("", t.TempDir())
+ t.Cleanup(manager.Stop)
+ manager.SetEmailConfig(cfg)
+ delivery, _ = manager.emailDeliveryManager(cfg)
+ } else {
+ delivery = newEmailDeliveryManager(cfg, cfg.To)
+ }
+ require.NoError(t, delivery.ValidateConfiguration())
+ require.NoError(t, delivery.SendEmailWithRetry("synthetic test", "<p>test</p>", "test"))
+ require.Len(t, receipts, 1, "valid provider credentials must produce an accepted message")
+ require.Empty(t, cfg.Username, "provider resolution must not mutate saved input")
+ })
+ }
+ }
+}
+
+func TestEmailDeliveryKeepsIndependentEnvelopeSnapshots(t *testing.T) {
+ cfg, receipts := isolatedSMTPReceiver(t, "", "")
+ manager := NewNotificationManagerWithDataDir("", t.TempDir())
+ t.Cleanup(manager.Stop)
+ manager.SetEmailConfig(cfg)
+ saved := manager.GetEmailConfig()
+ firstConfig, secondConfig := copyEmailConfig(cfg), copyEmailConfig(cfg)
+ firstConfig.From, firstConfig.To = "[email protected]", []string{"[email protected]"}
+ secondConfig.From, secondConfig.To = "[email protected]", []string{"[email protected]"}
+ first, _ := manager.emailDeliveryManager(firstConfig)
+ second, _ := manager.emailDeliveryManager(secondConfig)
+ // Both configurations are acquired before either is sent, as can happen
+ // with independent queue workers or a scheduled report and an alert.
+ require.NoError(t, first.SendEmailWithRetry("first", "<p>first</p>", "first"))
+ require.NoError(t, second.SendEmailWithRetry("second", "<p>second</p>", "second"))
+ require.Len(t, receipts, 2)
+ require.Equal(t, isolatedSMTPReceipt{"FROM:<[email protected]>", []string{"TO:<[email protected]>"}}, <-receipts)
+ require.Equal(t, isolatedSMTPReceipt{"FROM:<[email protected]>", []string{"TO:<[email protected]>"}}, <-receipts)
+ require.Equal(t, saved, manager.GetEmailConfig())
+}
+
+func TestEmailDeliverySnapshotsShareRateLimit(t *testing.T) {
+ cfg, receipts := isolatedSMTPReceiver(t, "", "")
+ cfg.RateLimit = 1
+ manager := NewNotificationManagerWithDataDir("", t.TempDir())
+ t.Cleanup(manager.Stop)
+ manager.SetEmailConfig(cfg)
+ first, _ := manager.emailDeliveryManager(cfg)
+ second, _ := manager.emailDeliveryManager(cfg)
+ // Avoid sleeping through transport retries for a deterministic local limit.
+ first.config.MaxRetries, second.config.MaxRetries = 0, 0
+ require.NoError(t, first.SendEmailWithRetry("first", "<p>test</p>", "test"))
+ err := second.SendEmailWithRetry("second", "<p>test</p>", "test")
+ require.Error(t, err)
+ require.Equal(t, NotificationFailureRateLimited, ClassifyNotificationFailureError(err))
+ require.Len(t, receipts, 1, "isolating a delivery must not reset the destination's rate budget")
+}
+
+func TestEmailDeliveryConcurrentEnvelopes(t *testing.T) {
+ cfg, receipts := isolatedSMTPReceiver(t, "", "")
+ manager := NewNotificationManagerWithDataDir("", t.TempDir())
+ t.Cleanup(manager.Stop)
+ manager.SetEmailConfig(cfg)
+ const workers = 8
+ saved := manager.GetEmailConfig()
+ start := make(chan struct{})
+ results := make(chan error, workers)
+ for index := 0; index < workers; index++ {
+ go func(index int) {
+ own := copyEmailConfig(cfg)
+ own.From = fmt.Sprintf("sender-%[email protected]", index)
+ own.To = []string{fmt.Sprintf("recipient-%[email protected]", index)}
+ <-start
+ results <- manager.sendHTMLEmailWithError("synthetic test", "<p>test</p>", "test", own)
+ }(index)
+ }
+ close(start)
+ for index := 0; index < workers; index++ {
+ require.NoError(t, <-results)
+ }
+ require.Len(t, receipts, workers)
+ seen := make(map[string][]string)
+ for index := 0; index < workers; index++ {
+ receipt := <-receipts
+ seen[receipt.from] = receipt.recipients
+ }
+ for index := 0; index < workers; index++ {
+ require.Equal(t, []string{fmt.Sprintf("TO:<recipient-%[email protected]>", index)},
+ seen[fmt.Sprintf("FROM:<sender-%[email protected]>", index)])
+ }
+ require.Equal(t, saved, manager.GetEmailConfig())
+}
+
+func TestQueuedEmailProviderAuthenticationVerdictSurvivesRestart(t *testing.T) {
+ for _, valid := range []bool{true, false} {
+ t.Run(fmt.Sprintf("valid=%t", valid), func(t *testing.T) {
+ cfg, receipts := isolatedSMTPReceiver(t, "apikey", "synthetic-provider-key")
+ cfg.Provider, cfg.Password = "SendGrid", "synthetic-provider-key"
+ if !valid {
+ cfg.Password = "synthetic-invalid-key"
+ }
+ dir := t.TempDir()
+ manager := NewNotificationManagerWithDeferredQueue("", dir)
+ t.Cleanup(manager.Stop)
+ manager.SetEmailConfig(cfg)
+ manager.SetGroupingConfig(false, 0, false, false)
+ manager.SendAlert(&alerts.Alert{ID: "smtp-auth-test", ResourceName: "synthetic-node",
+ Type: "cpu", Level: alerts.AlertLevelWarning, Message: "synthetic alert", StartTime: time.Now()})
+ pending, err := manager.queue.GetPending(10)
+ require.NoError(t, err)
+ require.Len(t, pending, 1)
+ id := pending[0].ID
+ manager.StartQueueProcessing()
+ waitVerdictAudit(t, manager.queue, id)
+ manager.Stop()
+ reopened := NewNotificationManagerWithDeferredQueue("", dir)
+ t.Cleanup(reopened.Stop)
+ var status, failureClass string
+ var attempts, success int
+ require.NoError(t, reopened.queue.db.QueryRow(`SELECT status, attempts FROM notification_queue WHERE id = ?`, id).Scan(&status, &attempts))
+ require.NoError(t, reopened.queue.db.QueryRow(`SELECT success, failure_class FROM notification_audit WHERE notification_id = ?`, id).Scan(&success, &failureClass))
+ stats, err := reopened.GetTelemetryStats(time.Now().Add(-time.Hour))
+ require.NoError(t, err)
+ require.Equal(t, 1, attempts)
+ require.Equal(t, 1, stats.Attempts)
+ if valid {
+ require.Equal(t, string(QueueStatusSent), status)
+ require.Equal(t, 1, success)
+ require.Empty(t, failureClass)
+ require.Equal(t, 1, stats.Deliveries)
+ require.Zero(t, stats.Failures)
+ require.Len(t, receipts, 1)
+ require.True(t, reopened.DeliveryHealth().Healthy)
+ } else {
+ require.Equal(t, string(QueueStatusDLQ), status)
+ require.Zero(t, success)
+ require.Equal(t, string(NotificationFailureAuthentication), failureClass)
+ require.Zero(t, stats.Deliveries)
+ require.Equal(t, 1, stats.Failures)
+ require.Equal(t, 1, stats.FailureClasses.Authentication)
+ require.Empty(t, receipts)
+ require.False(t, reopened.DeliveryHealth().Healthy)
+ }
+ })
+ }
+}
diff --git a/internal/notifications/email_enhanced.go b/internal/notifications/email_enhanced.go
index e398fb39d2..a21c466068 100644
--- a/internal/notifications/email_enhanced.go
+++ b/internal/notifications/email_enhanced.go
@@ -506,6 +506,14 @@ type RateLimiter struct {
// NewEnhancedEmailManager creates an enhanced email manager
func NewEnhancedEmailManager(config EmailProviderConfig) *EnhancedEmailManager {
+ config.EmailConfig = copyEmailConfig(config.EmailConfig)
+ if config.Provider == "" {
+ config.Provider = config.EmailConfig.Provider
+ }
+ // Provider defaults (for example SendGrid's "apikey") are credentials too.
+ // Delivery and connection tests must make the same authentication decision
+ // as validation and negotiateAuth, without rewriting the saved username.
+ config.AuthRequired = config.AuthRequired || (resolveProviderUsername(config) != "" && config.Password != "")
return &EnhancedEmailManager{
config: config,
rateLimit: &RateLimiter{
diff --git a/internal/notifications/email_legacy_coverage_test.go b/internal/notifications/email_legacy_coverage_test.go
index 8e9269a783..68ddf9880b 100644
--- a/internal/notifications/email_legacy_coverage_test.go
+++ b/internal/notifications/email_legacy_coverage_test.go
@@ -15,7 +15,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
)
-func stubSMTPDialSuccess(t *testing.T, deliveries *int32) {
+func stubSMTPDialSuccess(t *testing.T, deliveries *int32, observers ...func(isolatedSMTPReceipt)) {
t.Helper()
origDial := smtpDialTimeout
@@ -24,6 +24,7 @@ func stubSMTPDialSuccess(t *testing.T, deliveries *int32) {
go func() {
defer serverConn.Close()
+ var receipt isolatedSMTPReceipt
writer := bufio.NewWriter(serverConn)
reader := textproto.NewReader(bufio.NewReader(serverConn))
@@ -43,8 +44,10 @@ func stubSMTPDialSuccess(t *testing.T, deliveries *int32) {
case strings.HasPrefix(line, "AUTH"):
fmt.Fprint(writer, "235 2.7.0 Authentication successful\r\n")
case strings.HasPrefix(line, "MAIL FROM:"):
+ receipt = isolatedSMTPReceipt{from: strings.TrimPrefix(line, "MAIL ")}
fmt.Fprint(writer, "250 2.1.0 OK\r\n")
case strings.HasPrefix(line, "RCPT TO:"):
+ receipt.recipients = append(receipt.recipients, strings.TrimPrefix(line, "RCPT "))
fmt.Fprint(writer, "250 2.1.5 OK\r\n")
case strings.HasPrefix(line, "DATA"):
fmt.Fprint(writer, "354 End data with <CR><LF>.<CR><LF>\r\n")
@@ -62,6 +65,9 @@ func stubSMTPDialSuccess(t *testing.T, deliveries *int32) {
if deliveries != nil {
atomic.AddInt32(deliveries, 1)
}
+ for _, observe := range observers {
+ observe(receipt)
+ }
fmt.Fprint(writer, "250 2.0.0 queued\r\n")
case strings.HasPrefix(line, "QUIT"):
fmt.Fprint(writer, "221 2.0.0 Bye\r\n")
@@ -307,7 +313,8 @@ func TestNegotiateAuth_ServerMechanisms(t *testing.T) {
func TestSendGroupedEmail_UsesFromAsRecipient(t *testing.T) {
var deliveries int32
- stubSMTPDialSuccess(t, &deliveries)
+ receipts := make(chan isolatedSMTPReceipt, 1)
+ stubSMTPDialSuccess(t, &deliveries, func(receipt isolatedSMTPReceipt) { receipts <- receipt })
manager := NewEnhancedEmailManager(EmailProviderConfig{
EmailConfig: EmailConfig{
@@ -348,15 +355,16 @@ func TestSendGroupedEmail_UsesFromAsRecipient(t *testing.T) {
t.Fatalf("expected 1 delivered email, got %d", deliveries)
}
- expectedTo := []string{"[email protected]"}
- if !reflect.DeepEqual(manager.config.EmailConfig.To, expectedTo) {
- t.Fatalf("expected manager recipients %v, got %v", expectedTo, manager.config.EmailConfig.To)
+ expectedTo := []string{"TO:<[email protected]>"}
+ if got := awaitIsolatedSMTPReceipt(t, receipts); !reflect.DeepEqual(got.recipients, expectedTo) {
+ t.Fatalf("expected SMTP recipients %v, got %v", expectedTo, got.recipients)
}
}
func TestSendEmail_UsesSharedDeliveryExecutor(t *testing.T) {
var deliveries int32
- stubSMTPDialSuccess(t, &deliveries)
+ receipts := make(chan isolatedSMTPReceipt, 1)
+ stubSMTPDialSuccess(t, &deliveries, func(receipt isolatedSMTPReceipt) { receipts <- receipt })
manager := NewEnhancedEmailManager(EmailProviderConfig{
EmailConfig: EmailConfig{
@@ -391,10 +399,11 @@ func TestSendEmail_UsesSharedDeliveryExecutor(t *testing.T) {
t.Fatalf("expected shared sendEmail path to deliver 1 message, got %d", deliveries)
}
- if manager.config.EmailConfig.From != "[email protected]" {
- t.Fatalf("expected existing manager config to be updated, got %q", manager.config.EmailConfig.From)
+ receipt := awaitIsolatedSMTPReceipt(t, receipts)
+ if receipt.from != "FROM:<[email protected]>" {
+ t.Fatalf("expected submitted SMTP sender, got %q", receipt.from)
}
- if !reflect.DeepEqual(manager.config.EmailConfig.To, []string{"[email protected]"}) {
- t.Fatalf("expected existing manager recipients to be updated, got %v", manager.config.EmailConfig.To)
+ if !reflect.DeepEqual(receipt.recipients, []string{"TO:<[email protected]>"}) {
+ t.Fatalf("expected submitted SMTP recipients, got %v", receipt.recipients)
}
}
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index fab4422de5..023d70d05f 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -2672,30 +2672,21 @@ func (n *NotificationManager) emailDeliveryManager(config EmailConfig) (*Enhance
return newEmailDeliveryManager(config, recipients), recipients
}
- manager.config.EmailConfig = EmailConfig{
- Provider: config.Provider,
- From: config.From,
- To: recipients,
- SMTPHost: config.SMTPHost,
- SMTPPort: config.SMTPPort,
- Username: config.Username,
- Password: config.Password,
- TLS: config.TLS,
- StartTLS: config.StartTLS,
- RateLimit: config.RateLimit,
- }
- manager.config.Provider = config.Provider
- manager.config.StartTLS = config.StartTLS
- manager.config.RateLimit = effectiveEmailRateLimit(config.RateLimit)
- manager.config.AuthRequired = config.Username != "" && config.Password != ""
-
- if manager.rateLimit != nil {
- manager.rateLimit.mu.Lock()
- manager.rateLimit.rate = manager.config.RateLimit
- manager.rateLimit.mu.Unlock()
- }
-
- return manager, recipients
+ // Concurrent queue workers and reports may share an SMTP transport while
+ // carrying different admitted envelopes. Keep the cached manager immutable:
+ // otherwise preparing one delivery changes another delivery's recipients,
+ // sender and rate policy while it is being sent or waiting to retry.
+ deliveryConfig := manager.config
+ deliveryConfig.EmailConfig = copyEmailConfig(config)
+ deliveryConfig.To = append([]string(nil), recipients...)
+ deliveryConfig.Provider = config.Provider
+ deliveryConfig.StartTLS = config.StartTLS
+ deliveryConfig.RateLimit = effectiveEmailRateLimit(config.RateLimit)
+ deliveryConfig.AuthRequired = config.Username != "" && config.Password != ""
+ delivery := NewEnhancedEmailManager(deliveryConfig)
+ // Isolating envelopes must not give every delivery a fresh rate budget.
+ delivery.rateLimit = manager.rateLimit
+ return delivery, recipients
}
// sendHTMLEmailWithError sends an HTML email with multipart content and returns any error
diff --git a/internal/notifications/notifications_additional_test.go b/internal/notifications/notifications_additional_test.go
index db9ad5110e..97ae914cda 100644
--- a/internal/notifications/notifications_additional_test.go
+++ b/internal/notifications/notifications_additional_test.go
@@ -597,6 +597,8 @@ func TestSendResolvedWebhookNtfyValidationAndRateLimit(t *testing.T) {
}
func TestSendResolvedNotificationsDirectDispatchesEnabledTargets(t *testing.T) {
+ receipts := make(chan isolatedSMTPReceipt, 1)
+ stubSMTPDialSuccess(t, nil, func(receipt isolatedSMTPReceipt) { receipts <- receipt })
origSpawn := spawnAsync
spawnAsync = func(f func()) { f() }
t.Cleanup(func() { spawnAsync = origSpawn })
@@ -677,8 +679,9 @@ func TestSendResolvedNotificationsDirectDispatchesEnabledTargets(t *testing.T) {
if !appriseCalled {
t.Fatalf("expected resolved Apprise branch to be called")
}
- if manager.emailManager.config.EmailConfig.From != "[email protected]" {
- t.Fatalf("expected email manager config update from resolved-email send, got %q", manager.emailManager.config.EmailConfig.From)
+ receipt := awaitIsolatedSMTPReceipt(t, receipts)
+ if receipt.from != "FROM:<[email protected]>" || len(receipt.recipients) != 1 || receipt.recipients[0] != "TO:<[email protected]>" {
+ t.Fatalf("resolved email did not use its submitted SMTP envelope: %+v", receipt)
}
}
diff --git a/internal/notifications/notifications_test.go b/internal/notifications/notifications_test.go
index 5f6517959f..589b1e6199 100644
--- a/internal/notifications/notifications_test.go
+++ b/internal/notifications/notifications_test.go
@@ -3229,6 +3229,8 @@ func TestSendHTMLEmailWithError_NilEmailManager(t *testing.T) {
}
func TestSendHTMLEmailWithError_ExistingEmailManager(t *testing.T) {
+ receipts := make(chan isolatedSMTPReceipt, 1)
+ stubSMTPDialSuccess(t, nil, func(receipt isolatedSMTPReceipt) { receipts <- receipt })
// Create an email manager first
existingManager := NewEnhancedEmailManager(EmailProviderConfig{
EmailConfig: EmailConfig{
@@ -3250,16 +3252,19 @@ func TestSendHTMLEmailWithError_ExistingEmailManager(t *testing.T) {
SMTPPort: 25,
}
- // Will fail but exercises the "update existing manager config" path when the
- // passed config matches the persisted SMTP target.
+ // The submitted envelope shares the cached transport's rate budget without
+ // changing another delivery's configuration.
err := nm.sendHTMLEmailWithError("Test Subject", "<p>test</p>", "test", config)
- if err == nil {
- t.Error("expected error for invalid SMTP host")
+ if err != nil {
+ t.Fatalf("expected accepted SMTP message, got %v", err)
}
- // Verify the manager's From/To were updated on the shared delivery path.
- if existingManager.config.EmailConfig.From != "[email protected]" {
- t.Errorf("expected From to be updated to '[email protected]', got %q", existingManager.config.EmailConfig.From)
+ receipt := awaitIsolatedSMTPReceipt(t, receipts)
+ if receipt.from != "FROM:<[email protected]>" || len(receipt.recipients) != 1 || receipt.recipients[0] != "TO:<[email protected]>" {
+ t.Errorf("SMTP envelope did not use the submitted configuration: %+v", receipt)
+ }
+ if existingManager.config.EmailConfig.From != "[email protected]" {
+ t.Errorf("delivery changed the cached sender: %q", existingManager.config.EmailConfig.From)
}
}