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
+135
View File
@@ -0,0 +1,135 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
)
type smtpConfigResp struct {
Enabled bool `json:"enabled"`
Host string `json:"host"`
Port int32 `json:"port"`
Username string `json:"username"`
Password string `json:"password"` // masked: "***" if non-empty, "" otherwise
FromAddress string `json:"from_address"`
FromName string `json:"from_name"`
UseTLS bool `json:"use_tls"`
}
type updateSMTPConfigReq struct {
Enabled bool `json:"enabled"`
Host string `json:"host"`
Port int32 `json:"port"`
Username string `json:"username"`
Password string `json:"password"` // empty string = preserve existing
FromAddress string `json:"from_address"`
FromName string `json:"from_name"`
UseTLS bool `json:"use_tls"`
}
func (h *handlers) handleGetSMTPConfig(w http.ResponseWriter, r *http.Request) {
q := dbq.New(h.pool)
cfg, err := q.GetSMTPConfig(r.Context())
if err != nil {
h.logger.Error("admin smtp: get failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
masked := ""
if cfg.Password != "" {
masked = "***"
}
writeJSON(w, http.StatusOK, smtpConfigResp{
Enabled: cfg.Enabled,
Host: cfg.Host,
Port: cfg.Port,
Username: cfg.Username,
Password: masked,
FromAddress: cfg.FromAddress,
FromName: cfg.FromName,
UseTLS: cfg.UseTls,
})
}
func (h *handlers) handleUpdateSMTPConfig(w http.ResponseWriter, r *http.Request) {
var req updateSMTPConfigReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, "invalid_body", "")
return
}
if req.Enabled {
if req.Host == "" || req.FromAddress == "" {
writeErr(w, http.StatusBadRequest, "missing_fields",
"host and from_address are required when enabled")
return
}
}
q := dbq.New(h.pool)
current, err := q.GetSMTPConfig(r.Context())
if err != nil {
h.logger.Error("admin smtp: get failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
// Preserve existing password when the request sends "" (so the
// admin doesn't have to re-enter it on every save).
password := req.Password
if password == "" {
password = current.Password
}
if err := q.UpdateSMTPConfig(r.Context(), dbq.UpdateSMTPConfigParams{
Enabled: req.Enabled,
Host: req.Host,
Port: req.Port,
Username: req.Username,
Password: password,
FromAddress: req.FromAddress,
FromName: req.FromName,
UseTls: req.UseTLS,
}); err != nil {
h.logger.Error("admin smtp: update failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *handlers) handleTestSMTPConfig(w http.ResponseWriter, r *http.Request) {
caller, ok := auth.UserFromContext(r.Context())
if !ok {
writeErr(w, http.StatusUnauthorized, "auth_required", "")
return
}
if caller.Email == nil || *caller.Email == "" {
writeErr(w, http.StatusBadRequest, "no_email_on_file",
"set your email in /settings before testing SMTP")
return
}
// Use a short-circuit context so the SMTP send doesn't hang the
// HTTP request indefinitely on a misconfigured host.
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
sender := mailer.NewSMTPSender(h.pool, h.logger)
textBody := "This is a test message from your Minstrel server.\n\nIf you got this, your SMTP config is working.\n\n— Minstrel"
htmlBody := "<p>This is a test message from your Minstrel server.</p><p>If you got this, your SMTP config is working.</p><p>— Minstrel</p>"
if err := sender.Send(ctx, *caller.Email, "Minstrel SMTP test", textBody, htmlBody); err != nil {
if errors.Is(err, mailer.ErrNotConfigured) {
writeErr(w, http.StatusBadRequest, "not_configured",
"SMTP is not enabled or required fields are empty")
return
}
h.logger.Error("admin smtp: test send failed", "err", err)
writeErr(w, http.StatusInternalServerError, "send_failed", err.Error())
return
}
w.WriteHeader(http.StatusNoContent)
}
+137
View File
@@ -0,0 +1,137 @@
package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/go-chi/chi/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
)
func newAdminSMTPRouter(h *handlers) chi.Router {
r := chi.NewRouter()
r.Route("/api/admin", func(admin chi.Router) {
admin.Use(auth.RequireAdmin())
admin.Get("/smtp-config", h.handleGetSMTPConfig)
admin.Put("/smtp-config", h.handleUpdateSMTPConfig)
admin.Post("/smtp-config/test", h.handleTestSMTPConfig)
})
return r
}
func TestSMTPConfig_GetMasksPassword(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
admin := seedUser(t, pool, "smtpadmin", "pw", true)
// Seed a non-empty password.
if _, err := pool.Exec(context.Background(),
"UPDATE smtp_config SET password = 'secret' WHERE id = true"); err != nil {
t.Fatalf("seed: %v", err)
}
req := httptest.NewRequest(http.MethodGet, "/api/admin/smtp-config", nil)
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminSMTPRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
var resp smtpConfigResp
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp.Password != "***" {
t.Errorf("password = %q, want \"***\"", resp.Password)
}
}
func TestSMTPConfig_UpdatePreservesPasswordWhenEmpty(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
admin := seedUser(t, pool, "smtpupd", "pw", true)
// Seed a known password.
if _, err := pool.Exec(context.Background(),
"UPDATE smtp_config SET password = 'original' WHERE id = true"); err != nil {
t.Fatalf("seed: %v", err)
}
body := `{
"enabled": true,
"host": "smtp.example.com",
"port": 587,
"username": "u",
"password": "",
"from_address": "from@example.com",
"from_name": "T",
"use_tls": true
}`
req := httptest.NewRequest(http.MethodPut, "/api/admin/smtp-config",
bytes.NewReader([]byte(body)))
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminSMTPRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String())
}
// Password preserved?
var pass string
if err := pool.QueryRow(context.Background(),
"SELECT password FROM smtp_config WHERE id = true").Scan(&pass); err != nil {
t.Fatalf("verify: %v", err)
}
if pass != "original" {
t.Errorf("password = %q, want \"original\" (preserved when empty in request)", pass)
}
}
func TestSMTPConfig_UpdateValidatesEnabled(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
admin := seedUser(t, pool, "smtpvalid", "pw", true)
body := `{"enabled": true, "host": "", "from_address": "", "port": 587, "use_tls": true}`
req := httptest.NewRequest(http.MethodPut, "/api/admin/smtp-config",
bytes.NewReader([]byte(body)))
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminSMTPRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400 (missing host + from_address with enabled=true)", rec.Code)
}
}
func TestSMTPConfig_TestRequiresEmail(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
// Admin without email on file.
admin := seedUser(t, pool, "noemail", "pw", true)
req := httptest.NewRequest(http.MethodPost, "/api/admin/smtp-config/test", nil)
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminSMTPRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400 (no email on file)", rec.Code)
}
}
+4
View File
@@ -140,6 +140,10 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
admin.Patch("/cover-sources/{provider_id}", h.handleUpdateCoverSource)
admin.Post("/cover-sources/{provider_id}/test", h.handleTestCoverSource)
admin.Post("/cover-sources/research", h.handleResearchMissingArt)
admin.Get("/smtp-config", h.handleGetSMTPConfig)
admin.Put("/smtp-config", h.handleUpdateSMTPConfig)
admin.Post("/smtp-config/test", h.handleTestSMTPConfig)
})
authed.Get("/playlists", h.handleListPlaylists)