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 ==
{{ .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) // 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 ", 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) } // 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 := `
{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Go" }}
` 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(`]*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, "