package postcard import ( "context" "strings" "testing" "testing/fstest" ) // siteNameLayouts are the site-name fixture's templates on the default and // the system layout, with a text of their file version. var siteNameLayouts = []struct{ layout, template, fileText string }{ {"default", "acme.site::mail.hello", "Hi Ada."}, {"system", "acme.site::mail.notice", "Notice for Ada."}, } // siteNamePaths are the three ways a send renders: the file version (the // Branding only), a template override, and an override that fails to render // (it reads a field of a variable the caller does not pass), which sends the // file version. var siteNamePaths = []struct { name string template *TemplateOverride // want is a text the sent HTML holds on this path. want string // fallback is whether the override failure is logged. fallback bool }{ {name: "file_version"}, {name: "override", template: &TemplateOverride{Subject: "S", Body: "Override for **{{ .Name }}**."}, want: "Override for Ada."}, {name: "override_fallback", template: &TemplateOverride{Subject: "S", Body: "Order {{ .order.code }}"}, fallback: true}, } // siteNameMailer is a mailer over a small catalog with one template on the // default layout and one on the system layout, with the given overrides. func siteNameMailer(t *testing.T, opts Options, ov *Overrides) (Mailer, *MemoryDriver) { t.Helper() fsys := fstest.MapFS{ "views/mail/hello.htm": {Data: []byte("subject = \"Hello\"\n==\nHi {{ .Name }}.\n")}, "views/mail/notice.htm": {Data: []byte("subject = \"Notice\"\nlayout = \"system\"\n==\nNotice for {{ .Name }}.\n")}, } cat := NewCatalog() if err := cat.Register("acme.site", fsys, []string{"acme.site::mail.hello", "acme.site::mail.notice"}, nil); err != nil { t.Fatalf("Register: %v", err) } if ov != nil { opts.Overrides = fakeOverrides{ov: *ov} } drv := NewMemoryDriver() return NewMailer(cat, drv, opts), drv } // siteNameOverrides is the override answer for brand on path: nil when // there is neither. func siteNameOverrides(brand *Brand, tmpl *TemplateOverride) *Overrides { if brand == nil && tmpl == nil { return nil } return &Overrides{Brand: brand, Template: tmpl} } // assertPath checks that msg is what path sends for the fixture template: // the override's text, or the file version's. func assertPath(t *testing.T, msg RenderedMessage, fileText, want string, fallback bool, logs string) { t.Helper() if want == "" { want = fileText } if !strings.Contains(msg.HTML, want) { t.Errorf("the HTML lacks %q:\n%s", want, msg.HTML) } if fallback != strings.Contains(logs, "override failed, sending the file version") { t.Errorf("override failure logged = %v, want %v:\n%s", !fallback, fallback, logs) } } // siteNameWarnings counts the site-name warnings in logs. func siteNameWarnings(logs string) int { return strings.Count(logs, "site name left out of the layouts") } // TestSiteNameSend covers the CR-01 regression: a site name that reads as // prose with a colon, from mail.from or from the Branding, is shown in the // header and the footer of the built-in layouts and never stops a send, on // every render path. func TestSiteNameSend(t *testing.T) { t.Parallel() const from = `"Metadata: Weekly" ` sources := []struct { name string brand *Brand want string }{ {"mail_from", nil, "Metadata: Weekly"}, {"branding", &Brand{SiteName: "Big Data: Summit"}, "Big Data: Summit"}, } for _, l := range siteNameLayouts { for _, src := range sources { for _, p := range siteNamePaths { t.Run(l.layout+"/"+src.name+"/"+p.name, func(t *testing.T) { t.Parallel() m, drv := siteNameMailer(t, Options{From: from}, siteNameOverrides(src.brand, p.template)) logs := captureLog(m) msg := sendTemplate(t, m, drv, l.template, inlineVars) assertPath(t, msg, l.fileText, p.want, p.fallback, logs.String()) assertSiteName(t, msg, src.want) if n := siteNameWarnings(logs.String()); n != 0 { t.Errorf("%d site name warnings for a prose name:\n%s", n, logs) } }) } } t.Run(l.layout+"/prose_body", func(t *testing.T) { t.Parallel() ov := &Overrides{Brand: &Brand{SiteName: "Big Data: Summit"}, Template: &TemplateOverride{Subject: "S", Body: "See the metadata: field."}} m, drv := siteNameMailer(t, Options{From: from}, ov) logs := captureLog(m) msg := sendTemplate(t, m, drv, l.template, inlineVars) assertPath(t, msg, l.fileText, "See the metadata: field.", false, logs.String()) if !strings.Contains(msg.Text, "See the metadata: field.") { t.Errorf("the text part lacks the prose body:\n%s", msg.Text) } assertSiteName(t, msg, "Big Data: Summit") }) } } // TestUnsafeSiteNameDropped covers the render-time drop: a site name that // fails the safety check is left out of every render path with one warning // per minute that names the source and never the value, and the send // succeeds. The editor neither refuses saves under such a stored name nor // shows it in a preview. func TestUnsafeSiteNameDropped(t *testing.T) { t.Parallel() cases := []struct { name string brand string from string // want is the name shown; empty means no header row and a footer // with the year only. want string // bad are texts that must not reach the message. bad []string }{ {"script_branding", "javascript:alert(1)", "Acme ", "Acme", []string{"javascript:", "alert"}}, {"handler_branding", "Shop onclick=x", "Acme ", "Acme", []string{"onclick", "Shop"}}, {"both_unsafe", "javascript: Acme", `"vbscript:x" `, "", []string{"javascript:", "vbscript:", "Acme"}}, // Unsafe only where the layouts print it: the footer's "© " // puts whitespace before the on= (CR-01 residual). {"context_handler_branding", "Online=Shop", "Acme ", "Acme", []string{"Online"}}, {"context_handler_both", "onboarding=team", `"Online=Shop" `, "", []string{"onboarding", "Online"}}, } for _, l := range siteNameLayouts { for _, tc := range cases { for _, p := range siteNamePaths { t.Run(l.layout+"/"+tc.name+"/"+p.name, func(t *testing.T) { t.Parallel() m, drv := siteNameMailer(t, Options{From: tc.from}, siteNameOverrides(&Brand{SiteName: tc.brand}, p.template)) logs := captureLog(m) for range 2 { msg := sendTemplate(t, m, drv, l.template, inlineVars) assertPath(t, msg, l.fileText, p.want, p.fallback, logs.String()) if tc.want != "" { assertSiteName(t, msg, tc.want) } else { if cell, ok := headerCell(msg.HTML); ok { t.Errorf("a header row without a name or a logo: %q", cell) } if got := footerText(t, msg.HTML); got != copyright() { t.Errorf("footer = %q, want %q", got, copyright()) } } for _, bad := range tc.bad { if strings.Contains(msg.HTML, bad) || strings.Contains(msg.Text, bad) { t.Errorf("%q reached the message:\n%s\n%s", bad, msg.HTML, msg.Text) } } } out := logs.String() if n := siteNameWarnings(out); n != 1 { t.Errorf("%d site name warnings in two sends, want 1:\n%s", n, out) } if !strings.Contains(out, "source=branding") { t.Errorf("log = %q, want source=branding", out) } for _, bad := range tc.bad { if strings.Contains(out, bad) { t.Errorf("log = %q, holds the value %q", out, bad) } } }) } } } // No Branding, an unsafe mail.from display name: no name, and the // warning names mail.from. Configuration alone never stops a send. for _, l := range siteNameLayouts { for _, from := range []struct{ name, value string }{ {"script", "javascript: Acme"}, {"context_handler", "Online=Shop"}, {"context_handler_lower", "onboarding=team"}, } { t.Run(l.layout+"/mail_from_source/"+from.name, func(t *testing.T) { t.Parallel() m, drv := siteNameMailer(t, Options{From: `"` + from.value + `" `}, nil) logs := captureLog(m) msg := sendTemplate(t, m, drv, l.template, inlineVars) if got := footerText(t, msg.HTML); got != copyright() { t.Errorf("footer = %q, want %q", got, copyright()) } if strings.Contains(msg.HTML, from.value) || strings.Contains(msg.Text, from.value) { t.Errorf("%q reached the message:\n%s", from.value, msg.HTML) } if out := logs.String(); siteNameWarnings(out) != 1 || !strings.Contains(out, "source=mail.from") || strings.Contains(out, from.value) { t.Errorf("log = %q, want one warning naming mail.from and not the value", out) } }) } } t.Run("editor", func(t *testing.T) { t.Parallel() ctx := context.Background() ed, _ := newEditor(t, &Overrides{Brand: &Brand{SiteName: "javascript:alert(1)"}}) tmpl := Draft{Kind: KindTemplate, Name: editorWelcome, Subject: "Hi {{ .Name }}", Body: "Hi **{{ .Name }}**.", Layout: defaultLayoutName} if err := ed.Validate(ctx, tmpl); err != nil { t.Errorf("a template draft under an unsafe stored name was refused: %+v", err) } def, ok := NewCatalog().Layout(defaultLayoutName) if !ok { t.Fatal("no built-in default layout") } layout := Draft{Kind: KindLayout, Name: defaultLayoutName, HTML: def.HTML, Text: def.Text} if err := ed.Validate(ctx, layout); err != nil { t.Errorf("a layout draft under an unsafe stored name was refused: %+v", err) } for _, d := range []Draft{tmpl, layout} { prev, err := ed.Preview(ctx, d) if err != nil { t.Fatalf("preview of a %v draft under an unsafe stored name: %v", d.Kind, err) } if strings.Contains(prev.HTML, "javascript:") || strings.Contains(prev.Text, "javascript:") { t.Errorf("the %v preview shows the unsafe stored name:\n%s", d.Kind, prev.HTML) } } // A name unsafe only in the footer's context does not refuse a save // either (the template's layout renders the footer). edCtx, _ := newEditor(t, &Overrides{Brand: &Brand{SiteName: "Online=Shop"}}) if err := edCtx.Validate(ctx, tmpl); err != nil { t.Errorf("a template draft under a stored Online=Shop was refused: %+v", err) } if err := edCtx.Validate(ctx, layout); err != nil { t.Errorf("a layout draft under a stored Online=Shop was refused: %+v", err) } // A Branding draft with an unsafe name previews without it. prev, err := ed.Preview(ctx, Draft{Kind: KindBrand, Brand: &Brand{SiteName: "javascript: Acme"}}) if err != nil { t.Fatalf("Branding preview of an unsafe name: %v", err) } if strings.Contains(prev.HTML, "javascript:") || strings.Contains(prev.Text, "javascript:") || strings.Contains(prev.HTML, "Acme") { t.Errorf("the Branding preview shows the unsafe name:\n%s", prev.HTML) } if got := footerText(t, prev.HTML); got != copyright() { t.Errorf("Branding preview footer = %q, want %q", got, copyright()) } }) } // TestUnsafeText pins the rule a layout's printed text is held to: prose // with a colon is safe, a script URL at a scheme boundary, a data URL or // event-handler-shaped text is not. func TestUnsafeText(t *testing.T) { t.Parallel() for _, s := range []string{ "", "Acme", "Big Data: Summit", "Metadata: Weekly", "Metadata:Weekly", "Data: Summit", "Acme ", "*Acme*", "[x](https://example.com)", } { if UnsafeText(s) { t.Errorf("UnsafeText(%q) = true, want false", s) } } for _, s := range []string{ "javascript:alert(1)", "javascript: Acme", "JAVASCRIPT:x", "Go vbscript:msgbox(1)", "data:text/html,x", "Shop data:x", "Shop onclick=x", "x onload = 1", // Unsafe where the layouts print it, after "© ". "Online=Shop", "onboarding=team", } { if !UnsafeText(s) { t.Errorf("UnsafeText(%q) = false, want true", s) } } } // TestFooterSiteNameLiteral covers the literal footer (WR-01): the built-in // layouts print the site name as text, escaped, in the footer as in the // header, so Markdown or markup in a name is never rendered; the footer // partial's body argument is still Markdown. func TestFooterSiteNameLiteral(t *testing.T) { t.Parallel() names := []struct{ name, escaped string }{ {"*Acme*", "*Acme*"}, {"Acme ", "Acme <Studio>"}, {"[x](https://example.com)", "[x](https://example.com)"}, } for _, l := range siteNameLayouts { for _, n := range names { t.Run(l.layout+"/"+n.name, func(t *testing.T) { t.Parallel() m, drv := siteNameMailer(t, Options{}, &Overrides{Brand: &Brand{SiteName: n.name}}) logs := captureLog(m) msg := sendTemplate(t, m, drv, l.template, inlineVars) if got, want := footerText(t, msg.HTML), copyright()+" "+n.escaped; got != want { t.Errorf("footer = %q, want %q", got, want) } footer := footerTable(t, msg.HTML) for _, bad := range []string{"", "raw HTML omitted", "