fix(router): RFC 2047 encode a non-ASCII List-Id phrase

- headers: the title in List-Id goes through mime.QEncoding, the <id> part stays ASCII
- test: UTF-8 and 200-character titles read back through net/mail and the word decoder
This commit is contained in:
tgiachi 2026-11-10 11:51:05 +01:00
commit 087bc92d41
2 changed files with 52 additions and 1 deletions

View file

@ -5,6 +5,7 @@ import (
"bytes"
"fmt"
"io"
"mime"
"net/mail"
"github.com/emersion/go-message/textproto"
@ -27,7 +28,8 @@ func rewrite(l store.List, data []byte) ([]byte, error) {
}
id := l.Name + "." + l.Domain
h.Set("List-Id", fmt.Sprintf("%s <%s>", l.Title, id))
// The phrase is RFC 2047 encoded when it is not ASCII; the <id> stays plain ASCII (list names and domains are).
h.Set("List-Id", fmt.Sprintf("%s <%s>", mime.QEncoding.Encode("utf-8", l.Title), id))
h.Set("List-Post", "<mailto:"+l.Address()+">")
// List-Unsubscribe is per recipient: Router.Send adds it.
h.Set("Precedence", "list")

View file

@ -3,6 +3,7 @@ package router
import (
"bytes"
"errors"
"mime"
"net/mail"
"strings"
"testing"
@ -107,3 +108,51 @@ func TestRewriteKeepsExistingReplyTo(t *testing.T) {
t.Errorf("Reply-To = %q", got)
}
}
func TestListIdWithANonASCIITitleIsEncoded(t *testing.T) {
l := store.List{Name: "dev", Domain: "example.org", Title: "Développeurs ☕ \"café\""}
out, err := rewrite(l, []byte(sample))
if err != nil {
t.Fatal(err)
}
for _, line := range strings.Split(string(out), "\r\n") {
if strings.HasPrefix(line, "List-Id:") {
for _, b := range []byte(line) {
if b >= 0x80 {
t.Fatalf("raw non-ASCII in %q", line)
}
}
}
}
m, err := mail.ReadMessage(bytes.NewReader(out))
if err != nil {
t.Fatal(err)
}
raw := m.Header.Get("List-Id")
if !strings.HasSuffix(raw, " <dev.example.org>") {
t.Fatalf("the id must stay a plain <id>: %q", raw)
}
phrase, err := new(mime.WordDecoder).DecodeHeader(strings.TrimSuffix(raw, " <dev.example.org>"))
if err != nil || phrase != l.Title {
t.Fatalf("phrase = %q (%v), want %q", phrase, err, l.Title)
}
// A long title is folded into several encoded words and still reads back.
long := store.List{Name: "dev", Domain: "example.org", Title: strings.Repeat("è", 200)}
out, err = rewrite(long, []byte(sample))
if err != nil {
t.Fatal(err)
}
m, err = mail.ReadMessage(bytes.NewReader(out))
if err != nil {
t.Fatal(err)
}
raw = m.Header.Get("List-Id")
if phrase, err := new(mime.WordDecoder).DecodeHeader(strings.TrimSuffix(raw, " <dev.example.org>")); err != nil || phrase != long.Title {
t.Fatalf("long phrase = %q (%v)", phrase, err)
}
// An ASCII title is left as it is.
out, _ = rewrite(store.List{Name: "dev", Domain: "example.org", Title: "Dev"}, []byte(sample))
if !strings.Contains(string(out), "List-Id: Dev <dev.example.org>\r\n") {
t.Fatalf("ascii title changed: %q", out)
}
}