package cabana_test import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "io/fs" "mime/multipart" "net/http" "net/http/httptest" "os" "path/filepath" "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" ) // 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 ==
{{ .Content }}
`)}, "views/mail/partials/card.htm": {Data: []byte(`name = "Card" == {{ .title }} ==
{{ .title }}
`)}, } } // 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) } 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) } 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) base, en := rows[blogWelcome], rows[blogWelcomeEn] if base == nil || en == nil { t.Fatalf("templates list = %v", list["data"]) } if en["locale"] != "en" || base["locale"] != "Default" { t.Fatalf("locales = %v / %v", base["locale"], en["locale"]) } 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 ", 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", "no content", "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": `
{{ .Content }}
`, "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) } }) 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": `
{{ .title
`, "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": `
{{ .title }}
`, "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}) list := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil) if got := fmt.Sprint(rowStates(list, id)); 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, ",") != blogWelcomeEn { 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, ",") != blogWelcomeEn { 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) } localeFilter := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[locale]=en", rootToken, nil) if codes := listCodes(localeFilter); strings.Join(codes, ",") != blogWelcomeEn { t.Fatalf("locale filter = %v", codes) } 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), id)); 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}) }) 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), "{{ .Content }}`, "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": `
{{ .title }}
`, "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 }