diff --git a/docs/services/mail.md b/docs/services/mail.md
index bdf3ef8e..fb32dfb2 100644
--- a/docs/services/mail.md
+++ b/docs/services/mail.md
@@ -85,7 +85,7 @@ The settings also hold a logo. A layout shows it where it uses `{{ .logoUrl }}`:
The settings also hold a site name, given to layouts as `{{ .siteName }}`. The built-in layouts show it in the header (as the logo's alternative text when there is a logo) and in the footer. Left empty, the display name of `mail.from` is used (`Acme` for `Acme `), so mail from an application that never saved Branding still carries a name.
-A site name mail could not show safely is refused when the settings are saved: one holding a `javascript:`, `vbscript:` or `data:` address, or text that would read as markup where the layouts print it, such as `onclick=`, or `Online=Shop`, which the footer prints after `© `. Ordinary text with a colon, such as `Big Data: Summit`, is accepted. A name stored before this check, or a `mail.from` display name of that kind, is left out of mail at send time (the next name in line is used, or none), with a warning in the log; the message is still sent.
+A site name mail could not show safely is refused when the settings are saved: one holding a `javascript:`, `vbscript:` or `data:` address. Ordinary text with a colon, such as `Big Data: Summit`, and text such as `Online=Shop` or `onclick=` are accepted: the layouts print the name as escaped text. A name stored before this check, or a `mail.from` display name of that kind, is left out of mail at send time (the next name in line is used, or none), with a warning in the log; the message is still sent.
A mail client needs an absolute address, so the logo's URL is built at send time from the configuration: `storage.uploads.public_url` when it is set, otherwise `app.url` with `storage.uploads.public_path_prefix`; see [Absolute URLs for mail](storage.md#absolute-urls-for-mail). Set one of them, or the logo is left out and a warning is logged.
@@ -155,7 +155,7 @@ fmt.Println(err != nil, len(driver.Messages()))
postcard does not pick a locale: the caller passes the full name. A per-language version of a template is a file named after the template, a dash and the locale (`welcome-en.htm`, sent as `acme.blog::mail.welcome-en`). A name with its own file always renders that file. A name the catalog does not hold, of the form `-` where `` is registered and `` is a locale tag (two letters, optionally followed by `-` or `_` and a 2 to 8 character subtag, such as `de` or `pt-BR`), sends the default-locale version: the locale's own version when an administrator customized it, else the customized template, else the template's file. Any other unknown name fails with `postcard: unknown template `. So a plugin can pass `-` for every locale it serves, and a locale without a file still sends mail, in the default language until someone writes that locale's version in the admin.
-Before a driver sees a message, postcard refuses a subject or address with a line break, parses every address with `net/mail`, and rejects rendered HTML that contains script, iframe, object or embed tags, inline event handlers, or `javascript:`, `vbscript:` or `data:` URLs. URLs are looked for where a mail client reads one: URL-bearing attributes such as `href` and `src`, `style` attributes, style elements, comments and `meta` content, after character references are decoded and whitespace removed, so `href="javascript:..."` and `values="java script:..."` are refused. Markup inside `noscript`, `title`, `textarea`, `style`, `xmp` and similar elements, and inside comments, is checked as well, since a mail client may read it as markup. Text is not a URL: a body or a site name such as `metadata:` or `Big Data: Summit` is sent. Variables are escaped by Go's `html/template`.
+Before a driver sees a message, postcard refuses a subject or address with a line break, parses every address with `net/mail`, and rejects rendered HTML that contains script, iframe, object or embed tags, inline event handlers, or `javascript:`, `vbscript:` or `data:` URLs. URLs are looked for where a mail client reads one: URL-bearing attributes such as `href` and `src`, `style` attributes, style elements, comments and `meta` content, after character references are decoded and whitespace removed, so `href="javascript:..."` and `values="java script:..."` are refused. Markup inside `noscript`, `title`, `textarea`, `style`, `xmp` and similar elements, and inside comments, is checked as well, since a mail client may read it as markup. Text is neither markup nor a URL: a body, a variable or a site name such as `metadata:`, `Big Data: Summit` or `buy one = get one free` is sent; only attributes count as event handlers. Variables are escaped by Go's `html/template`.
`postcard.Mailer.Send` delivers before it returns. To keep a request fast, send from a queued job, and send after the write that triggered the mail has committed; see [Queued jobs](jobs.md) and [Transactions](../database/transactions.md).
diff --git a/modules/cabana/mail_site_name_postgres_test.go b/modules/cabana/mail_site_name_postgres_test.go
index a6699cbd..12dbc1ce 100644
--- a/modules/cabana/mail_site_name_postgres_test.go
+++ b/modules/cabana/mail_site_name_postgres_test.go
@@ -82,19 +82,12 @@ func TestMailSiteNameSafety(t *testing.T) {
if got := storedSiteName(t, env); got != "Acme Mail" {
t.Fatalf("the refused pl save stored site_name %q", got)
}
-
- // A name unsafe only where the layouts print it, after the footer's
- // "© ", is refused as well (CR-01 residual).
- for _, name := range []string{"Online=Shop", "onboarding=team"} {
- env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": name}, "site_name", "cannot be shown in mail", false)
- if got := storedSiteName(t, env); got != "Acme Mail" {
- t.Fatalf("the refused save of %q stored site_name %q", name, got)
- }
- }
})
t.Run("prose_names_saved", func(t *testing.T) {
- for _, name := range []string{"Big Data: Summit", "Metadata: Weekly"} {
+ // Text shaped like an event handler is text, also after the footer's
+ // "© " (CR-01 residual, WR-02).
+ for _, name := range []string{"Big Data: Summit", "Metadata: Weekly", "Online=Shop", "onboarding=team"} {
saved := env.expect(t, http.StatusOK, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": name})
if got := dataOf(saved)["data"].(map[string]any)["site_name"]; got != name {
t.Errorf("response site_name = %#v, want %q", got, name)
@@ -106,6 +99,19 @@ func TestMailSiteNameSafety(t *testing.T) {
env.expect(t, http.StatusOK, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": "Acme Mail"})
})
+ t.Run("handler_shaped_name_sends", func(t *testing.T) {
+ env.expect(t, http.StatusOK, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": "Online=Shop"})
+ t.Cleanup(func() {
+ env.expect(t, http.StatusOK, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": "Acme Mail"})
+ })
+ for _, layout := range []string{mailDefaultLayout, mailSystemLayout} {
+ got := moveWelcome(t, env, root, layout)
+ if !strings.Contains(got.HTML, "Online=Shop
") || !strings.Contains(got.Text, "Online=Shop") {
+ t.Errorf("%s: the footer does not show the saved name:\n%s\n%s", layout, got.HTML, got.Text)
+ }
+ }
+ })
+
t.Run("preview_drops_unsafe_name", func(t *testing.T) {
html := brandPreview(t, env, root, map[string]any{"site_name": "javascript: Acme"})
if strings.Contains(html, "javascript:") {
diff --git a/modules/phrasebook/backend/lang/en/lang.yaml b/modules/phrasebook/backend/lang/en/lang.yaml
index d4c05dfb..1fb36186 100644
--- a/modules/phrasebook/backend/lang/en/lang.yaml
+++ b/modules/phrasebook/backend/lang/en/lang.yaml
@@ -703,7 +703,7 @@ mail:
logo_comment: "The built-in layouts show the logo in their header. Your own layouts show it where they use {{ .logoUrl }}."
site_name: "Site name"
site_name_comment: "Shown in the header and footer of the built-in layouts. Leave it empty to use the sender name from mail.from."
- site_name_unsafe: "This name cannot be shown in mail. Remove addresses that start with javascript:, vbscript: or data: and text such as onclick=."
+ site_name_unsafe: "This name cannot be shown in mail. Remove addresses that start with javascript:, vbscript: or data:."
body_bg: "Body background"
content_bg: "Content background"
header_color: "Header colour"
diff --git a/modules/phrasebook/backend/lang/pl/lang.yaml b/modules/phrasebook/backend/lang/pl/lang.yaml
index 0754ef4b..1f432a91 100644
--- a/modules/phrasebook/backend/lang/pl/lang.yaml
+++ b/modules/phrasebook/backend/lang/pl/lang.yaml
@@ -741,7 +741,7 @@ mail:
logo_comment: "Wbudowane układy pokazują logo w nagłówku. Własne układy pokazują je tam, gdzie używają {{ .logoUrl }}."
site_name: "Nazwa witryny"
site_name_comment: "Wyświetlana w nagłówku i stopce wbudowanych układów. Zostaw puste, aby użyć nazwy nadawcy z mail.from."
- site_name_unsafe: "Tej nazwy nie można pokazać w wiadomościach. Usuń adresy zaczynające się od javascript:, vbscript: lub data: oraz tekst w rodzaju onclick=."
+ site_name_unsafe: "Tej nazwy nie można pokazać w wiadomościach. Usuń adresy zaczynające się od javascript:, vbscript: lub data:."
body_bg: "Główne tło"
content_bg: "Tło treści"
header_color: "Kolor górnego nagłówka"
diff --git a/modules/postcard/README.md b/modules/postcard/README.md
index d783baaf..12c19797 100644
--- a/modules/postcard/README.md
+++ b/modules/postcard/README.md
@@ -27,7 +27,7 @@ Use cases:
- Layouts with a header, a text wrapper and an HTML wrapper, referenced from templates by a short alias (`pact.HasMailTemplates` maps aliases to full names). Three layouts are built in and usable from any plugin's templates: `default`, `system` and `minimal`.
- Partials: reusable blocks named `::mail.partials.`, loaded from `views/mail/partials/.htm` and declared through `pact.HasMailPartials`. Bodies and layouts call them with `{{ partial "" "key" value }}`. The partials `button`, `panel`, `table` and `subcopy` are built in.
- Every message gets an HTML part (Markdown converted with goldmark) and a plain-text part. The brand CSS (`mail.brandCss`, or the saved Branding) and `mail.css` go into the layout's style block, and the rendered HTML is then inlined: each CSS rule is copied into the `style` attribute of the elements it matches (go-premailer), so mail clients that drop style blocks still show the design. A layout opts out with `disable_auto_inline_css`.
-- Safety checks: rendered HTML with script, iframe, object or embed tags, inline event handlers (any attribute whose name starts with `on`) or `javascript:`/`vbscript:`/`data:` URLs is rejected. Schemes are looked for in URL-bearing attributes, `style` attributes, style elements, comments and `meta` content, after character references are decoded and whitespace and control characters removed (`javascript:` and `java script:` are `javascript:`). The content of `noscript`, `title`, `textarea`, `style`, `xmp` and the other raw-text elements, and of comments, is checked as markup too, because a mail client may read it so (scripting off, `svg` content, Outlook conditional comments); such elements nested more than eight deep are refused. Text is not a URL and is not checked for them. CR/LF in the subject or address headers is rejected; addresses are parsed with `net/mail`.
+- Safety checks: rendered HTML with script, iframe, object or embed tags, inline event handlers (any attribute whose name starts with `on`) or `javascript:`/`vbscript:`/`data:` URLs is rejected. Schemes are looked for in URL-bearing attributes, `style` attributes, style elements, comments and `meta` content, after character references are decoded and whitespace and control characters removed (`javascript:` and `java script:` are `javascript:`). The content of `noscript`, `title`, `textarea`, `style`, `xmp` and the other raw-text elements, and of comments, is checked as markup too, because a mail client may read it so (scripting off, `svg` content, Outlook conditional comments); such elements nested more than eight deep are refused. Text is neither markup nor a URL: it is not checked for schemes, and text shaped like an event handler (`buy one = get one free`, `online = yes`) is sent. CR/LF in the subject or address headers is rejected; addresses are parsed with `net/mail`.
- Drivers behind the `postcard.Driver` interface: `postcard.MemoryDriver` (keeps messages for tests), `postcard.LogDriver` (logs headers and the text part through `log/slog`, never the HTML or credentials), `postcard.SMTPDriver` (go-mail with an explicit TLS policy) and `postcard.FailDriver` (a deterministic failure for tests).
- Database overrides: a customized row of `system_mail_templates` replaces a template's subject, body and layout, a customized row of `system_mail_layouts` or `system_mail_partials` replaces a layout or a partial, and `system_mail_layouts` also holds layouts that exist only in the database. The mailer reads them on every send, with no cache, in every process that publishes a `*gorm.DB`. A missing database, tables that are not migrated yet, or an override that does not render or fails the safety checks sends the file version.
- Branding: once the branding settings have been saved, the brand CSS is compiled from their colours (`postcard.CompileBrandCSS`) and replaces `mail.brandCss`, and layouts get the logo's absolute URL as `{{ .logoUrl }}` and the site name as `{{ .siteName }}` (else the display name of `mail.from`). The built-in default layout shows them in a header and a copyright footer.
@@ -289,7 +289,7 @@ The row's `logo_file_id` names a public `system_files` row. Its URL is not store
The row's `site_name` column is `postcard.Brand.SiteName`. The built-in layouts show it in their header (as the logo's alternative text when there is a logo) and footer. While it is empty, and while no Branding row exists, `{{ .siteName }}` is the display name of `mail.from` parsed with `net/mail` (`Acme` for `Acme `), or empty when the address has none. The name is HTML-escaped by `html/template` wherever a layout prints it, and printed literally in the header and the footer (`*Acme*` and `Acme ` appear as typed).
-A name `postcard.UnsafeText` refuses (a `javascript:`, `vbscript:` or `data:` URL, or text that would read as markup where the layouts print it, such as `Shop onclick=x`, or `Online=Shop` after the footer's `© `) never reaches a layout and never stops a send: an unsafe Branding name is treated as empty, so the `mail.from` display name is used if that one is safe, and an unsafe `mail.from` display name gives no name. A warning naming the source (`branding` or `mail.from`), never the value, is logged at most once a minute per source. Prose such as `Big Data: Summit` is a name like any other. The Branding preview of an unsaved draft leaves such a name out the same way; the admin's Branding form refuses to save it.
+A name `postcard.UnsafeText` refuses (a `javascript:`, `vbscript:` or `data:` URL) never reaches a layout and never stops a send: an unsafe Branding name is treated as empty, so the `mail.from` display name is used if that one is safe, and an unsafe `mail.from` display name gives no name. A warning naming the source (`branding` or `mail.from`), never the value, is logged at most once a minute per source. Prose such as `Big Data: Summit`, and text shaped like an event handler such as `Online=Shop` or `Shop onclick=x`, is a name like any other: it is printed as escaped text, which is never markup. The Branding preview of an unsaved draft leaves such a name out the same way; the admin's Branding form refuses to save it.
A mail that falls back to its file version because an override failed still gets the Branding.
@@ -414,7 +414,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `postcard.Brand` | The Branding: thirteen colours, `postcard.Brand.LogoURL`, the logo's absolute URL, and `postcard.Brand.SiteName`, the name the built-in layouts show. |
| `postcard.DefaultBrand` | WinterCMS's default mail colours. |
| `postcard.CompileBrandCSS` | Checks a brand's colours and returns the brand CSS compiled from them. |
-| `postcard.UnsafeText` | Reports whether a text a layout prints, such as the site name, must be kept out of mail: it holds a `javascript:`, `vbscript:` or `data:` URL, or fails the rendered-HTML safety checks once HTML-escaped and placed where the built-in layouts print it (after `© ` in the footer, in the header). |
+| `postcard.UnsafeText` | Reports whether a text a layout prints, such as the site name, must be kept out of mail: it holds a `javascript:`, `vbscript:` or `data:` URL, or fails the rendered-HTML safety checks once HTML-escaped and placed where the built-in layouts print it (after `© ` in the footer, in the header). Event-handler-shaped text such as `Online=Shop` is safe. |
| `postcard.Migrations` | The gormigrate set that creates the mail tables; lagoon runs it under the `summercms.postcard` history. |
| `postcard.TemplatesTable`, `postcard.LayoutsTable`, `postcard.PartialsTable`, `postcard.BrandTable`, `postcard.ImageLibraryTable` | The names of the mail tables, for code that defines models over them. |
| `postcard.SyncIndex` | Upserts one index row per file template, layout and partial of a catalog; mirrors the file into rows that are not customized and refreshes `file_hash` and the template's `base_code` on all. |
diff --git a/modules/postcard/override_smoke_test.go b/modules/postcard/override_smoke_test.go
index 1033d16c..805fca43 100644
--- a/modules/postcard/override_smoke_test.go
+++ b/modules/postcard/override_smoke_test.go
@@ -431,10 +431,10 @@ func TestMailOverrideSmoke(t *testing.T) {
// A body that does not parse.
"parse": "Hi {{ .name",
// A body that renders but fails the safety checks on the result:
- // goldmark drops raw HTML and dangerous link targets, so a body
- // cannot produce a markup-level URL, but event-handler-shaped
- // text still fails the handler check.
- "unsafe": "Click the button onclick= to continue.",
+ // goldmark drops raw HTML and script link targets but keeps a
+ // data: image, which the scheme check refuses. Event-handler-shaped
+ // text is text and no longer fails.
+ "unsafe": "Click  to continue.",
}
for name, body := range cases {
logs.Reset()
diff --git a/modules/postcard/safety.go b/modules/postcard/safety.go
index dfa65f4e..9a2711b3 100644
--- a/modules/postcard/safety.go
+++ b/modules/postcard/safety.go
@@ -18,11 +18,10 @@ var scriptURLText = regexp.MustCompile(`(?i)(?:^|[^a-z0-9+.\-])(?:(?:javascript|
// UnsafeText reports whether a text that a layout prints, such as the site
// name of the built-in layouts, must be kept out of mail. A text is unsafe
// when, HTML-escaped as html/template prints text, it fails the rendered-HTML
-// safety checks in the places the built-in layouts print it (for example
-// event-handler-shaped text such as "Shop onclick=x", or "Online=Shop" after
-// the footer's "© "), or when it holds a script URL: javascript: or
-// vbscript: at a scheme boundary, or a data: URL. "Big Data: Summit" is safe;
-// "javascript: Acme" is not.
+// safety checks in the places the built-in layouts print it, or when it holds
+// a script URL: javascript: or vbscript: at a scheme boundary, or a data:
+// URL. Escaped text is never markup, so "Big Data: Summit", "Online=Shop" and
+// "Shop onclick=x" are safe; "javascript: Acme" is not.
func UnsafeText(s string) bool {
return validateHTML(printContext(html.EscapeString(s))) != nil || scriptURLText.MatchString(s)
}
diff --git a/modules/postcard/safety_smoke_test.go b/modules/postcard/safety_smoke_test.go
index c0c44891..af87b076 100644
--- a/modules/postcard/safety_smoke_test.go
+++ b/modules/postcard/safety_smoke_test.go
@@ -116,12 +116,12 @@ func TestMailSafetySmoke(t *testing.T) {
})
t.Run("unsafe_site_name", func(t *testing.T) {
ctx := context.Background()
- for _, s := range []string{"", "Acme", "Big Data: Summit", "Metadata: Weekly", "Metadata:Weekly", "Acme ", "*Acme*", "[x](https://example.com)"} {
+ for _, s := range []string{"", "Acme", "Big Data: Summit", "Metadata: Weekly", "Metadata:Weekly", "Acme ", "*Acme*", "[x](https://example.com)", "Shop onclick=x", "Online=Shop"} {
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 onclick=x"} {
+ for _, s := range []string{"javascript:alert(1)", "javascript: Acme", "JavaScript:x", "Go vbscript:msgbox(1)", "data:text/html,x"} {
if !UnsafeText(s) {
t.Errorf("UnsafeText(%q) = false, want true", s)
}
@@ -148,7 +148,7 @@ func TestMailSafetySmoke(t *testing.T) {
// Both names unsafe: no name at all, so no header row (no logo) and a
// footer with the year only.
- m, drv = partialsMailer(t, Options{From: `"javascript: Acme" `}, &Overrides{Brand: &Brand{SiteName: "Shop onclick=x"}})
+ m, drv = partialsMailer(t, Options{From: `"javascript: Acme" `}, &Overrides{Brand: &Brand{SiteName: "vbscript:msgbox(1)"}})
logs = captureLog(m)
msg := sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars)
if _, ok := headerCell(msg.HTML); ok {
@@ -157,14 +157,14 @@ func TestMailSafetySmoke(t *testing.T) {
if got := footerText(t, msg.HTML); got != copyright() {
t.Errorf("footer = %q, want %q", got, copyright())
}
- if out := logs.String(); !strings.Contains(out, "source=branding") || strings.Contains(out, "onclick") {
+ if out := logs.String(); !strings.Contains(out, "source=branding") || strings.Contains(out, "msgbox") {
t.Errorf("log = %q, want the branding source and not the value", out)
}
// The editor: saving a template or a layout under a stored unsafe
// name is not refused; the Branding preview of an unsafe draft name
// renders without it.
- ed, _ := newEditor(t, &Overrides{Brand: &Brand{SiteName: "Shop onclick=x"}})
+ ed, _ := newEditor(t, &Overrides{Brand: &Brand{SiteName: "vbscript:msgbox(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)
diff --git a/modules/postcard/safety_test.go b/modules/postcard/safety_test.go
index f311c180..71d8c489 100644
--- a/modules/postcard/safety_test.go
+++ b/modules/postcard/safety_test.go
@@ -29,6 +29,10 @@ func TestURLSchemeCheck(t *testing.T) {
{"textarea_escaped_link", ``},
{"title_escaped_link", ``},
{"noscript_safe_link", ``},
+ // Text shaped like an event handler is text (WR-02).
+ {"prose_handler_shaped", `Ada, buy one = get one free, online = yes
`},
+ {"footer_handler_shaped_name", `© 2026 Online=Shop
`},
+ {"title_escaped_handler", ``},
{"outlook_conditional_vml", ``},
}
for _, tc := range accepts {
@@ -67,6 +71,7 @@ func TestURLSchemeCheck(t *testing.T) {
{"entity_first_letter", `x`, `javascript:alert(1)`, schemeMsg},
{"tab_split", `x`, `java script:alert(1)`, schemeMsg},
{"newline_split", `x`, `java
script:alert(1)`, schemeMsg},
+ {"handler_with_space", `x
`, `onclick="x()"`, "event handlers"},
{"handler_without_space", `
`, `onerror="alert(1)"`, "event handlers"},
// Raw-text element content that a mail client parses as markup
// (scripting off, foreign content in svg) (CR-02).
diff --git a/modules/postcard/sitename_test.go b/modules/postcard/sitename_test.go
index 0c36fd8f..0f82a9f2 100644
--- a/modules/postcard/sitename_test.go
+++ b/modules/postcard/sitename_test.go
@@ -80,26 +80,33 @@ func siteNameWarnings(logs string) int {
}
// 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.
+// prose with a colon, or text shaped like an event handler (Online=Shop,
+// which the footer prints after "© "), 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
+ from string
brand *Brand
want string
}{
- {"mail_from", nil, "Metadata: Weekly"},
- {"branding", &Brand{SiteName: "Big Data: Summit"}, "Big Data: Summit"},
+ {"mail_from", from, nil, "Metadata: Weekly"},
+ {"branding", from, &Brand{SiteName: "Big Data: Summit"}, "Big Data: Summit"},
+ {"mail_from_handler_text", `"Online=Shop" `, nil, "Online=Shop"},
+ {"mail_from_handler_text_lower", `"onboarding=team" `, nil, "onboarding=team"},
+ {"branding_handler_text", from, &Brand{SiteName: "Online=Shop"}, "Online=Shop"},
+ {"branding_handler_text_lower", from, &Brand{SiteName: "onboarding=team"}, "onboarding=team"},
+ {"branding_handler_text_spaced", from, &Brand{SiteName: "Shop onclick=x"}, "Shop onclick=x"},
}
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))
+ m, drv := siteNameMailer(t, Options{From: src.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())
@@ -122,6 +129,17 @@ func TestSiteNameSend(t *testing.T) {
}
assertSiteName(t, msg, "Big Data: Summit")
})
+ // Text shaped like an event handler is text (WR-02): a variable such
+ // as a user's name never stops its own message.
+ t.Run(l.layout+"/handler_shaped_variable", func(t *testing.T) {
+ t.Parallel()
+ m, drv := siteNameMailer(t, Options{From: from}, nil)
+ const name = "Ada, buy one = get one free online = yes"
+ msg := sendTemplate(t, m, drv, l.template, map[string]any{"Name": name})
+ if !strings.Contains(msg.HTML, name) || !strings.Contains(msg.Text, name) {
+ t.Errorf("the message lacks %q:\n%s\n%s", name, msg.HTML, msg.Text)
+ }
+ })
}
}
@@ -143,12 +161,7 @@ func TestUnsafeSiteNameDropped(t *testing.T) {
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 {
@@ -198,8 +211,7 @@ func TestUnsafeSiteNameDropped(t *testing.T) {
for _, l := range siteNameLayouts {
for _, from := range []struct{ name, value string }{
{"script", "javascript: Acme"},
- {"context_handler", "Online=Shop"},
- {"context_handler_lower", "onboarding=team"},
+ {"vbscript", "vbscript:x"},
} {
t.Run(l.layout+"/mail_from_source/"+from.name, func(t *testing.T) {
t.Parallel()
@@ -270,8 +282,8 @@ func TestUnsafeSiteNameDropped(t *testing.T) {
}
// 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.
+// with a colon and event-handler-shaped text are safe, a script URL at a
+// scheme boundary or a data URL is not.
func TestUnsafeText(t *testing.T) {
t.Parallel()
for _, s := range []string{
@@ -284,6 +296,12 @@ func TestUnsafeText(t *testing.T) {
"Acme ",
"*Acme*",
"[x](https://example.com)",
+ // Text shaped like an event handler is text, also where the
+ // layouts print it, after "© " (CR-01, WR-02).
+ "Shop onclick=x",
+ "x onload = 1",
+ "Online=Shop",
+ "onboarding=team",
} {
if UnsafeText(s) {
t.Errorf("UnsafeText(%q) = true, want false", s)
@@ -296,11 +314,6 @@ func TestUnsafeText(t *testing.T) {
"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)
diff --git a/modules/postcard/templates.go b/modules/postcard/templates.go
index 55bc2168..0915493d 100644
--- a/modules/postcard/templates.go
+++ b/modules/postcard/templates.go
@@ -46,7 +46,6 @@ var (
// unsafeMarkup applies it to CSS (style attributes and style elements),
// list-valued URL attributes, meta content and comments, never to text.
dangerousScheme = regexp.MustCompile(`(?i)(?:javascript|vbscript|data):`)
- eventHandler = regexp.MustCompile(`(?i)\son[a-z]+\s*=`)
rawUnsafeTag = regexp.MustCompile(`(?i)<(?:script|iframe|object|embed)\b`)
markdown = goldmark.New()
@@ -819,17 +818,15 @@ func markdownHTML(src string) (string, error) {
}
// validateHTML is the safety check of rendered HTML. Raw unsafe tags
-// (script, iframe, object, embed) and whitespace-prefixed on* attributes are
-// found in the raw markup; unsafeMarkup then reads the decoded attribute
-// values, style elements and comments for event handlers and script or data
-// URLs. Text content is not a URL and is not checked for schemes.
+// (script, iframe, object, embed) are found in the raw markup; unsafeMarkup
+// then reads the attributes, style elements, comments and raw-text element
+// content for event handlers (any attribute whose name starts with "on")
+// and script or data URLs. Text content is neither markup nor a URL, so
+// prose such as "buy one = get one free" or "metadata:" is not refused.
func validateHTML(html string) error {
if loc := rawUnsafeTag.FindStringIndex(html); loc != nil {
return &unsafeError{msg: "rendered HTML contains raw unsafe tags", snippet: snippetAt(html, loc)}
}
- if loc := eventHandler.FindStringIndex(html); loc != nil {
- return &unsafeError{msg: "rendered HTML contains event handlers", snippet: snippetAt(html, loc)}
- }
return unsafeMarkup(html)
}