Files
summercms/modules/cabana/mail_screens_smoke_test.go
Jakub Zych d320733510 feat(postcard): inline mail CSS at render with a per-layout opt-out
- github.com/vanng822/go-premailer v1.38.0 (default options) inlines the
  rendered HTML after the safety checks; the result is checked again,
  HTML without a style element is left as it is, an inliner error sends
  the style block only and warns (key inline:<layout>)
- opt-out: layout header key disable_auto_inline_css, the layouts column
  of the same name (migration 202611130003), LayoutFile/LayoutOverride/
  Draft.DisableAutoInlineCSS; SyncIndex mirrors and ResetOverride restores
  the file's value
- cabana layout form switch on the CSS tab, mapped into the layout draft
  and the save validation; en/pl copy
- tests: TestMailPartialsSmoke/inline, TestMailEditorSmoke/inline_flag,
  the layouts switch in TestMailScreensSmoke; CSS-slot tests read the
  style block through a no-op inliner
- 35-06 Task 2 (G-35-8)
2026-11-13 21:12:01 +01:00

1225 lines
51 KiB
Go

package cabana_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"sync/atomic"
"testing"
"testing/fstest"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/party"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"git.golem15.com/golem15/summercms/modules/postcard"
"git.golem15.com/golem15/summercms/modules/surf"
"gocloud.dev/blob/memblob"
"gorm.io/gorm"
)
// The mail screens' paths under the admin API.
const (
mailTemplatesPath = "/summercms/cabana/mailtemplates"
mailLayoutsPath = "/summercms/cabana/maillayouts"
mailPartialsPath = "/summercms/cabana/mailpartials"
)
// The fixture plugin's mail.
const (
blogWelcome = "acme.blog::mail.welcome"
blogWelcomeEn = "acme.blog::mail.welcome-en"
blogLayout = "acme.blog::mail.layouts.blog"
blogCard = "acme.blog::mail.partials.card"
)
// mailBlogPlugin ships two templates (a base and its -en variant), one
// layout aliased blog and one partial. files is mutable so a test can change
// a file and sync again.
type mailBlogPlugin struct{ files fstest.MapFS }
func (mailBlogPlugin) ID() string { return "acme.blog" }
func (mailBlogPlugin) Requires() []string { return nil }
func (mailBlogPlugin) Register(*backpack.App) error { return nil }
func (mailBlogPlugin) Boot(*backpack.App) error { return nil }
func (p mailBlogPlugin) MailTemplatesFS() fs.FS { return p.files }
func (mailBlogPlugin) MailTemplates() []string { return []string{blogWelcome, blogWelcomeEn} }
func (mailBlogPlugin) MailLayouts() map[string]string {
return map[string]string{"blog": blogLayout}
}
func (p mailBlogPlugin) MailPartialsFS() fs.FS { return p.files }
func (mailBlogPlugin) MailPartials() []string { return []string{blogCard} }
func mailBlogFiles() fstest.MapFS {
return fstest.MapFS{
"views/mail/welcome.htm": {Data: []byte(`subject = "Witaj, {{ .name }}"
description = "Sent after registration"
layout = "blog"
sample.name = "Ada"
==
Cześć **{{ .name }}**, dzięki za rejestrację.
`)},
"views/mail/welcome-en.htm": {Data: []byte(`subject = "Welcome, {{ .name }}"
description = "Sent after registration (English)"
layout = "blog"
sample.name = "Ada"
==
Hi **{{ .name }}**, thanks for joining.
`)},
"views/mail/layouts/blog.htm": {Data: []byte(`name = "Blog"
==
{{ .Content }}
-- The Acme blog
==
<div class="blog-mail">{{ .Content }}</div>
`)},
"views/mail/partials/card.htm": {Data: []byte(`name = "Card"
==
{{ .title }}
==
<div class="card">{{ .title }}</div>
`)},
}
}
// mailSpy is the mail driver of the mail screens' env: it keeps every
// message and fails while fail is set.
type mailSpy struct {
mu sync.Mutex
msgs []postcard.RenderedMessage
fail atomic.Bool
}
func (d *mailSpy) Send(_ context.Context, msg postcard.RenderedMessage) error {
if d.fail.Load() {
return errors.New("dial tcp smtp.internal.example:25: connection refused")
}
d.mu.Lock()
defer d.mu.Unlock()
d.msgs = append(d.msgs, msg)
return nil
}
func (d *mailSpy) messages() []postcard.RenderedMessage {
d.mu.Lock()
defer d.mu.Unlock()
return append([]postcard.RenderedMessage(nil), d.msgs...)
}
// mailEnv is screensEnv with postcard's Mailer published and the fixture
// mail plugin booted.
type mailEnv struct {
*screensEnv
blog mailBlogPlugin
driver *mailSpy
mailer postcard.Mailer
}
// newMailScreensEnv assembles the admin like newScreensEnv, with postcard's
// Mailer (over a spy driver and postcard's database override source) and the
// acme.blog mail plugin booted before surf.Assemble, as party.Activate does
// in an application. Assemble runs the serve-start index sync. The mail
// tables are emptied first: they are shared by every test on the database.
func newMailScreensEnv(t *testing.T, mutate func(*compass.Config)) *mailEnv {
t.Helper()
return newMailScreensEnvWith(t, mailEnvOptions{mutate: mutate})
}
// mailEnvOptions configure newMailScreensEnvWith: files replaces the
// fixture plugin's files, keep leaves the mail tables as they are (a second
// process on the same database), mutate changes the configuration.
type mailEnvOptions struct {
files fstest.MapFS
keep bool
mutate func(*compass.Config)
// writer, when set, is published as the cabana.TranslationWriter: the
// application's content locales, which the mail locales include.
writer cabana.TranslationWriter
}
// mailLocaleWriter is a TranslationWriter that only answers the locales.
type mailLocaleWriter struct {
def string
enabled []string
}
func (w mailLocaleWriter) DefaultLocale(context.Context, *gorm.DB) (string, error) {
return w.def, nil
}
func (w mailLocaleWriter) EnabledLocales(context.Context, *gorm.DB) ([]string, error) {
return w.enabled, nil
}
func (mailLocaleWriter) WriteTranslated(context.Context, *gorm.DB, any, string, string, string) error {
return nil
}
func (mailLocaleWriter) TranslatedExact(context.Context, *gorm.DB, any, string, string) (string, bool, error) {
return "", false, nil
}
func newMailScreensEnvWith(t *testing.T, opts mailEnvOptions) *mailEnv {
t.Helper()
mutate := opts.mutate
gdb := adminGorm(t)
if !opts.keep {
for _, table := range []string{postcard.TemplatesTable, postcard.LayoutsTable, postcard.PartialsTable, postcard.BrandTable, postcard.ImageLibraryTable} {
if err := gdb.Exec("DELETE FROM " + table).Error; err != nil {
t.Fatal(err)
}
}
}
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: cabana-mail\nlocale: en\nfallback_locale: en\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development", "SUMMER_ADMIN__JWT__SECRET=" + adminTestSecret}})
if err != nil {
t.Fatal(err)
}
for key, value := range map[string]any{
"http.body_limits.default_bytes": 1048576, "http.body_limits.upload_bytes": 8388608,
"admin.password.bcrypt_cost": 4, "admin.login.max_attempts": 100000,
"app.url": "https://mail.example.test",
} {
if err := cfg.Set(key, value); err != nil {
t.Fatal(err)
}
}
if mutate != nil {
mutate(cfg)
}
app := backpack.New(cfg)
if err := lagoon.Publish(app, adminSQL, gdb); err != nil {
t.Fatal(err)
}
bucket := memblob.OpenBucket(nil)
t.Cleanup(func() { _ = bucket.Close() })
if err := attach.Publish(app, bucket); err != nil {
t.Fatal(err)
}
driver := &mailSpy{}
mailer := postcard.NewMailer(nil, driver, postcard.Options{From: "noreply@example.test", Overrides: postcard.NewDBSource(app)})
if err := app.Publish[postcard.Mailer](mailer); err != nil {
t.Fatal(err)
}
files := opts.files
if files == nil {
files = mailBlogFiles()
}
blog := mailBlogPlugin{files: files}
if err := postcard.BootPlugin(app, blog); err != nil {
t.Fatal(err)
}
if opts.writer != nil {
if err := app.Publish[cabana.TranslationWriter](opts.writer); err != nil {
t.Fatal(err)
}
}
spy := &pingSpy{}
plugins := []party.Plugin{demoPlugin{fsys: demoFS()}, pingPlugin{spy: spy}, blog}
if err := phrasebook.Activate(app, plugins); err != nil {
t.Fatal(err)
}
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
return &mailEnv{
screensEnv: &screensEnv{h: h, app: app, gdb: gdb, stamp: fmt.Sprintf("m%d", time.Now().UnixNano()), spy: spy},
blog: blog, driver: driver, mailer: mailer,
}
}
// mailRowID is the id of a mail index row by code.
func (e *mailEnv) mailRowID(t *testing.T, table, code string) uint {
t.Helper()
var id uint
if err := e.gdb.Raw("SELECT id FROM "+table+" WHERE code = ?", code).Scan(&id).Error; err != nil || id == 0 {
t.Fatalf("%s row %s: id=%d err=%v", table, code, id, err)
}
return id
}
// listRows returns a list response's rows by their code column.
func listRows(t *testing.T, body map[string]any) map[string]map[string]any {
t.Helper()
rows, _ := body["data"].([]any)
out := map[string]map[string]any{}
for _, row := range rows {
fields, _ := row.(map[string]any)
code, _ := fields["code"].(string)
out[code] = fields
}
return out
}
// templateBody is a full template form save.
func templateBody(subject, body string, layout uint) map[string]any {
return map[string]any{"subject": subject, "body": body, "layout": layout}
}
func TestMailScreensSmoke(t *testing.T) {
env := newMailScreensEnv(t, nil)
_, rootToken := env.admin(t, "mail-root", true, "")
t.Run("templates", func(t *testing.T) {
list := env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil)
rows := listRows(t, list)
// One row per template: the -en variant is a version of welcome.
base := rows[blogWelcome]
if base == nil || rows[blogWelcomeEn] != nil || len(rows) != 1 {
t.Fatalf("templates list = %v", list["data"])
}
if _, has := base["locale"]; has || base["customized_locales"] != "" {
t.Fatalf("welcome row locale columns = %v", base)
}
if base["subject"] != "Witaj, {{ .name }}" || base["description"] != "Sent after registration" {
t.Fatalf("base row = %v", base)
}
schema := env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"/schema/form", rootToken, nil)
names := []string{}
fields, _ := dataOf(schema)["fields"].([]any)
for _, item := range fields {
field, _ := item.(map[string]any)
names = append(names, fmt.Sprint(field["name"]))
}
if got := strings.Join(names, ","); !strings.Contains(got, "subject,layout,body") {
t.Fatalf("template form fields = %s", got)
}
id := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, id)
saved := env.expect(t, http.StatusOK, http.MethodPut, path, rootToken, templateBody("Hello {{ .name }} from the admin", "Hi **{{ .name }}**.", layoutID))
if data := dataOf(saved); data["subject"] != "Hello {{ .name }} from the admin" {
t.Fatalf("saved template = %v", data)
}
var stored cabana.MailTemplate
if err := env.gdb.First(&stored, id).Error; err != nil {
t.Fatal(err)
}
file, _ := mailFileHash(t, env, blogWelcome)
if !stored.IsCustom || stored.BaseHash == nil || *stored.BaseHash != file || stored.CustomizedAt == nil {
t.Fatalf("stored template = %+v", stored)
}
// The next send of the template uses the override.
if err := env.mailer.Send(context.Background(), postcard.Message{Template: blogWelcome, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil {
t.Fatal(err)
}
msgs := env.driver.messages()
if len(msgs) == 0 || msgs[len(msgs)-1].Subject != "Hello Grace from the admin" {
t.Fatalf("sent = %+v", msgs)
}
// Unsafe content is a field line, and nothing is saved.
rec := env.call(t, http.MethodPut, path, rootToken, templateBody("Hello", "Hi <script>alert(1)</script>", layoutID))
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("unsafe save status=%d body=%s", rec.Code, rec.Body.String())
}
_, details := errorOf(t, rec)
if !detailHas(details, "body", "Mail cannot contain scripts") || !detailHas(details, "body", "<script") {
t.Fatalf("unsafe save details = %v", details)
}
var after cabana.MailTemplate
if err := env.gdb.First(&after, id).Error; err != nil {
t.Fatal(err)
}
if after.Subject != stored.Subject || after.Body != stored.Body {
t.Fatalf("unsafe save changed the row: %+v", after)
}
// The permission split (D-03).
_, layoutsToken := env.admin(t, "mail-layouts", false, `{"system.manage_mail_layouts":1}`)
_, templatesToken := env.admin(t, "mail-templates", false, `{"system.manage_mail_templates":1}`)
if rec := env.call(t, http.MethodGet, mailTemplatesPath, layoutsToken, nil); rec.Code != http.StatusForbidden {
t.Fatalf("layouts-only templates list status=%d", rec.Code)
}
env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, templatesToken, nil)
// No role gained either code from code or migrations.
var granted int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM backend_user_roles WHERE permissions LIKE '%system.manage_mail%' AND code NOT LIKE 'code-%'`).Scan(&granted).Error; err != nil || granted != 0 {
t.Fatalf("roles granted a mail code: %d err=%v", granted, err)
}
// The templates-only holder sees one Mail tile.
settings := env.expect(t, http.StatusOK, http.MethodGet, "/settings", templatesToken, nil)
tiles := []string{}
entries, _ := settings["data"].([]any)
for _, entry := range entries {
item, _ := entry.(map[string]any)
if item["category"] == "Mail" {
tiles = append(tiles, fmt.Sprint(item["code"]))
}
}
if strings.Join(tiles, ",") != "mail_templates" {
t.Fatalf("templates-only Mail tiles = %v", tiles)
}
})
mailLayoutsAndPartials(t, env, rootToken)
// Runs last: its env empties the mail tables.
t.Run("locales", func(t *testing.T) {
mailLocalesSmoke(t, rootToken)
})
t.Run("locales_list", func(t *testing.T) {
mailLocalesListSmoke(t, rootToken)
})
}
// welcomeListRow is the templates list's row of welcome, after checking it
// is the only row of its group.
func welcomeListRow(t *testing.T, env *mailEnv, token, query string) map[string]any {
t.Helper()
list := env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+query, token, nil)
for _, code := range listCodes(list) {
if code != blogWelcome && strings.HasPrefix(code, blogWelcome) {
t.Fatalf("list%s holds the variant %s: %v", query, code, listCodes(list))
}
}
row := listRows(t, list)[blogWelcome]
if row != nil {
row["_states"] = fmt.Sprint(rowStates(list, uint(row["id"].(float64))))
}
return row
}
// mailLocalesListSmoke is G-35-1 in the list and the per-locale states: one
// row per template with its customized locales and grouped badges, the
// status filter on the group, the default version shown for a locale
// without a file, the info and file version partials and reset of such a
// locale, and no locale filter.
func mailLocalesListSmoke(t *testing.T, rootToken string) {
writer := mailLocaleWriter{def: "pl", enabled: []string{"pl", "en", "de", "fr"}}
env := newMailScreensEnvWith(t, mailEnvOptions{writer: writer})
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
baseID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
deID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome+"-de")
frID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome+"-fr")
dePath := fmt.Sprintf("%s/%d", mailTemplatesPath, deID)
basePath := fmt.Sprintf("%s/%d", mailTemplatesPath, baseID)
// No locale filter any more; the status filter stays.
listSchema := env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"/schema/list", rootToken, nil)
scopes := []string{}
filters, _ := dataOf(listSchema)["filters"].([]any)
for _, item := range filters {
filter, _ := item.(map[string]any)
scopes = append(scopes, fmt.Sprint(filter["scope"], filter["name"]))
}
if got := strings.Join(scopes, ","); strings.Contains(got, "ocale") || !strings.Contains(got, "status") {
t.Fatalf("templates list filters = %s", got)
}
row := welcomeListRow(t, env, rootToken, "")
if row == nil || row["customized_locales"] != "" || row["_states"] != "[]" {
t.Fatalf("fresh welcome row = %v", row)
}
// A locale without a file shows the default version.
file, _ := mailEditor(t, env).Catalog().Template(blogWelcome)
deShow := dataOf(env.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil))
if deShow["subject"] != file.Subject || deShow["body"] != file.Body || fmt.Sprint(deShow["layout"]) != fmt.Sprint(layoutID) {
t.Fatalf("not customized de show = %v", deShow)
}
info := partialText(t, env, mailTemplatesPath, "info", rootToken, deID)
if !strings.Contains(info, "Locale de has no file of its own") || !strings.Contains(info, "views/mail/welcome.htm") {
t.Fatalf("de info partial = %s", info)
}
if baseInfo := partialText(t, env, mailTemplatesPath, "info", rootToken, baseID); !strings.Contains(baseInfo, "Default version: sent for every locale") {
t.Fatalf("default info partial = %s", baseInfo)
}
if version := partialText(t, env, mailTemplatesPath, "file_version", rootToken, deID); !strings.Contains(version, "dzięki za rejestrację") {
t.Fatalf("de file version partial = %s", version)
}
// Saving only de: the template's row is customized, de listed.
env.expect(t, http.StatusOK, http.MethodPut, dePath, rootToken, templateBody("Willkommen, {{ .name }}", "Hallo **{{ .name }}**.", layoutID))
row = welcomeListRow(t, env, rootToken, "")
if row["customized_locales"] != "de" || row["_states"] != "[customized]" {
t.Fatalf("welcome row after the de save = %v", row)
}
if welcomeListRow(t, env, rootToken, "?filter[status]=customized") == nil || welcomeListRow(t, env, rootToken, "?filter[status]=not_customized") != nil {
t.Fatal("status filter does not follow the de customization")
}
if deShow := dataOf(env.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil)); deShow["subject"] != "Willkommen, {{ .name }}" {
t.Fatalf("customized de show = %v", deShow)
}
if version := partialText(t, env, mailTemplatesPath, "file_version", rootToken, deID); !strings.Contains(version, "summer-diff__add") || !strings.Contains(version, "Willkommen") {
t.Fatalf("customized de file version = %s", version)
}
// The base file changes in a second process: de is outdated.
files := mailBlogFiles()
files["views/mail/welcome.htm"] = &fstest.MapFile{Data: []byte(`subject = "Witaj, {{ .name }}"
description = "Sent after registration"
layout = "blog"
sample.name = "Ada"
==
Cześć **{{ .name }}**, dzięki za rejestrację na blogu.
`)}
next := newMailScreensEnvWith(t, mailEnvOptions{files: files, keep: true, writer: writer})
row = welcomeListRow(t, next, rootToken, "")
if row["_states"] != "[customized outdated]" {
t.Fatalf("welcome row after the base file changed = %v", row)
}
if welcomeListRow(t, next, rootToken, "?filter[status]=outdated") == nil {
t.Fatal("outdated filter misses welcome")
}
// The base saved too: Default, de; fr shows the base customization.
next.expect(t, http.StatusOK, http.MethodPut, basePath, rootToken, templateBody("Witamy, {{ .name }}", "Base.", layoutID))
if row = welcomeListRow(t, next, rootToken, ""); row["customized_locales"] != "Default, de" {
t.Fatalf("welcome row after the base save = %v", row)
}
if frShow := dataOf(next.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", mailTemplatesPath, frID), rootToken, nil)); frShow["subject"] != "Witamy, {{ .name }}" || frShow["body"] != "Base." {
t.Fatalf("fr show with a customized base = %v", frShow)
}
// Reset of de: not customized, its show back to the default version.
if names := recordActionNames(next.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil)); strings.Join(names, ",") != "reset" {
t.Fatalf("customized de actions = %v", names)
}
next.expect(t, http.StatusOK, http.MethodPost, dePath+"/actions/reset", rootToken, map[string]any{})
var de cabana.MailTemplate
if err := next.gdb.First(&de, deID).Error; err != nil {
t.Fatal(err)
}
if de.IsCustom || de.BaseHash != nil {
t.Fatalf("reset de row = %+v", de)
}
if deShow := dataOf(next.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil)); deShow["subject"] != "Witamy, {{ .name }}" {
t.Fatalf("de show after reset = %v", deShow)
}
if row = welcomeListRow(t, next, rootToken, ""); row["customized_locales"] != "Default" {
t.Fatalf("welcome row after the de reset = %v", row)
}
if err := postcard.ResetOverride(context.Background(), next.gdb, mailEditor(t, next).Catalog(), postcard.KindTemplate, blogWelcome+"-fr"); err != nil {
t.Fatalf("ResetOverride of a fallback-locale code: %v", err)
}
}
// localeVariants returns a show response's meta.localeVariants.
func localeVariants(t *testing.T, show map[string]any) []map[string]any {
t.Helper()
meta, _ := show["meta"].(map[string]any)
items, _ := meta["localeVariants"].([]any)
out := make([]map[string]any, 0, len(items))
for _, item := range items {
v, _ := item.(map[string]any)
out = append(out, v)
}
return out
}
// variantSummary is "label[states]*" per variant, * marking the current one.
func variantSummary(variants []map[string]any) string {
parts := make([]string, 0, len(variants))
for _, v := range variants {
part := fmt.Sprintf("%v%v", v["label"], v["states"])
if v["current"] == true {
part += "*"
}
parts = append(parts, part)
}
return strings.Join(parts, " ")
}
// mailLocalesSmoke is G-35-1 end to end: on an application whose content
// locales are pl (default), en and de, the welcome template's form lists
// Default, de (no file) and en (its own file); the de version is opened,
// saved and sent for acme.blog::mail.welcome-de.
func mailLocalesSmoke(t *testing.T, rootToken string) {
env := newMailScreensEnvWith(t, mailEnvOptions{writer: mailLocaleWriter{def: "pl", enabled: []string{"pl", "en", "de"}}})
ctx := context.Background()
baseID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
show := env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", mailTemplatesPath, baseID), rootToken, nil)
variants := localeVariants(t, show)
if got := variantSummary(variants); got != "Default[]* de[] en[]" {
t.Fatalf("welcome variants = %s", got)
}
deID := uint(variants[1]["id"].(float64))
if deID != env.mailRowID(t, postcard.TemplatesTable, blogWelcome+"-de") || variants[1]["locale"] != "de" || variants[0]["locale"] != "" {
t.Fatalf("de variant = %v", variants[1])
}
dePath := fmt.Sprintf("%s/%d", mailTemplatesPath, deID)
deShow := env.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil)
if meta, _ := deShow["meta"].(map[string]any); meta["title"] != blogWelcome {
t.Fatalf("de title = %v, want the base code", meta["title"])
}
if got := variantSummary(localeVariants(t, deShow)); got != "Default[] de[]* en[]" {
t.Fatalf("de variants = %s", got)
}
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
env.expect(t, http.StatusOK, http.MethodPut, dePath, rootToken, templateBody("Willkommen, {{ .name }}", "Hallo **{{ .name }}**.", layoutID))
var stored cabana.MailTemplate
if err := env.gdb.First(&stored, deID).Error; err != nil {
t.Fatal(err)
}
baseHash, _ := mailFileHash(t, env, blogWelcome)
if !stored.IsCustom || stored.BaseHash == nil || *stored.BaseHash != baseHash {
t.Fatalf("stored de row = %+v, want customized against the base file", stored)
}
after := localeVariants(t, env.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil))
if got := variantSummary(after); got != "Default[] de[Customized]* en[]" {
t.Fatalf("variants after the de save = %s", got)
}
send := func(name string) postcard.RenderedMessage {
t.Helper()
if err := env.mailer.Send(ctx, postcard.Message{Template: name, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil {
t.Fatalf("Send %s: %v", name, err)
}
msgs := env.driver.messages()
return msgs[len(msgs)-1]
}
if got := send(blogWelcome + "-de"); got.Subject != "Willkommen, Grace" || !strings.Contains(got.HTML, "blog-mail") {
t.Fatalf("welcome-de sent %q / %q", got.Subject, got.HTML)
}
if got := send(blogWelcome); got.Subject != "Witaj, Grace" {
t.Fatalf("welcome sent %q, want the base file", got.Subject)
}
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
"mode": "template",
"id": deID,
"values": map[string]any{
"subject": "Vorschau",
"body": "Hallo **{{ .name }}**",
"layout": layoutID,
},
})
// An id outside the catalog's templates and their locale rows is a 404.
var orphan uint
if err := env.gdb.Raw(`INSERT INTO ` + postcard.TemplatesTable + ` (code, source, base_code) VALUES ('acme.gone::mail.x-de', 'acme.gone', 'acme.gone::mail.x') RETURNING id`).Scan(&orphan).Error; err != nil {
t.Fatal(err)
}
if rec := env.call(t, http.MethodGet, fmt.Sprintf("%s/%d", mailTemplatesPath, orphan), rootToken, nil); rec.Code != http.StatusNotFound {
t.Fatalf("orphan row status = %d", rec.Code)
}
}
// mailEditor is the env's postcard editor.
func mailEditor(t *testing.T, env *mailEnv) *postcard.Editor {
t.Helper()
editor, ok := postcard.EditorFrom(env.app)
if !ok {
t.Fatal("no postcard editor")
}
return editor
}
// listCodes are a list response's code column values in row order.
func listCodes(body map[string]any) []string {
rows, _ := body["data"].([]any)
out := []string{}
for _, row := range rows {
fields, _ := row.(map[string]any)
out = append(out, fmt.Sprint(fields["code"]))
}
return out
}
// partialText is a partial response as text, for contains checks.
func partialText(t *testing.T, env *mailEnv, path, name, token string, id uint) string {
t.Helper()
rec := env.call(t, http.MethodGet, fmt.Sprintf("%s/partials/%s?id=%d", path, name, id), token, nil)
if rec.Code != http.StatusOK {
t.Fatalf("partial %s status=%d body=%s", name, rec.Code, rec.Body.String())
}
return rec.Body.String()
}
// mailLayoutsAndPartials runs the Task 2 behaviour: layouts, partials,
// reset, delete, drift and meta.deletable.
func mailLayoutsAndPartials(t *testing.T, env *mailEnv, rootToken string) {
editor := mailEditor(t, env)
def, _ := editor.Catalog().Layout("postcard::mail.layouts.default")
var customID uint
t.Run("layouts", func(t *testing.T) {
created := env.expect(t, http.StatusCreated, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{
"name": "Promo", "code": "promo-2026", "content_html": def.HTML, "content_text": def.Text, "content_css": ".promo { color: #d66829; }",
})
customID = uint(dataOf(created)["id"].(float64))
var custom cabana.MailLayout
if err := env.gdb.First(&custom, customID).Error; err != nil {
t.Fatal(err)
}
if !custom.IsCustom || custom.Source != nil || custom.Code != "promo-2026" || custom.DisableAutoInlineCSS {
t.Fatalf("custom layout = %+v", custom)
}
env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{
"name": "Bad", "code": "Promo 2026", "content_html": def.HTML, "content_text": def.Text,
}, "code", "Use lowercase letters, digits and dashes only.", false)
env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{
"name": "Again", "code": "promo-2026", "content_html": def.HTML, "content_text": def.Text,
}, "code", "already used by another layout", false)
list := env.expect(t, http.StatusOK, http.MethodGet, mailLayoutsPath, rootToken, nil)
codes := listCodes(list)
if len(codes) == 0 || codes[0] != "postcard::mail.layouts.default" {
t.Fatalf("layouts order = %v", codes)
}
for _, want := range []string{"postcard::mail.layouts.system", "postcard::mail.layouts.minimal", blogLayout, "promo-2026"} {
if !strings.Contains(strings.Join(codes, ","), want) {
t.Fatalf("layouts %v miss %s", codes, want)
}
}
if rows := listRows(t, list); rows["promo-2026"]["source"] != "Custom" || rows[blogLayout]["source"] != "acme.blog" {
t.Fatalf("layout sources = %v / %v", rows["promo-2026"], rows[blogLayout])
}
blogID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
blogPath := fmt.Sprintf("%s/%d", mailLayoutsPath, blogID)
blogFile, _ := editor.Catalog().Layout(blogLayout)
env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPut, blogPath, rootToken, map[string]any{
"name": "Blog", "content_html": "<div>no content</div>", "content_text": blogFile.Text, "content_css": "",
}, "content_html", "Put {{ .Content }} where the message goes.", false)
env.expect(t, http.StatusOK, http.MethodPut, blogPath, rootToken, map[string]any{
"name": "Blog", "content_html": `<div class="blog-mail customized-layout">{{ .Content }}</div>`, "content_text": blogFile.Text, "content_css": "",
})
var blog cabana.MailLayout
if err := env.gdb.First(&blog, blogID).Error; err != nil || !blog.IsCustom || blog.BaseHash == nil {
t.Fatalf("customized file layout = %+v err=%v", blog, err)
}
if err := env.mailer.Send(context.Background(), postcard.Message{Template: blogWelcomeEn, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil {
t.Fatal(err)
}
if msgs := env.driver.messages(); !strings.Contains(msgs[len(msgs)-1].HTML, "customized-layout") {
t.Fatalf("send did not use the customized layout: %s", msgs[len(msgs)-1].HTML)
}
// The CSS tab's switch keeps the layout's CSS in its style block:
// the next send has no inlined style on the button.
withButton := `<style>{{ .css }}</style><div class="blog-mail customized-layout">{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Go" }}</div>`
for _, optOut := range []bool{true, false} {
env.expect(t, http.StatusOK, http.MethodPut, blogPath, rootToken, map[string]any{
"name": "Blog", "content_html": withButton, "content_text": blogFile.Text, "content_css": ".button { color: #123456; }", "disable_auto_inline_css": optOut,
})
if err := env.gdb.First(&blog, blogID).Error; err != nil || blog.DisableAutoInlineCSS != optOut {
t.Fatalf("saved switch = %v, want %v (err %v)", blog.DisableAutoInlineCSS, optOut, err)
}
if err := env.mailer.Send(context.Background(), postcard.Message{Template: blogWelcomeEn, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil {
t.Fatal(err)
}
msgs := env.driver.messages()
html := msgs[len(msgs)-1].HTML
button := regexp.MustCompile(`<a [^>]*button-primary[^>]*>`).FindString(html)
if inlined := strings.Contains(button, `style="color:#123456"`); button == "" || inlined == optOut {
t.Fatalf("opt-out %v: button %q in %s", optOut, button, html)
}
if optOut && !strings.Contains(html, "<style>.button { color: #123456; }") {
t.Fatalf("opt-out: the style block was not kept: %s", html)
}
}
})
t.Run("partials", func(t *testing.T) {
list := env.expect(t, http.StatusOK, http.MethodGet, mailPartialsPath, rootToken, nil)
codes := strings.Join(listCodes(list), ",")
for _, want := range []string{"postcard::mail.partials.button", "postcard::mail.partials.panel", "postcard::mail.partials.table", "postcard::mail.partials.subcopy", blogCard} {
if !strings.Contains(codes, want) {
t.Fatalf("partials %s miss %s", codes, want)
}
}
cardID := env.mailRowID(t, postcard.PartialsTable, blogCard)
cardPath := fmt.Sprintf("%s/%d", mailPartialsPath, cardID)
env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPut, cardPath, rootToken, map[string]any{
"content_html": `<div class="card">{{ .title </div>`, "content_text": "{{ .title }}",
}, "content_html", "This cannot be read as a template", false)
env.expect(t, http.StatusOK, http.MethodPut, cardPath, rootToken, map[string]any{
"content_html": `<div class="card card--custom">{{ .title }}</div>`, "content_text": "{{ .title }}",
})
info := partialText(t, env, mailPartialsPath, "info", rootToken, cardID)
if !strings.Contains(info, `{{ partial \"acme.blog::mail.partials.card\" \"title\" .title }}`) {
t.Fatalf("partial usage line = %s", info)
}
buttonInfo := partialText(t, env, mailPartialsPath, "info", rootToken, env.mailRowID(t, postcard.PartialsTable, "postcard::mail.partials.button"))
if !strings.Contains(buttonInfo, `{{ partial \"button\"`) {
t.Fatalf("built-in partial usage line = %s", buttonInfo)
}
})
t.Run("reset", func(t *testing.T) {
id := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, id)
if names := recordActionNames(env.expect(t, http.StatusOK, http.MethodGet, path, rootToken, nil)); strings.Join(names, ",") != "reset" {
t.Fatalf("customized template actions = %v", names)
}
result := env.expect(t, http.StatusOK, http.MethodPost, path+"/actions/reset", rootToken, map[string]any{})
if dataOf(result)["message"] != "Reset to the file version." {
t.Fatalf("reset result = %v", result)
}
file, _ := editor.Catalog().Template(blogWelcome)
var row cabana.MailTemplate
if err := env.gdb.First(&row, id).Error; err != nil {
t.Fatal(err)
}
if row.IsCustom || row.Subject != file.Subject || row.Body != file.Body || row.BaseHash != nil {
t.Fatalf("reset row = %+v", row)
}
if names := recordActionNames(env.expect(t, http.StatusOK, http.MethodGet, path, rootToken, nil)); len(names) != 0 {
t.Fatalf("reset template still offers %v", names)
}
if names := recordActionNames(env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", mailLayoutsPath, customID), rootToken, nil)); len(names) != 0 {
t.Fatalf("custom layout offers %v", names)
}
})
t.Run("delete", func(t *testing.T) {
id := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, id)
env.expect(t, http.StatusOK, http.MethodPut, path, rootToken, templateBody("Promo for {{ .name }}", "Hi **{{ .name }}**.", customID))
layoutPath := fmt.Sprintf("%s/%d", mailLayoutsPath, customID)
env.expectRefusal(t, http.StatusForbidden, http.MethodDelete, layoutPath, rootToken, nil, "The layout “Promo” is used by 1 customized template.")
env.expect(t, http.StatusOK, http.MethodPost, path+"/actions/reset", rootToken, map[string]any{})
if rec := env.call(t, http.MethodDelete, layoutPath, rootToken, nil); rec.Code/100 != 2 {
t.Fatalf("delete unused custom layout status=%d body=%s", rec.Code, rec.Body.String())
}
for _, target := range []string{
fmt.Sprintf("%s/%d", mailLayoutsPath, env.mailRowID(t, postcard.LayoutsTable, blogLayout)),
path,
fmt.Sprintf("%s/%d", mailPartialsPath, env.mailRowID(t, postcard.PartialsTable, blogCard)),
} {
if rec := env.call(t, http.MethodDelete, target, rootToken, nil); rec.Code != http.StatusForbidden {
t.Fatalf("delete %s status=%d body=%s", target, rec.Code, rec.Body.String())
}
}
})
t.Run("deletable", func(t *testing.T) {
created := env.expect(t, http.StatusCreated, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{
"name": "Keep", "code": "keep-me", "content_html": def.HTML, "content_text": def.Text,
})
keepID := uint(dataOf(created)["id"].(float64))
for _, tc := range []struct {
path string
want string
}{
{fmt.Sprintf("%s/%d", mailLayoutsPath, keepID), "true"},
{fmt.Sprintf("%s/%d", mailLayoutsPath, env.mailRowID(t, postcard.LayoutsTable, blogLayout)), "false"},
{fmt.Sprintf("%s/%d", mailTemplatesPath, env.mailRowID(t, postcard.TemplatesTable, blogWelcome)), "false"},
{fmt.Sprintf("%s/%d", mailPartialsPath, env.mailRowID(t, postcard.PartialsTable, blogCard)), "false"},
} {
meta, _ := env.expect(t, http.StatusOK, http.MethodGet, tc.path, rootToken, nil)["meta"].(map[string]any)
if fmt.Sprint(meta["deletable"]) != tc.want {
t.Fatalf("%s meta.deletable = %v want %s", tc.path, meta["deletable"], tc.want)
}
}
root, _ := env.admin(t, "mail-deletable", true, "")
meta, _ := env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", usersPath, root.ID), rootToken, nil)["meta"].(map[string]any)
if _, has := meta["deletable"]; has {
t.Fatalf("users meta carries deletable: %v", meta)
}
})
t.Run("drift", func(t *testing.T) {
id := env.mailRowID(t, postcard.TemplatesTable, blogWelcomeEn)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, id)
blogID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
env.expect(t, http.StatusOK, http.MethodPut, path, rootToken, templateBody("Welcome aboard, {{ .name }}", "Hi **{{ .name }}**, glad you joined.", blogID))
// A second process boots with a changed file and syncs the index.
files := mailBlogFiles()
files["views/mail/welcome-en.htm"] = &fstest.MapFile{Data: []byte(`subject = "Welcome, {{ .name }}"
description = "Sent after registration (English)"
layout = "blog"
sample.name = "Ada"
==
Hi **{{ .name }}**, thanks for joining the Acme blog.
`)}
next := newMailScreensEnvWith(t, mailEnvOptions{files: files, keep: true})
// The list row is the template's: its states are the group's.
baseID := next.mailRowID(t, postcard.TemplatesTable, blogWelcome)
list := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil)
if got := fmt.Sprint(rowStates(list, baseID)); got != "[customized outdated]" {
t.Fatalf("drifted row states = %s", got)
}
filtered := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[status]=outdated", rootToken, nil)
if codes := listCodes(filtered); strings.Join(codes, ",") != blogWelcome {
t.Fatalf("outdated filter = %v", codes)
}
customized := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[status]=customized", rootToken, nil)
if codes := listCodes(customized); strings.Join(codes, ",") != blogWelcome {
t.Fatalf("customized filter = %v", codes)
}
info := partialText(t, next, mailTemplatesPath, "info", rootToken, id)
if !strings.Contains(info, "The file changed after this was customized") {
t.Fatalf("info partial = %s", info)
}
version := partialText(t, next, mailTemplatesPath, "file_version", rootToken, id)
if !strings.Contains(version, "summer-diff__add") || !strings.Contains(version, "summer-diff__del") || !strings.Contains(version, "thanks for joining the Acme blog") {
t.Fatalf("file version partial = %s", version)
}
next.expect(t, http.StatusOK, http.MethodPut, path, rootToken, templateBody("Welcome aboard, {{ .name }}", "Hi **{{ .name }}**, glad you joined.", blogID))
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil), baseID)); got != "[customized]" {
t.Fatalf("reviewed row states = %s", got)
}
})
t.Run("diff", func(t *testing.T) {
got := cabana.LineDiffForTest([]string{"a", "b", "c", "d", "e", "f", "g", "h"}, []string{"a", "b", "c", "d", "X", "f", "g", "h"}, 3)
if got != " b| c| d|- e|+ X| f| g| h" {
t.Fatalf("lineDiff = %s", got)
}
long := make([]string, 2001)
for i := range long {
long[i] = fmt.Sprint(i)
}
if got := cabana.LineDiffForTest(long, []string{"x"}, 3); got != "" {
t.Fatalf("lineDiff above the cap = %q", got)
}
})
t.Run("fields", func(t *testing.T) {
schema := env.expect(t, http.StatusOK, http.MethodGet, mailLayoutsPath+"/schema/form", rootToken, nil)
fields, _ := schema["data"].(map[string]any)["fields"].([]any)
var html map[string]any
for _, raw := range fields {
f, _ := raw.(map[string]any)
if f["name"] == "content_html" {
html = f
break
}
}
if html == nil || html["type"] != "codeeditor" || html["language"] != "html" || html["mailImages"] != true {
t.Fatalf("content_html schema = %#v", html)
}
})
t.Run("branding", func(t *testing.T) {
got := env.expect(t, http.StatusOK, http.MethodGet, "/settings/mail_brand", rootToken, nil)
if got["data"].(map[string]any)["exists"] != false {
t.Fatalf("fresh brand exists = %#v", got["data"])
}
data, _ := got["data"].(map[string]any)["data"].(map[string]any)
if fmt.Sprint(data["button_primary_bg"]) != "#d66829" {
t.Fatalf("default button_primary_bg = %#v", data["button_primary_bg"])
}
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"button_primary_bg": "red"})
saved := env.expect(t, http.StatusOK, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"button_primary_bg": "#D66829"})
if saved["data"].(map[string]any)["exists"] != true {
t.Fatalf("saved brand exists = %#v", saved["data"])
}
row := saved["data"].(map[string]any)["data"].(map[string]any)
if fmt.Sprint(row["button_primary_bg"]) != "#d66829" {
t.Fatalf("stored colour = %#v", row["button_primary_bg"])
}
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"logo_file_id": 999999})
// The site name is saved trimmed and is shown in the default
// layout's header and footer by the Branding preview.
saved = env.expect(t, http.StatusOK, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"button_primary_bg": "#d66829", "site_name": " Acme Mail "})
if name := saved["data"].(map[string]any)["data"].(map[string]any)["site_name"]; name != "Acme Mail" {
t.Fatalf("stored site_name = %#v", name)
}
var stored cabana.MailBrandSetting
if err := env.gdb.First(&stored, 1).Error; err != nil || stored.SiteName != "Acme Mail" {
t.Fatalf("brand row = %+v err=%v", stored, err)
}
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"site_name": strings.Repeat("x", 256)})
preview := env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
"mode": "branding", "id": 0, "values": map[string]any{"site_name": "Preview Name"},
})
if html := fmt.Sprint(preview["data"].(map[string]any)["html"]); !strings.Contains(html, "Preview Name</span>") || !strings.Contains(html, "Preview Name</p>") {
t.Fatalf("branding preview lacks the site name: %s", html)
}
})
t.Run("images", func(t *testing.T) {
listed := env.expect(t, http.StatusOK, http.MethodGet, "/mail/images", rootToken, nil)
meta, _ := listed["meta"].(map[string]any)
if meta["canUpload"] != true {
t.Fatalf("root canUpload = %#v", meta)
}
rec := mailUpload(t, env.h, rootToken, conformPNG(t), "badge.png")
if rec.Code != http.StatusCreated {
t.Fatalf("upload status=%d body=%s", rec.Code, rec.Body.String())
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
item, _ := body["data"].(map[string]any)
if !strings.HasPrefix(fmt.Sprint(item["url"]), "https://mail.example.test/") {
t.Fatalf("url = %#v", item["url"])
}
id := fmt.Sprint(item["id"])
env.expect(t, http.StatusOK, http.MethodGet, "/mail/images/"+id, rootToken, nil)
env.expect(t, http.StatusNotFound, http.MethodGet, "/mail/images/999999", rootToken, nil)
noURL := newMailScreensEnv(t, func(cfg *compass.Config) {
_ = cfg.Set("app.url", "")
_ = cfg.Set("storage.uploads.public_url", "")
})
_, tok := noURL.admin(t, "mail-nourl", true, "")
noURL.expect(t, http.StatusConflict, http.MethodGet, "/mail/images", tok, nil)
})
t.Run("images_permissions", func(t *testing.T) {
_, templatesTok := env.admin(t, "mail-tmpl-img", false, `{"system.manage_mail_templates":1}`)
_, layoutsTok := env.admin(t, "mail-lay-img", false, `{"system.manage_mail_layouts":1}`)
listed := env.expect(t, http.StatusOK, http.MethodGet, "/mail/images", templatesTok, nil)
if listed["meta"].(map[string]any)["canUpload"] != false {
t.Fatalf("templates canUpload = %#v", listed["meta"])
}
if rec := mailUpload(t, env.h, templatesTok, conformPNG(t), "x.png"); rec.Code != http.StatusForbidden {
t.Fatalf("templates upload status=%d", rec.Code)
}
if rec := mailUpload(t, env.h, layoutsTok, conformPNG(t), "ok.png"); rec.Code != http.StatusCreated {
t.Fatalf("layouts upload status=%d body=%s", rec.Code, rec.Body.String())
}
env.expect(t, http.StatusForbidden, http.MethodGet, "/summercms/cabana/mailimages/singleton", templatesTok, nil)
env.expect(t, http.StatusOK, http.MethodGet, "/summercms/cabana/mailimages/singleton", layoutsTok, nil)
})
t.Run("preview", func(t *testing.T) {
user, rootToken := env.admin(t, "mail-preview", true, "")
_ = user
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
got := env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
"mode": "template",
"id": tmplID,
"values": map[string]any{
"subject": "Preview subject",
"body": "Hello **{{ .name }}**",
"layout": layoutID,
},
})
data, _ := got["data"].(map[string]any)
if fmt.Sprint(data["subject"]) != "Preview subject" {
t.Fatalf("subject = %#v", data["subject"])
}
html := fmt.Sprint(data["html"])
if strings.Contains(strings.ToLower(html), "<script") {
t.Fatalf("html carries a script: %s", html)
}
if !strings.Contains(html, "Ada") && !strings.Contains(html, "[name]") {
t.Fatalf("html missing sample or placeholder: %s", html)
}
env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, "/mail/preview", rootToken, map[string]any{
"mode": "template",
"id": tmplID,
"values": map[string]any{
"subject": "x",
"body": `{{ partial "no.such.partial" }}`,
"layout": layoutID,
},
})
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
"mode": "layout",
"id": 0,
"values": map[string]any{
"content_html": `<div class="preview-layout">{{ .Content }}</div>`,
"content_text": "{{ .Content }}",
"content_css": "",
},
})
partialID := env.mailRowID(t, postcard.PartialsTable, blogCard)
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
"mode": "partial",
"id": partialID,
"values": map[string]any{
"content_html": `<div>{{ .title }}</div>`,
"content_text": "{{ .title }}",
},
})
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
"mode": "branding",
"id": 0,
"values": map[string]any{
"button_primary_bg": "#112233",
},
})
})
t.Run("preview_permissions", func(t *testing.T) {
_, templatesTok := env.admin(t, "mail-prev-tmpl", false, `{"system.manage_mail_templates":1}`)
_, layoutsTok := env.admin(t, "mail-prev-lay", false, `{"system.manage_mail_layouts":1}`)
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", templatesTok, map[string]any{
"mode": "template", "id": tmplID,
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
})
env.expect(t, http.StatusForbidden, http.MethodPost, "/mail/preview", templatesTok, map[string]any{
"mode": "layout", "id": 0,
"values": map[string]any{"content_html": "{{ .Content }}", "content_text": "{{ .Content }}"},
})
env.expect(t, http.StatusForbidden, http.MethodPost, "/mail/preview", templatesTok, map[string]any{
"mode": "partial", "id": env.mailRowID(t, postcard.PartialsTable, blogCard),
"values": map[string]any{"content_html": "x", "content_text": "x"},
})
env.expect(t, http.StatusForbidden, http.MethodPost, "/mail/preview", templatesTok, map[string]any{
"mode": "branding", "id": 0, "values": map[string]any{},
})
env.expect(t, http.StatusForbidden, http.MethodPost, "/mail/preview", layoutsTok, map[string]any{
"mode": "template", "id": tmplID,
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
})
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", layoutsTok, map[string]any{
"mode": "layout", "id": 0,
"values": map[string]any{"content_html": "{{ .Content }}", "content_text": "{{ .Content }}"},
})
})
t.Run("test_send", func(t *testing.T) {
user, tok := env.admin(t, "mail-test-send", true, "")
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
before := len(env.driver.messages())
got := env.expect(t, http.StatusOK, http.MethodPost, "/mail/test-send", tok, map[string]any{
"mode": "template",
"id": tmplID,
"values": map[string]any{
"subject": "Test subject",
"body": "Hello {{ .name }}",
"layout": layoutID,
},
})
if fmt.Sprint(got["data"].(map[string]any)["email"]) != user.Email {
t.Fatalf("email = %#v want %s", got["data"], user.Email)
}
msgs := env.driver.messages()
if len(msgs) != before+1 {
t.Fatalf("messages = %d want %d", len(msgs), before+1)
}
last := msgs[len(msgs)-1]
if len(last.To) != 1 || last.To[0] != user.Email || len(last.Cc) != 0 || len(last.Bcc) != 0 {
t.Fatalf("recipients To=%v Cc=%v Bcc=%v", last.To, last.Cc, last.Bcc)
}
})
t.Run("test_send_recipient", func(t *testing.T) {
user, tok := env.admin(t, "mail-test-recip", true, "")
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
values := map[string]any{"subject": "s", "body": "b", "layout": layoutID}
for _, key := range []string{"to", "email", "recipient"} {
body := map[string]any{"mode": "template", "id": tmplID, "values": values, key: "other@example.test"}
rec := env.call(t, http.MethodPost, "/mail/test-send", tok, body)
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("%s key status=%d want 422 body=%s", key, rec.Code, rec.Body.String())
}
}
plain, err := cabana.IssueTestAPIToken(env.gdb, user.ID, []string{"*"}, nil)
if err != nil {
t.Fatal(err)
}
rec := env.call(t, http.MethodPost, "/mail/test-send", plain, map[string]any{
"mode": "template", "id": tmplID, "values": values,
})
if rec.Code != http.StatusForbidden {
t.Fatalf("API token status=%d want 403 body=%s", rec.Code, rec.Body.String())
}
})
t.Run("test_send_limit", func(t *testing.T) {
userA, tokA := env.admin(t, "mail-limit-a", true, "")
userB, tokB := env.admin(t, "mail-limit-b", true, "")
_ = userA
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
body := map[string]any{
"mode": "template", "id": tmplID,
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
}
for i := 0; i < 5; i++ {
env.expect(t, http.StatusOK, http.MethodPost, "/mail/test-send", tokA, body)
}
rec := env.call(t, http.MethodPost, "/mail/test-send", tokA, body)
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("sixth status=%d want 429 body=%s", rec.Code, rec.Body.String())
}
if rec.Header().Get("Retry-After") == "" {
t.Fatal("missing Retry-After")
}
env.expect(t, http.StatusOK, http.MethodPost, "/mail/test-send", tokB, body)
_ = userB
})
t.Run("test_send_driver_failure", func(t *testing.T) {
_, tok := env.admin(t, "mail-test-fail", true, "")
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
env.driver.fail.Store(true)
t.Cleanup(func() { env.driver.fail.Store(false) })
rec := env.call(t, http.MethodPost, "/mail/test-send", tok, map[string]any{
"mode": "template", "id": tmplID,
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
})
if rec.Code != http.StatusBadGateway {
t.Fatalf("status=%d want 502 body=%s", rec.Code, rec.Body.String())
}
if strings.Contains(rec.Body.String(), "connection refused") {
t.Fatalf("driver error leaked: %s", rec.Body.String())
}
})
}
// mailUpload POSTs a multipart file to /mail/images.
func mailUpload(t *testing.T, h http.Handler, token string, data []byte, name string) *httptest.ResponseRecorder {
t.Helper()
var body bytes.Buffer
w := multipart.NewWriter(&body)
part, err := w.CreateFormFile("file", name)
if err != nil {
t.Fatal(err)
}
if _, err := io.Copy(part, bytes.NewReader(data)); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, adminAPI("/mail/images"), &body)
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Requested-With", "XMLHttpRequest")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
// mailFileHash is the catalog hash and source of a template file.
func mailFileHash(t *testing.T, env *mailEnv, name string) (string, string) {
t.Helper()
editor, ok := postcard.EditorFrom(env.app)
if !ok {
t.Fatal("no postcard editor")
}
file, ok := editor.Catalog().Template(name)
if !ok {
t.Fatalf("template %s not in the catalog", name)
}
return file.Hash, file.Source
}