fix(35): WR-02 drop the whole-document event-handler regex

validateHTML ran (?i)\son[a-z]+\s*= over the rendered document, text
included, so a variable such as "buy one = get one free" stopped its own
message, and it is what made Online=Shop in the footer a send failure.
The tokenizer walk refuses every on* attribute, and since CR-02 it also
reads raw-text element and comment content as markup, so the regex is
dropped. Text shaped like a handler is now sent; such site names are shown
and saved, and the Branding refusal copy no longer mentions onclick=.
This commit is contained in:
Jakub Zych
2026-11-14 17:37:52 +01:00
parent baba524caf
commit 31de2ff90f
11 changed files with 79 additions and 59 deletions

View File

@@ -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 <no-reply@acme.test>`), 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 `© <year> `. 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 `<template>-<locale>` where `<template>` is registered and `<locale>` 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 <name>`. So a plugin can pass `<template>-<locale>` 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&#58;..."` and `values="java&#9;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&#58;..."` and `values="java&#9;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).

View File

@@ -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
// "© <year> ", 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
// "© <year> " (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</p>") || !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:") {

View File

@@ -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"

View File

@@ -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"

View File

@@ -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 `<plugin>::mail.partials.<name>`, loaded from `views/mail/partials/<name>.htm` and declared through `pact.HasMailPartials`. Bodies and layouts call them with `{{ partial "<name>" "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&#58;` and `java&#9;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&#58;` and `java&#9;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 <no-reply@acme.test>`), 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 <Studio>` 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 `© <year> `) 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 `© <year> ` 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 `© <year> ` 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. |

View File

@@ -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 ![the button](data:image/png;base64,AAAA) to continue.",
}
for name, body := range cases {
logs.Reset()

View File

@@ -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 "© <year> "), 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)
}

View File

@@ -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 <Studio>", "*Acme*", "[x](https://example.com)"} {
for _, s := range []string{"", "Acme", "Big Data: Summit", "Metadata: Weekly", "Metadata:Weekly", "Acme <Studio>", "*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" <x@example.com>`}, &Overrides{Brand: &Brand{SiteName: "Shop onclick=x"}})
m, drv = partialsMailer(t, Options{From: `"javascript: Acme" <x@example.com>`}, &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)

View File

@@ -29,6 +29,10 @@ func TestURLSchemeCheck(t *testing.T) {
{"textarea_escaped_link", `<textarea>&lt;a href="javascript:x"&gt;</textarea>`},
{"title_escaped_link", `<svg><title>&lt;a href="javascript:x"&gt;</title></svg>`},
{"noscript_safe_link", `<noscript><a href="https://example.com/">Open</a></noscript>`},
// Text shaped like an event handler is text (WR-02).
{"prose_handler_shaped", `<p>Ada, buy one = get one free, online = yes</p>`},
{"footer_handler_shaped_name", `<p>© 2026 Online=Shop</p>`},
{"title_escaped_handler", `<svg><title>&lt;img onerror=x&gt;</title></svg>`},
{"outlook_conditional_vml", `<!--[if mso]><v:roundrect href="https://example.com/" style="height:40px"><w:anchorlock/></v:roundrect><![endif]-->`},
}
for _, tc := range accepts {
@@ -67,6 +71,7 @@ func TestURLSchemeCheck(t *testing.T) {
{"entity_first_letter", `<a href="&#106;avascript:alert(1)">x</a>`, `&#106;avascript:alert(1)`, schemeMsg},
{"tab_split", `<a href="java&#9;script:alert(1)">x</a>`, `java&#9;script:alert(1)`, schemeMsg},
{"newline_split", `<a href="java&#x0A;script:alert(1)">x</a>`, `java&#x0A;script:alert(1)`, schemeMsg},
{"handler_with_space", `<p class="x" onclick="x()">x</p>`, `onclick="x()"`, "event handlers"},
{"handler_without_space", `<img src="x.png"onerror="alert(1)">`, `onerror="alert(1)"`, "event handlers"},
// Raw-text element content that a mail client parses as markup
// (scripting off, foreign content in svg) (CR-02).

View File

@@ -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 "© <year> "), 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" <x@example.com>`
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" <x@example.com>`, nil, "Online=Shop"},
{"mail_from_handler_text_lower", `"onboarding=team" <x@example.com>`, 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 <x@example.com>", "Acme", []string{"javascript:", "alert"}},
{"handler_branding", "Shop onclick=x", "Acme <x@example.com>", "Acme", []string{"onclick", "Shop"}},
{"both_unsafe", "javascript: Acme", `"vbscript:x" <x@example.com>`, "", []string{"javascript:", "vbscript:", "Acme"}},
// Unsafe only where the layouts print it: the footer's "© <year> "
// puts whitespace before the on<letters>= (CR-01 residual).
{"context_handler_branding", "Online=Shop", "Acme <x@example.com>", "Acme", []string{"Online"}},
{"context_handler_both", "onboarding=team", `"Online=Shop" <x@example.com>`, "", []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 <Studio>",
"*Acme*",
"[x](https://example.com)",
// Text shaped like an event handler is text, also where the
// layouts print it, after "© <year> " (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 "© <year> ".
"Online=Shop",
"onboarding=team",
} {
if !UnsafeText(s) {
t.Errorf("UnsafeText(%q) = false, want true", s)

View File

@@ -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)
}