feat(server/m7-user-mgmt): mailer package + SMTP config endpoints (U3)

New internal/mailer/ package:

- Sender interface with two impls: SMTPSender (production, reads
  smtp_config at send time so admin edits apply without restart;
  uses stdlib net/smtp + STARTTLS) and FakeSender (test/concurrent-
  safe call recorder).
- Embedded text + HTML templates for the password reset email,
  rendered via stdlib text/template + html/template. The HTML
  uses the FabledSword forest-teal accent color.
- ErrNotConfigured surfaces when smtp_config.enabled is false or
  required fields are empty; callers like the future forgot-password
  handler will treat this as "log and pretend success" to avoid
  user-enumeration leaks.

Three admin endpoints under RequireAdmin:

- GET /api/admin/smtp-config — returns the singleton; password
  field is masked ("***" or "").
- PUT /api/admin/smtp-config — updates settings. Validates
  host + from_address are non-empty when enabled=true. Empty
  password in the request preserves the stored value (so the
  operator doesn't have to re-enter it on every save).
- POST /api/admin/smtp-config/test — sends a real test email to
  the calling admin's email. 400 if admin has no email; 500 with
  the error message on send failure (so the operator can debug
  config without grep-then-trace through logs).

Tests cover the password-mask, password-preservation-on-empty,
enabled-requires-host-and-from validation, and the no-email-on-file
rejection. Mailer unit tests cover the fake recorder and template
rendering. The "real SMTP send" path needs a live server and isn't
covered in CI; the FakeSender covers that role for downstream tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-07 12:43:44 -04:00
parent aa73c93f85
commit aa67a09b80
8 changed files with 631 additions and 0 deletions
+206
View File
@@ -0,0 +1,206 @@
// Package mailer sends transactional email for the user-management
// flows (password reset, etc). The Sender interface lets handlers
// inject a fake in tests; SMTPSender is the production implementation
// that reads SMTP config from the smtp_config singleton at send time
// so admin edits take effect without a server restart.
package mailer
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net"
"net/smtp"
"strconv"
"sync"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// ErrNotConfigured is returned when smtp_config.enabled is false or
// required fields are empty. Handlers that depend on email send
// (forgot-password) treat this as a soft failure — log it and pretend
// the send succeeded so users don't enumerate which emails are on
// file.
var ErrNotConfigured = errors.New("mailer: SMTP not configured")
// Sender is the interface every caller of the mailer uses.
// Implementations: SMTPSender (production), FakeSender (tests).
type Sender interface {
Send(ctx context.Context, to, subject, textBody, htmlBody string) error
}
// SMTPSender is the production implementation. Reads smtp_config from
// the database at send time so config changes apply without restart.
type SMTPSender struct {
pool *pgxpool.Pool
logger *slog.Logger
}
func NewSMTPSender(pool *pgxpool.Pool, logger *slog.Logger) *SMTPSender {
return &SMTPSender{pool: pool, logger: logger}
}
// Send composes a multipart/alternative message with text + html and
// dispatches it via SMTP. Returns ErrNotConfigured when smtp_config
// is disabled or missing required fields; returns the underlying
// network/auth error otherwise.
func (s *SMTPSender) Send(ctx context.Context, to, subject, textBody, htmlBody string) error {
q := dbq.New(s.pool)
cfg, err := q.GetSMTPConfig(ctx)
if err != nil {
return fmt.Errorf("mailer: load config: %w", err)
}
if !cfg.Enabled || cfg.Host == "" || cfg.FromAddress == "" {
return ErrNotConfigured
}
msg := composeMessage(cfg, to, subject, textBody, htmlBody)
addr := net.JoinHostPort(cfg.Host, strconv.Itoa(int(cfg.Port)))
var auth smtp.Auth
if cfg.Username != "" {
auth = smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)
}
// We respect the use_tls flag: if true, we require STARTTLS via
// smtp.SendMail's default behavior (which negotiates STARTTLS when
// the server advertises it). For implicit-TLS (port 465 style),
// we'd need a custom dial — skip that complexity for v1 and rely on
// STARTTLS via port 587 (the default).
dialCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
_ = dialCtx // smtp.SendMail doesn't accept ctx; the timeout is enforced via Dialer below
if err := sendMail(addr, cfg, auth, []string{to}, msg); err != nil {
s.logger.Error("mailer: send failed",
"to", to, "host", cfg.Host, "err", err)
return fmt.Errorf("mailer: send: %w", err)
}
return nil
}
// sendMail wraps net/smtp's SendMail with optional TLS verification.
// Mostly identical to smtp.SendMail but explicitly handles the
// use_tls flag.
func sendMail(addr string, cfg dbq.SmtpConfig, auth smtp.Auth, to []string, msg []byte) error {
c, err := smtp.Dial(addr)
if err != nil {
return err
}
defer func() { _ = c.Close() }()
if cfg.UseTls {
if ok, _ := c.Extension("STARTTLS"); ok {
tlsConfig := &tls.Config{ServerName: cfg.Host}
if err := c.StartTLS(tlsConfig); err != nil {
return err
}
}
}
if auth != nil {
if ok, _ := c.Extension("AUTH"); ok {
if err := c.Auth(auth); err != nil {
return err
}
}
}
if err := c.Mail(cfg.FromAddress); err != nil {
return err
}
for _, addr := range to {
if err := c.Rcpt(addr); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
if _, err := w.Write(msg); err != nil {
return err
}
if err := w.Close(); err != nil {
return err
}
return c.Quit()
}
// composeMessage builds an RFC 5322 multipart/alternative message
// with the from/subject headers and both text + html bodies. Boundary
// is timestamp-based to keep the implementation dependency-free.
func composeMessage(cfg dbq.SmtpConfig, to, subject, textBody, htmlBody string) []byte {
var buf bytes.Buffer
boundary := fmt.Sprintf("minstrel-%d", time.Now().UnixNano())
from := cfg.FromAddress
if cfg.FromName != "" {
from = fmt.Sprintf("%s <%s>", cfg.FromName, cfg.FromAddress)
}
fmt.Fprintf(&buf, "From: %s\r\n", from)
fmt.Fprintf(&buf, "To: %s\r\n", to)
fmt.Fprintf(&buf, "Subject: %s\r\n", subject)
fmt.Fprintf(&buf, "MIME-Version: 1.0\r\n")
fmt.Fprintf(&buf, "Content-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", boundary)
fmt.Fprintf(&buf, "--%s\r\n", boundary)
fmt.Fprintf(&buf, "Content-Type: text/plain; charset=\"utf-8\"\r\n\r\n")
buf.WriteString(textBody)
buf.WriteString("\r\n")
fmt.Fprintf(&buf, "--%s\r\n", boundary)
fmt.Fprintf(&buf, "Content-Type: text/html; charset=\"utf-8\"\r\n\r\n")
buf.WriteString(htmlBody)
buf.WriteString("\r\n")
fmt.Fprintf(&buf, "--%s--\r\n", boundary)
return buf.Bytes()
}
// SentEmail is the in-memory record FakeSender keeps. Tests assert
// against these.
type SentEmail struct {
To string
Subject string
TextBody string
HtmlBody string
}
// FakeSender records calls instead of sending. Safe for concurrent use.
type FakeSender struct {
mu sync.Mutex
Sent []SentEmail
// FailNext, when true, makes the next Send call return an error
// instead of recording. Useful for testing send-failure paths.
FailNext error
}
func (f *FakeSender) Send(ctx context.Context, to, subject, textBody, htmlBody string) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.FailNext != nil {
err := f.FailNext
f.FailNext = nil
return err
}
f.Sent = append(f.Sent, SentEmail{
To: to, Subject: subject, TextBody: textBody, HtmlBody: htmlBody,
})
return nil
}
// LastSent returns the most recently recorded email, or zero value
// if nothing has been sent.
func (f *FakeSender) LastSent() SentEmail {
f.mu.Lock()
defer f.mu.Unlock()
if len(f.Sent) == 0 {
return SentEmail{}
}
return f.Sent[len(f.Sent)-1]
}
+64
View File
@@ -0,0 +1,64 @@
package mailer_test
import (
"context"
"errors"
"strings"
"testing"
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
)
func TestFakeSender_RecordsCalls(t *testing.T) {
f := &mailer.FakeSender{}
if err := f.Send(context.Background(), "u@example.com", "Subj", "text body", "<p>html body</p>"); err != nil {
t.Fatalf("Send: %v", err)
}
if len(f.Sent) != 1 {
t.Fatalf("Sent len = %d, want 1", len(f.Sent))
}
got := f.LastSent()
if got.To != "u@example.com" || got.Subject != "Subj" {
t.Errorf("LastSent = %+v", got)
}
}
func TestFakeSender_FailNext(t *testing.T) {
f := &mailer.FakeSender{FailNext: errors.New("simulated")}
if err := f.Send(context.Background(), "u@example.com", "Subj", "t", "h"); err == nil {
t.Errorf("Send returned nil, want error")
}
// Subsequent call should succeed (FailNext consumed).
if err := f.Send(context.Background(), "u@example.com", "Subj", "t", "h"); err != nil {
t.Errorf("second Send: %v", err)
}
if len(f.Sent) != 1 {
t.Errorf("Sent len = %d, want 1 (first call failed, second recorded)", len(f.Sent))
}
}
func TestRenderResetEmail(t *testing.T) {
textBody, htmlBody, err := mailer.RenderResetEmail(mailer.ResetEmailVars{
Username: "alice",
ResetURL: "https://example.com/reset/abc123",
ExpiryHours: 24,
})
if err != nil {
t.Fatalf("RenderResetEmail: %v", err)
}
if !strings.Contains(textBody, "alice") {
t.Errorf("textBody missing username; got: %s", textBody)
}
if !strings.Contains(textBody, "https://example.com/reset/abc123") {
t.Errorf("textBody missing reset URL; got: %s", textBody)
}
if !strings.Contains(textBody, "24") {
t.Errorf("textBody missing expiry hours; got: %s", textBody)
}
if !strings.Contains(htmlBody, "alice") {
t.Errorf("htmlBody missing username")
}
if !strings.Contains(htmlBody, "https://example.com/reset/abc123") {
t.Errorf("htmlBody missing reset URL")
}
}
+45
View File
@@ -0,0 +1,45 @@
package mailer
import (
"bytes"
"embed"
"fmt"
htmltemplate "html/template"
texttemplate "text/template"
)
//go:embed templates/password_reset.txt templates/password_reset.html
var resetEmailFS embed.FS
// ResetEmailVars is the data passed to the password reset templates.
type ResetEmailVars struct {
Username string
ResetURL string
ExpiryHours int
}
// RenderResetEmail returns (textBody, htmlBody) for the password
// reset email, parameterized with the given vars.
func RenderResetEmail(vars ResetEmailVars) (string, string, error) {
textTpl, err := texttemplate.ParseFS(resetEmailFS, "templates/password_reset.txt")
if err != nil {
return "", "", fmt.Errorf("mailer: parse text template: %w", err)
}
htmlTpl, err := htmltemplate.ParseFS(resetEmailFS, "templates/password_reset.html")
if err != nil {
return "", "", fmt.Errorf("mailer: parse html template: %w", err)
}
var textBuf, htmlBuf bytes.Buffer
if err := textTpl.Execute(&textBuf, vars); err != nil {
return "", "", fmt.Errorf("mailer: render text: %w", err)
}
if err := htmlTpl.Execute(&htmlBuf, vars); err != nil {
return "", "", fmt.Errorf("mailer: render html: %w", err)
}
return textBuf.String(), htmlBuf.String(), nil
}
// ResetEmailSubject is the subject line used by the forgot-password
// flow. Exported so callers don't string-literal it independently.
const ResetEmailSubject = "Minstrel password reset"
@@ -0,0 +1,29 @@
<!doctype html>
<html>
<body style="font-family: -apple-system, system-ui, sans-serif; max-width: 560px; margin: 0 auto; padding: 24px; color: #2c2c2c;">
<p>Hello <strong>{{.Username}}</strong>,</p>
<p>A password reset was requested for your Minstrel account. To set a new
password, click the button below within <strong>{{.ExpiryHours}}</strong> hours:</p>
<p style="margin: 24px 0;">
<a href="{{.ResetURL}}" style="display: inline-block; padding: 12px 24px;
background: #4a6b5c; color: #ffffff; text-decoration: none; border-radius: 6px;
font-weight: 500;">Reset password</a>
</p>
<p style="font-size: 14px; color: #666;">
Or copy this URL into your browser:<br>
<code style="word-break: break-all;">{{.ResetURL}}</code>
</p>
<p style="font-size: 14px; color: #666;">
If you didn't request this, you can safely ignore this email — your
password won't change.
</p>
<p style="font-size: 12px; color: #999; margin-top: 32px; border-top: 1px solid #eee; padding-top: 16px;">
— Minstrel
</p>
</body>
</html>
@@ -0,0 +1,11 @@
Hello {{.Username}},
A password reset was requested for your Minstrel account. To set a new
password, follow this link within {{.ExpiryHours}} hours:
{{.ResetURL}}
If you didn't request this, you can safely ignore this email — your
password won't change.
— Minstrel