Files
summercms/modules/postcard/mailer.go
Jakub Zych 3a725469c6 fix(postcard,cabana): unsafe site names never stop a send and are refused at save
- postcard.UnsafeText: a text a layout prints is unsafe when, escaped,
  it fails the rendered-HTML checks or holds a script or data URL at a
  scheme boundary ("Big Data: Summit" is safe)
- siteNameFrom/layoutSiteName: an unsafe Branding name falls back to the
  mail.from display name, an unsafe one of those gives no name; one
  rate-limited warning per source (site_name:branding, site_name:mail.from),
  never the value; file version, override, fallback and editor alike
- the Branding preview of an unsafe draft name renders without it
- MailBrandSetting.BeforeValidate: 422 on site_name with
  backend::lang.mail.brand.site_name_unsafe (en/pl)
- settings Put localizes a BeforeValidate refusal's phrase keys, as a
  controller save does
- TestMailSafetySmoke/unsafe_site_name, TestMailBrandSiteName/unsafe_name_refused
2026-11-14 15:20:29 +01:00

396 lines
12 KiB
Go

package postcard
import (
"context"
"fmt"
"log/slog"
netmail "net/mail"
"strings"
"sync"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/diary"
"git.golem15.com/golem15/summercms/modules/pact"
)
// moduleLog is postcard's logger: records carry component=postcard and follow
// log.components.postcard (diary).
var moduleLog = diary.For("postcard")
// Message is the Send contract for plugin callers.
type Message struct {
Template string
To []string
Cc []string
Bcc []string
ReplyTo string
Vars map[string]any
Subject string
}
// Mailer sends a registered template through the configured driver.
type Mailer interface {
Send(ctx context.Context, msg Message) error
}
// Options configure an app-scoped mailer.
type Options struct {
From string
CSS string
BrandCSS string
// Overrides, when set, is asked once per Send for the database
// overrides of the template being sent. Nil sends the file versions.
Overrides OverrideSource
}
type mailer struct {
catalog *Catalog
driver Driver
opts Options
// source supplies database overrides; nil means files only.
source OverrideSource
// log receives override warnings and failures; nil means moduleLog.
log *slog.Logger
warned warnGate
// inline inlines a message's CSS; nil means inlineCSS. Tests set it to
// force an inliner error.
inline func(html string) (string, error)
}
// NewMailer returns a mailer that renders from cat and delivers through
// driver. opts.Overrides, when set, supplies database overrides per send.
func NewMailer(cat *Catalog, driver Driver, opts Options) Mailer {
if cat == nil {
cat = NewCatalog()
}
return &mailer{catalog: cat, driver: driver, opts: opts, source: opts.Overrides}
}
// Send renders msg.Template and delivers it. It picks no locale: the caller
// passes the full dotted name, including any -en suffix. A <template>-<locale>
// name whose locale ships no file resolves to the default-locale version:
// that name's customized row when there is one, else the base template's
// customized row, else the base template's file. A database override of the
// template is applied when the mailer has an OverrideSource; an override
// that cannot be read or does not render is logged and the file version is
// sent instead.
func (m *mailer) Send(ctx context.Context, msg Message) error {
if m == nil {
return fmt.Errorf("postcard: mailer is nil")
}
if m.driver == nil {
return fmt.Errorf("postcard: driver is nil")
}
if msg.Template == "" {
return fmt.Errorf("postcard: template is empty")
}
if len(msg.To) == 0 && len(msg.Cc) == 0 && len(msg.Bcc) == 0 {
return fmt.Errorf("postcard: no recipients")
}
rendered, err := m.render(ctx, msg)
if err != nil {
return err
}
rendered.From = m.opts.From
_, smtp := m.driver.(*SMTPDriver)
if err := validateRendered(rendered, smtp); err != nil {
return err
}
if err := m.driver.Send(ctx, rendered); err != nil {
return fmt.Errorf("postcard: %w", err)
}
return nil
}
// render renders msg with its database overrides applied. With no source, no
// overrides, or overrides that fail to render or to pass the safety checks,
// it renders the file version.
func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, error) {
t, err := m.catalog.resolveTemplate(msg.Template)
if err != nil {
return RenderedMessage{}, err
}
ov := m.overrides(ctx, msg.Template)
if t.name != msg.Template && ov.Template == nil {
// A fallback-locale name with no customization of its own sends the
// base's. Layouts, partials and Branding are the same in both
// answers; only the template override is taken.
ov.Template = m.overrides(ctx, t.name).Template
}
// The file version carries the Branding too: it is not an override of a
// file, and a failing override must not change how the mail looks.
file := m.options(ov.Brand)
if ov.empty() {
return m.catalog.render(msg, file)
}
with := file
with.overrides = ov
with.warn = m.warn
rendered, err := m.catalog.render(msg, with)
if err == nil {
return rendered, nil
}
// The override is at fault only when the file version renders; a
// failure of both is the caller's (a bad subject, a missing variable)
// and is returned as before.
rendered, fileErr := m.catalog.render(msg, file)
if fileErr != nil {
return RenderedMessage{}, fileErr
}
m.logger().Error("postcard: override failed, sending the file version",
slog.String("template", msg.Template),
slog.String("error", err.Error()),
)
return rendered, nil
}
// options returns the render options of the file version: mail.css, and
// either the saved Branding (its compiled CSS and its logo) or, while none
// has been saved, mail.brandCss. A Branding whose colours do not compile
// keeps mail.brandCss. The site name is layoutSiteName's: the Branding's,
// else the display name of mail.from, leaving out a name that fails the
// safety check. The override render and the override-failure fallback are
// built from these options, so all of them carry the same checked name.
func (m *mailer) options(brand *Brand) renderOptions {
opts := renderOptions{
css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: m.layoutSiteName(brand), year: time.Now().Year(),
inline: m.inline, warn: m.warn,
}
if brand == nil {
return opts
}
opts.logoURL = brand.LogoURL
css, err := CompileBrandCSS(*brand)
if err != nil {
m.warn(err.Error(), "postcard: mail branding is not valid, using mail.brandCss",
slog.String("error", err.Error()))
return opts
}
opts.brandCSS = css
return opts
}
// siteName returns the name the built-in layouts show: the Branding's site
// name, trimmed, else the display name of the sender address from, else
// empty. A name UnsafeText refuses is skipped.
func siteName(brand *Brand, from string) string {
name, _ := siteNameFrom(brand, from)
return name
}
// siteNameFrom returns the first non-empty candidate UnsafeText accepts, of
// the trimmed Branding site name and the trimmed display name of from. In
// skipped it returns the source ("branding" or "mail.from") of the first
// non-empty candidate it refused.
func siteNameFrom(brand *Brand, from string) (name, skipped string) {
type candidate struct{ source, name string }
var candidates []candidate
if brand != nil {
candidates = append(candidates, candidate{"branding", strings.TrimSpace(brand.SiteName)})
}
if addr, err := netmail.ParseAddress(from); err == nil {
candidates = append(candidates, candidate{"mail.from", strings.TrimSpace(addr.Name)})
}
for _, c := range candidates {
if c.name == "" {
continue
}
if UnsafeText(c.name) {
if skipped == "" {
skipped = c.source
}
continue
}
return c.name, skipped
}
return "", skipped
}
// layoutSiteName is the site name the layouts get for brand and mail.from.
// A name that fails the safety check is left out, so it can never stop a
// send; a warning names its source, never its value, at most once per
// warnInterval.
func (m *mailer) layoutSiteName(brand *Brand) string {
name, skipped := siteNameFrom(brand, m.opts.From)
if skipped != "" {
m.warn("site_name:"+skipped, "postcard: site name left out of the layouts, it fails the mail safety check",
slog.String("source", skipped))
}
return name
}
// overrides asks the source once. A failed lookup (no connection, tables not
// migrated yet) is a warning, not a send failure: the file version is sent.
func (m *mailer) overrides(ctx context.Context, template string) Overrides {
if m.source == nil {
return Overrides{}
}
ov, err := m.source.MailOverrides(ctx, template)
if err != nil {
m.warn(err.Error(), "postcard: mail overrides unavailable, sending the file version",
slog.String("template", template),
slog.String("error", err.Error()),
)
return Overrides{}
}
for _, warning := range ov.warnings {
m.warn(warning, "postcard: "+warning, slog.String("template", template))
}
return ov
}
func (m *mailer) logger() *slog.Logger {
if m.log != nil {
return m.log
}
return moduleLog
}
// warn logs at warning level, at most once per warnInterval per key.
func (m *mailer) warn(key, msg string, args ...any) {
if !m.warned.allow(key, time.Now()) {
return
}
m.logger().Warn(msg, args...)
}
const (
// warnInterval is how often the same override warning is repeated.
warnInterval = time.Minute
// warnGateSize bounds the keys a warnGate remembers.
warnGateSize = 64
)
// warnGate rate-limits warnings by key. The zero value is ready to use.
type warnGate struct {
mu sync.Mutex
last map[string]time.Time
}
func (g *warnGate) allow(key string, now time.Time) bool {
g.mu.Lock()
defer g.mu.Unlock()
if last, ok := g.last[key]; ok && now.Sub(last) < warnInterval {
return false
}
if g.last == nil || len(g.last) >= warnGateSize {
g.last = make(map[string]time.Time)
}
g.last[key] = now
return true
}
// Activate publishes an app-scoped Mailer before plugin Boot. Catalog files
// are validated later at each plugin's Boot transition. The mailer reads
// database overrides through NewDBSource, so they apply in every process
// that publishes a *gorm.DB on app.
func Activate[P interface{ ID() string }](app *backpack.App, _ []P) error {
if app == nil {
return fmt.Errorf("postcard: app is nil")
}
driver, opts, err := driverFromApp(app)
if err != nil {
return err
}
opts.Overrides = NewDBSource(app)
m := &mailer{
catalog: NewCatalog(),
driver: driver,
opts: opts,
source: opts.Overrides,
}
if err := app.Publish[Mailer](m); err != nil {
return fmt.Errorf("postcard: %w", err)
}
return nil
}
func driverFromApp(app *backpack.App) (Driver, Options, error) {
opts := Options{}
name := "memory"
smtp := SMTPConfig{Port: 587, Timeout: 10 * time.Second}
if app != nil && app.Config != nil {
c := app.Config
if v := strings.TrimSpace(c.String("mail.driver")); v != "" {
name = strings.ToLower(v)
}
opts.From = strings.TrimSpace(c.String("mail.from"))
opts.CSS = c.String("mail.css")
opts.BrandCSS = c.String("mail.brandCss")
smtp = smtpFromConfig(c)
}
switch name {
case "memory":
return NewMemoryDriver(), opts, nil
case "log":
return NewLogDriver(loggerFromApp(app)), opts, nil
case "smtp":
d, err := NewSMTPDriver(smtp)
if err != nil {
return nil, opts, err
}
return d, opts, nil
default:
return nil, opts, fmt.Errorf("postcard: unknown mail.driver %q (use memory, log, or smtp)", name)
}
}
func smtpFromConfig(c *compass.Config) SMTPConfig {
cfg := SMTPConfig{
Host: strings.TrimSpace(c.String("mail.smtp.host")),
Port: c.Int("mail.smtp.port"),
Username: c.String("mail.smtp.username"),
Password: c.String("mail.smtp.password"),
TLS: strings.TrimSpace(c.String("mail.smtp.tls")),
Timeout: 10 * time.Second,
}
if raw := strings.TrimSpace(c.String("mail.smtp.timeout")); raw != "" {
if d, err := time.ParseDuration(raw); err == nil {
cfg.Timeout = d
} else if n := c.Int("mail.smtp.timeout"); n > 0 {
cfg.Timeout = time.Duration(n) * time.Second
}
}
return cfg
}
func loggerFromApp(app *backpack.App) *slog.Logger {
if app != nil {
if log, ok := app.Lookup[*slog.Logger](); ok && log != nil {
return log
}
}
return moduleLog
}
// BootPlugin registers a plugin's declared mail partials (pact.HasMailPartials)
// and its templates and layouts (pact.HasMailTemplates). Either capability is
// optional. Missing files, duplicates, names outside the plugin's namespace
// and unknown layout aliases fail with the dotted name.
func BootPlugin[P interface{ ID() string }](app *backpack.App, p P) error {
hm, hasTemplates := any(p).(pact.HasMailTemplates)
hp, hasPartials := any(p).(pact.HasMailPartials)
if !hasTemplates && !hasPartials {
return nil
}
got, ok := app.Lookup[Mailer]()
if !ok {
return fmt.Errorf("postcard: mailer not published")
}
m, ok := got.(*mailer)
if !ok || m == nil || m.catalog == nil {
return fmt.Errorf("postcard: mailer not published")
}
if hasPartials {
if err := m.catalog.RegisterPartials(p.ID(), hp.MailPartialsFS(), hp.MailPartials()); err != nil {
return err
}
}
if hasTemplates {
return m.catalog.Register(p.ID(), hm.MailTemplatesFS(), hm.MailTemplates(), hm.MailLayouts())
}
return nil
}