package postcard import ( "bytes" "context" "errors" "log/slog" "strings" "testing" "testing/fstest" "time" ) const ( inlineBrandColour = "#445566" inlineMedia = "@media only screen and (max-width: 600px) { .inner-body { width: 100% !important; } }" ) var inlineVars = map[string]any{"Name": "Ada", "Link": "https://example.com/go"} // defaultLayoutWithCSS is the built-in default layout as a database layout // whose CSS is css. func defaultLayoutWithCSS(css string, optOut bool) map[string]LayoutOverride { def, _ := NewCatalog().Layout(defaultLayoutName) return map[string]LayoutOverride{defaultLayoutName: {HTML: def.HTML, Text: def.Text, CSS: css, DisableAutoInlineCSS: optOut}} } func TestInlineCSS(t *testing.T) { t.Parallel() brand := &Brand{ButtonPrimaryBg: inlineBrandColour} ov := &Overrides{Brand: brand, Layouts: defaultLayoutWithCSS(inlineMedia, false)} m, drv := partialsMailer(t, Options{}, ov) inlined := sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars) // The same message with inlining off: the mailer's no-op inliner seam. plainMailer, plainDrv := partialsMailer(t, Options{}, ov) plainMailer.(*mailer).inline = noInline plain := sendTemplate(t, plainMailer, plainDrv, "acme.blog::mail.welcome", inlineVars) t.Run("button_colour", func(t *testing.T) { if style := buttonStyle(t, inlined.HTML); !strings.Contains(style, "background-color:"+inlineBrandColour) { t.Errorf("button style = %q, want the brand primary colour inline", style) } if style := buttonStyle(t, plain.HTML); style != "" { t.Errorf("without inlining the button has style %q", style) } }) t.Run("doctype", func(t *testing.T) { const doctype = `` if !strings.HasPrefix(inlined.HTML, doctype) { t.Errorf("DOCTYPE lost:\n%.200s", inlined.HTML) } if strings.Count(inlined.HTML, "
{{ .Content }}
`, Text: "{{ .Content }}", CSS: `.blog-mail { background: url("javascript:alert(1)"); }`, }, }} assertFileFallback(t, cat, fileWelcome(t), Options{Overrides: fakeOverrides{ov: unsafe}}, true) // The same CSS in an inlined style attribute is caught by the check // that runs on the inliner's output. if err := validateHTML(`
x
`); err == nil { t.Error("the safety check accepts a javascript: URL in a style attribute") } }) } func TestInlineCSSOptOut(t *testing.T) { t.Parallel() brand := &Brand{ButtonPrimaryBg: inlineBrandColour} const buttonBody = "{{ partial \"button\" \"url\" \"https://example.com\" \"body\" \"Go\" }}\n" const plainLayout = "{{ .Content }}\n" // optedOut checks a message whose layout kept its CSS in the style block. optedOut := func(t *testing.T, html string) { t.Helper() if style := buttonStyle(t, html); style != "" { t.Errorf("the button has an inlined style %q", style) } if css := styleBlock(t, html); !strings.Contains(css, inlineBrandColour) { t.Errorf("the style block lost the brand CSS:\n%s", css) } } inlinedButton := func(t *testing.T, html string) { t.Helper() if style := buttonStyle(t, html); !strings.Contains(style, inlineBrandColour) { t.Errorf("the button carries no inlined brand colour: %q", style) } } t.Run("file_header_key", func(t *testing.T) { for _, value := range []string{"true", "TRUE", "1", "yes", "false", "0", ""} { header := "name = \"Plain\"\n" if value != "" { header += "disable_auto_inline_css = " + value + "\n" } fsys := fstest.MapFS{ "views/mail/plain.htm": {Data: []byte("subject = \"Plain\"\nlayout = \"plain\"\n==\n" + buttonBody)}, "views/mail/layouts/plain.htm": {Data: []byte(header + "==\n{{ .Content }}\n==\n" + plainLayout)}, } cat := NewCatalog() if err := cat.Register("acme.shop", fsys, []string{"acme.shop::mail.plain"}, map[string]string{"plain": "acme.shop::mail.layouts.plain"}); err != nil { t.Fatal(err) } want := value == "true" || value == "TRUE" || value == "1" || value == "yes" if f, _ := cat.Layout("acme.shop::mail.layouts.plain"); f.DisableAutoInlineCSS != want { t.Errorf("header %q: LayoutFile.DisableAutoInlineCSS = %v, want %v", value, f.DisableAutoInlineCSS, want) } drv := NewMemoryDriver() msg := sendTemplate(t, NewMailer(cat, drv, Options{Overrides: fakeOverrides{ov: Overrides{Brand: brand}}}), drv, "acme.shop::mail.plain", nil) if want { optedOut(t, msg.HTML) } else { inlinedButton(t, msg.HTML) } } for _, f := range NewCatalog().Layouts() { if f.DisableAutoInlineCSS { t.Errorf("built-in layout %s opts out of inlining", f.Name) } } }) t.Run("override_column", func(t *testing.T) { m, drv := partialsMailer(t, Options{}, &Overrides{Brand: brand, Layouts: defaultLayoutWithCSS("", true)}) optedOut(t, sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars).HTML) m, drv = partialsMailer(t, Options{}, &Overrides{Brand: brand, Layouts: defaultLayoutWithCSS("", false)}) inlinedButton(t, sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars).HTML) }) t.Run("layout_draft", func(t *testing.T) { ed, _ := newEditor(t, &Overrides{Brand: brand}) draft := Draft{Kind: KindLayout, HTML: plainLayout, Text: "{{ .Content }}"} prev, err := ed.Preview(context.Background(), draft) if err != nil { t.Fatal(err) } inlinedButton(t, prev.HTML) draft.DisableAutoInlineCSS = true if prev, err = ed.Preview(context.Background(), draft); err != nil { t.Fatal(err) } optedOut(t, prev.HTML) if derr := ed.Validate(context.Background(), draft); derr != nil { t.Errorf("a layout draft with the opt-out does not validate: %v", derr) } }) } func TestInlineFailure(t *testing.T) { t.Parallel() brand := &Brand{ButtonPrimaryBg: inlineBrandColour} m, drv := partialsMailer(t, Options{CSS: inlineMedia}, &Overrides{Brand: brand}) mm := m.(*mailer) var logs bytes.Buffer mm.log = slog.New(slog.NewTextHandler(&logs, nil)) calls := 0 mm.inline = func(string) (string, error) { calls++; return "", errors.New("inliner broke") } failed := sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars) sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars) if calls != 2 { t.Fatalf("the inliner ran %d times, want 2", calls) } // The un-inlined HTML is sent: exactly what a no-op inliner produces. ref, refDrv := partialsMailer(t, Options{CSS: inlineMedia}, &Overrides{Brand: brand}) ref.(*mailer).inline = noInline want := sendTemplate(t, ref, refDrv, "acme.blog::mail.welcome", inlineVars) if failed.HTML != want.HTML || failed.Text != want.Text { t.Errorf("an inliner error did not send the un-inlined message:\n%s\nwant\n%s", failed.HTML, want.HTML) } if style := buttonStyle(t, failed.HTML); style != "" { t.Errorf("the button has a style %q after an inliner error", style) } if css := styleBlock(t, failed.HTML); !strings.Contains(css, inlineBrandColour) || !strings.Contains(css, "@media") { t.Errorf("the style block lost CSS after an inliner error:\n%s", css) } // One warning per layout per minute: two sends in the default layout // warn once; the system layout is another key. out := logs.String() if n := strings.Count(out, "level=WARN"); n != 1 || !strings.Contains(out, "inliner broke") || !strings.Contains(out, "layout="+defaultLayoutName) { t.Fatalf("log = %q, want one warning naming the error and the layout", out) } sendTemplate(t, m, drv, "acme.blog::mail.auto", nil) if n := strings.Count(logs.String(), "level=WARN"); n != 2 || !strings.Contains(logs.String(), "layout="+systemLayoutName) { t.Errorf("log = %q, want a second warning for the system layout", logs.String()) } // The gate behind it repeats a key after warnInterval. var g warnGate now := time.Now() if !g.allow("inline:"+defaultLayoutName, now) || g.allow("inline:"+defaultLayoutName, now.Add(warnInterval-time.Second)) { t.Error("the warning gate did not hold a key for the interval") } if !g.allow("inline:"+defaultLayoutName, now.Add(warnInterval)) { t.Error("the warning gate did not repeat a key after the interval") } // The real inliner takes ordinary HTML without an error. if _, err := inlineCSS("

x

"); err != nil { t.Errorf("inlineCSS on plain HTML: %v", err) } }