Merge pull request #508 from thejesh23/fix/email-date-message-id

fix(notify): add Date and Message-ID headers to notification emails
This commit is contained in:
BaaRai
2026-11-23 23:38:38 +01:00
committed by GitHub
3 changed files with 177 additions and 2 deletions
+62 -2
View File
@@ -2,12 +2,14 @@ package notify
import (
"context"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"mime"
"net"
"net/mail"
"net/smtp"
"strconv"
"strings"
@@ -57,6 +59,14 @@ func (emailChannel) Validate(cfg map[string]any) error {
if len(cfgStrings(cfg, "to")) == 0 {
return errors.New("at least one recipient address is required")
}
for _, rcpt := range cfgStrings(cfg, "to") {
if hasLineBreak(rcpt) {
return errors.New("recipient address must not contain line breaks")
}
}
if _, err := senderAddress(cfgString(cfg, "from")); err != nil {
return err
}
return nil
}
@@ -72,6 +82,10 @@ func (c emailChannel) Send(ctx context.Context, cfg map[string]any, m Message) (
password := cfgString(cfg, "password")
implicitTLS := cfgBool(cfg, "tls")
sender, err := senderAddress(from)
if err != nil {
return 0, Permanent(err)
}
msg, err := buildEmailMessage(from, to, m)
if err != nil {
return 0, Permanent(err)
@@ -106,8 +120,9 @@ func (c emailChannel) Send(ctx context.Context, cfg map[string]any, m Message) (
return 0, Permanent(fmt.Errorf("SMTP authentication failed: %w", err))
}
}
if err := client.Mail(from); err != nil {
return 0, smtpStageError(fmt.Sprintf("sender %s rejected", from), err)
// The envelope sender is the bare address; the display name stays in the header.
if err := client.Mail(sender.Address); err != nil {
return 0, smtpStageError(fmt.Sprintf("sender %s rejected", sender.Address), err)
}
for _, rcpt := range to {
if err := client.Rcpt(rcpt); err != nil {
@@ -217,9 +232,22 @@ func smtpReplyCode(text string) int {
// over-long lines; second, base64 never produces a line starting with ".",
// avoiding SMTP dot-stuffing entirely.
func buildEmailMessage(from string, to []string, m Message) (string, error) {
// From and To go into header lines: a CR or LF would start a new header.
if hasLineBreak(from) {
return "", errors.New("sender address must not contain line breaks")
}
for _, rcpt := range to {
if hasLineBreak(rcpt) {
return "", errors.New("recipient address must not contain line breaks")
}
}
var b strings.Builder
fmt.Fprintf(&b, "From: %s\r\n", from)
fmt.Fprintf(&b, "To: %s\r\n", strings.Join(to, ", "))
// RFC 5322 requires Date and recommends Message-ID. Not every submission
// server adds them, and spam filters penalize mail without them.
fmt.Fprintf(&b, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
fmt.Fprintf(&b, "Message-ID: <%s@%s>\r\n", rand.Text(), messageIDDomain(from))
// A non-ASCII subject must be RFC 2047 encoded, otherwise clients display it
// as mojibake.
fmt.Fprintf(&b, "Subject: %s\r\n", mime.QEncoding.Encode("utf-8", htmlTitle(m)))
@@ -237,3 +265,35 @@ func buildEmailMessage(from string, to []string, m Message) (string, error) {
b.WriteString(encoded + "\r\n")
return b.String(), nil
}
// senderAddress parses the configured sender with net/mail, so a display name and
// comments are accepted and the bare address is what gets used. A line break is
// refused before parsing: the value lands in header lines.
func senderAddress(from string) (*mail.Address, error) {
if hasLineBreak(from) {
return nil, errors.New("sender address must not contain line breaks")
}
addr, err := mail.ParseAddress(from)
if err != nil {
return nil, fmt.Errorf("invalid sender address: %w", err)
}
return addr, nil
}
// hasLineBreak reports whether s contains CR or LF.
func hasLineBreak(s string) bool {
return strings.ContainsAny(s, "\r\n")
}
// messageIDDomain is the right-hand side of a Message-ID: the domain of the parsed
// sender address, or "localhost" when there is none (or the sender does not parse).
func messageIDDomain(from string) string {
addr, err := senderAddress(from)
if err != nil {
return "localhost"
}
if i := strings.LastIndex(addr.Address, "@"); i >= 0 && i+1 < len(addr.Address) {
return addr.Address[i+1:]
}
return "localhost"
}
+81
View File
@@ -0,0 +1,81 @@
package notify
import (
"strings"
"testing"
)
func TestMessageIDDomainFromCommentedAddress(t *testing.T) {
if got := messageIDDomain("Name <a@example.com> (comment)"); got != "example.com" {
t.Fatalf("domain = %q, want example.com", got)
}
if got := messageIDDomain("ops@example.org"); got != "example.org" {
t.Fatalf("domain = %q, want example.org", got)
}
}
func TestMessageIDDomainFallsBackToLocalhost(t *testing.T) {
for _, from := range []string{"no-at-sign", "a@", "Name <a@>", ""} {
if got := messageIDDomain(from); got != "localhost" {
t.Fatalf("messageIDDomain(%q) = %q, want localhost", from, got)
}
}
}
func TestBuildEmailMessageRefusesLineBreaksInHeaders(t *testing.T) {
cases := []struct {
name string
from string
to []string
}{
{"CRLF in sender", "a@example.com\r\nBcc: victim@example.net", []string{"b@example.org"}},
{"LF in sender", "a@example.com\nBcc: victim@example.net", []string{"b@example.org"}},
{"CRLF in recipient", "a@example.com", []string{"b@example.org\r\nBcc: victim@example.net"}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
msg, err := buildEmailMessage(c.from, c.to, Message{})
if err == nil {
t.Fatalf("expected an error, got message:\n%s", msg)
}
if strings.Contains(msg, "Bcc:") {
t.Fatal("no header may be produced from an injected value")
}
})
}
}
func TestSenderAddressValidation(t *testing.T) {
if _, err := senderAddress("a@example.com\r\nX: y"); err == nil {
t.Fatal("CRLF sender must be refused")
}
if _, err := senderAddress("not an address"); err == nil {
t.Fatal("unparseable sender must be refused")
}
addr, err := senderAddress("Name <a@example.com> (comment)")
if err != nil {
t.Fatalf("commented sender refused: %v", err)
}
if addr.Address != "a@example.com" {
t.Fatalf("envelope address = %q, want a@example.com", addr.Address)
}
}
func TestEmailValidateRejectsBadSenderAndRecipients(t *testing.T) {
base := map[string]any{"host": "smtp.example.com", "port": 587, "to": []any{"b@example.org"}}
ok := map[string]any{"host": "smtp.example.com", "port": 587, "from": "a@example.com", "to": []any{"b@example.org"}}
if err := (emailChannel{}).Validate(ok); err != nil {
t.Fatalf("valid config refused: %v", err)
}
if err := (emailChannel{}).Validate(base); err == nil {
t.Fatal("empty sender must be refused")
}
bad := map[string]any{"host": "smtp.example.com", "port": 587, "from": "not an address", "to": []any{"b@example.org"}}
if err := (emailChannel{}).Validate(bad); err == nil {
t.Fatal("invalid sender must be refused")
}
crlf := map[string]any{"host": "smtp.example.com", "port": 587, "from": "a@example.com", "to": []any{"b@example.org\r\nX: y"}}
if err := (emailChannel{}).Validate(crlf); err == nil {
t.Fatal("CRLF recipient must be refused")
}
}
+34
View File
@@ -5,9 +5,11 @@ import (
"context"
"net"
"net/mail"
"strings"
"sync"
"testing"
"time"
)
// This file adds the protocol-level tests for the email channel. Before it,
@@ -187,6 +189,38 @@ func TestEmailSendDeliversFullMessage(t *testing.T) {
}
}
// RFC 5322 section 3.6 requires a Date header, and every message should carry
// a Message-ID. Not every submission server adds them, and spam filters
// penalize mail without them.
func TestEmailMessageHasDateAndMessageID(t *testing.T) {
ids := map[string]bool{}
for range 2 {
raw, err := buildEmailMessage("artex@example.com", []string{"a@example.com"}, singleMsg())
if err != nil {
t.Fatal(err)
}
msg, err := mail.ReadMessage(strings.NewReader(raw))
if err != nil {
t.Fatalf("message does not parse: %v\n%s", err, raw)
}
date, err := msg.Header.Date()
if err != nil {
t.Fatalf("missing or invalid Date header: %v\n%s", err, raw)
}
if d := time.Since(date); d < -time.Minute || d > time.Minute {
t.Errorf("Date %v is not the send time", date)
}
id := msg.Header.Get("Message-ID")
if !strings.HasPrefix(id, "<") || !strings.HasSuffix(id, "@example.com>") {
t.Errorf("Message-ID %q, want <...@example.com>", id)
}
ids[id] = true
}
if len(ids) != 2 {
t.Errorf("two messages share a Message-ID: %v", ids)
}
}
func TestEmailSendWithoutAuth(t *testing.T) {
// AUTH must not be sent when no account is configured — some relays reject
// because of it.