fix(postcard): check URL schemes in decoded attribute values, not in text

- validateHTML keeps the raw tag and handler regexes and reads the rest
  through unsafeMarkup: x/net/html tokenizer, decoded attribute values,
  prefix check on URL attributes, whole-value check on CSS, list
  attributes, meta content and comments; any on* attribute is refused
- text is not a URL: "Metadata: Weekly" or "Big Data: Summit" as a site
  name or body text no longer stops a send (CR-01)
- entity-encoded javascript: is refused whether or not the layout
  opts out of inlining (WR-05)
- draft layout CSS is checked as a style element
- fixtures that pinned prose as unsafe now carry markup-level URLs;
  the 35-07 subtest pinning an unsafe stored name is removed
- TestMailSafetySmoke prose_site_name and encoded_scheme
This commit is contained in:
Jakub Zych
2026-11-14 15:13:35 +01:00
parent 274dff4458
commit 13ab905f8d
11 changed files with 277 additions and 35 deletions

View File

@@ -89,18 +89,6 @@ func TestMailBrandSiteName(t *testing.T) {
t.Errorf("a send without a site name, a logo or a mail.from name has a header row:\n%s", got.HTML)
}
})
t.Run("unsafe_name_current_behaviour", func(t *testing.T) {
// Open item (35-06 threat flag): the site name is not checked for a
// URL scheme at save time. It is stored as typed; the rendered
// header then fails the safety check, so the preview refuses it.
env.expect(t, http.StatusOK, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": "javascript: Acme"})
rec := env.call(t, http.MethodPost, "/mail/preview", root, map[string]any{"mode": "branding", "id": 0, "values": map[string]any{"site_name": "javascript: Acme"}})
if rec.Code != http.StatusUnprocessableEntity {
t.Errorf("preview of an unsafe site name: status %d, want 422 (%s)", rec.Code, rec.Body.String())
}
env.expect(t, http.StatusOK, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": ""})
})
}
// inlineLayoutFiles is the blog fixture whose blog layout carries a style

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 or `javascript:`/`vbscript:`/`data:` URLs is rejected; 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 (`javascript&#58;` is `javascript:`); 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`.
- 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.
@@ -359,14 +359,14 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
|------|---------|
| `parse` | The content is not a valid template. |
| `render` | It does not render with the sample values and placeholders. |
| `unsafe` | It contains, or renders to, a script, iframe, object or embed tag, an inline event handler or a `javascript:`, `vbscript:` or `data:` address; a layout's CSS that would close the style block is refused the same way. `postcard.DraftError.Message` holds the text that matched. |
| `unsafe` | It contains, or renders to, a script, iframe, object or embed tag, an inline event handler or a `javascript:`, `vbscript:` or `data:` address in an attribute, a style or a comment (encoded or not); a layout's CSS that would close the style block is refused the same way. `postcard.DraftError.Message` holds the text that matched. |
| `subject_line` | The subject renders to more than one line. |
| `layout` | The template's layout code names no layout. |
| `partial` | A call names a partial that does not exist; `postcard.DraftError.Name` holds the name. |
| `no_content` | A layout wrapper does not use `{{ .Content }}`. |
| `colour` | A Branding colour is not a six-digit hexadecimal colour; the field is its column, such as `button_primary_bg`. |
`postcard.DraftError.Message` carries the template parser's, the renderer's or the safety check's own text and nothing else. The safety checks are the ones a send runs, so text such as `metadata:` is refused at save as it would be at send, and the message shows where. A template body is also refused when its source contains one of the unsafe tags, which Markdown would otherwise drop without notice.
`postcard.DraftError.Message` carries the template parser's, the renderer's or the safety check's own text and nothing else. The safety checks are the ones a send runs, and the message shows where. Text is not a URL, so prose such as `metadata:` or `Big Data: Summit` passes, while an encoded `href="javascript&#58;..."` is decoded and refused. A template body is also refused when its source contains one of the unsafe tags, which Markdown would otherwise drop without notice.
`postcard.Editor.Preview` and `postcard.Editor.SendDraft` return a draft problem as a `postcard.DraftError` too (use `errors.As`). `postcard.Editor.SendDraft` delivers the rendered draft to the one address it is given, through the mailer's driver and from `mail.from`.
@@ -466,7 +466,7 @@ mail:
## Dependencies
- SummerCMS modules: [backpack](../backpack/README.md), [compass](../compass/README.md), [diary](../diary/README.md) (component logger `postcard` when the app publishes no logger), [pact](../pact/README.md), and the `attach` package of [lagoon](../lagoon/README.md) (`attach.AbsolutePublicURL` and `attach.BlobKey` for the logo's URL; lagoon itself is not imported).
- Third-party: `github.com/wneessen/go-mail` (SMTP), `github.com/yuin/goldmark` (Markdown, and its table extension inside partials), `github.com/vanng822/go-premailer` (CSS inlining, pinned at v1.38.0; see `.planning/notes/2026-11-13-mail-layouts-css-inlining.md`), `gorm.io/gorm` (reading overrides), `github.com/go-gormigrate/gormigrate/v2` (the mail tables' migrations).
- Third-party: `github.com/wneessen/go-mail` (SMTP), `github.com/yuin/goldmark` (Markdown, and its table extension inside partials), `github.com/vanng822/go-premailer` (CSS inlining, pinned at v1.38.0; see `.planning/notes/2026-11-13-mail-layouts-css-inlining.md`), `golang.org/x/net/html` (tokenizing rendered HTML for the safety checks, already a framework dependency; see `.planning/notes/2026-11-14-mail-url-scheme-check.md`), `gorm.io/gorm` (reading overrides), `github.com/go-gormigrate/gormigrate/v2` (the mail tables' migrations).
- Standard library: `bytes`, `context`, `crypto/rand`, `crypto/sha256`, `database/sql`, `embed`, `encoding/hex`, `errors`, `fmt`, `html/template`, `io/fs`, `log/slog`, `net/mail`, `regexp`, `sort`, `strconv`, `strings`, `sync`, `text/template` (and `text/template/parse`), `time`.
- Tests additionally use `github.com/testcontainers/testcontainers-go` (Mailpit and Postgres containers), `gorm.io/driver/postgres` and `github.com/jackc/pgx/v5`.

View File

@@ -244,8 +244,10 @@ func (e *Editor) renderLayout(d Draft, ov Overrides, opts renderOptions) (Render
if loc := closingStyle.FindStringIndex(d.CSS); loc != nil {
return RenderedMessage{}, &DraftError{Field: fieldContentCSS, Rule: ruleUnsafe, Message: snippetAt(d.CSS, loc)}
}
// The CSS is placed in a style element; check it as one, so the scheme
// check reads it.
var unsafe *unsafeError
if err := validateHTML(d.CSS); errors.As(err, &unsafe) {
if err := validateHTML("<style>" + d.CSS + "</style>"); errors.As(err, &unsafe) {
return RenderedMessage{}, &DraftError{Field: fieldContentCSS, Rule: ruleUnsafe, Message: unsafe.snippet}
}
// A wrapper that does not parse is reported by the render below.

View File

@@ -197,7 +197,9 @@ func TestMailEditorSmoke(t *testing.T) {
}
layout := Draft{Kind: KindLayout, Name: "promo", HTML: `<div class="promo">{{ .Content }}</div>`, Text: "{{ .Content }}", CSS: ".promo{margin:0}"}
partial := Draft{Kind: KindPartial, Name: editorNote, HTML: `<b>{{ .text }}</b>`, Text: "{{ .text }}"}
for name, d := range map[string]Draft{"layout": layout, "file layout": with(layout, func(d *Draft) { d.Name = editorBlogLayout }), "partial": partial, "empty template layout": with(ok, func(d *Draft) { d.Layout = "" })} {
for name, d := range map[string]Draft{"layout": layout, "file layout": with(layout, func(d *Draft) { d.Name = editorBlogLayout }), "partial": partial, "empty template layout": with(ok, func(d *Draft) { d.Layout = "" }),
// Text is not a URL: prose with a scheme-like word is not refused.
"prose body": with(ok, func(d *Draft) { d.Body = "See the metadata: field." })} {
if err := ed.Validate(ctx, d); err != nil {
t.Errorf("a valid %s draft was refused: %+v", name, err)
}
@@ -214,7 +216,7 @@ func TestMailEditorSmoke(t *testing.T) {
{"subject parse", with(ok, func(d *Draft) { d.Subject = "{{ .Name" }), "subject", "parse", "", ""},
{"body render", with(ok, func(d *Draft) { d.Body = "{{ len 5 }}" }), "body", "render", "len of type int", ""},
{"body script", with(ok, func(d *Draft) { d.Body = "Hi\n\n<script>alert(1)</script>" }), "body", "unsafe", "<script>alert(1)", ""},
{"body scheme", with(ok, func(d *Draft) { d.Body = "See the metadata: field." }), "body", "unsafe", "metadata: field", ""},
{"layout scheme", with(layout, func(d *Draft) { d.HTML += `<a href="javascript&#58;alert(1)">x</a>` }), "content_html", "unsafe", "javascript&#58;alert(1)", ""},
{"subject line", with(ok, func(d *Draft) { d.Subject = "Hi\nthere" }), "subject", "subject_line", "", ""},
{"unknown layout", with(ok, func(d *Draft) { d.Layout = "nope" }), "layout", "layout", "", ""},
{"unknown partial", with(ok, func(d *Draft) { d.Body = `{{ partial "nope" "a" "b" }}` }), "body", "partial", "", "postcard::mail.partials.nope"},

View File

@@ -430,8 +430,11 @@ func TestMailOverrideSmoke(t *testing.T) {
"runtime": "Order {{ .order.code }}",
// A body that does not parse.
"parse": "Hi {{ .name",
// A body that renders but fails the safety checks on the result.
"unsafe": "Type javascript: in the address bar.",
// 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.",
}
for name, body := range cases {
logs.Reset()

View File

@@ -149,9 +149,14 @@ func TestFallback(t *testing.T) {
}}}}, true)
})
t.Run("unsafe_override", func(t *testing.T) {
assertFileFallback(t, cat, file, Options{Overrides: fakeOverrides{ov: Overrides{Template: &TemplateOverride{
Subject: "Hello {{ .name }}", Body: "Type javascript: in the address bar.", Layout: "acme.blog::mail.layouts.blog",
}}}}, true)
// The override selects a layout override whose wrapper holds an
// entity-encoded javascript: link; the check reads it decoded.
assertFileFallback(t, cat, file, Options{Overrides: fakeOverrides{ov: Overrides{
Template: &TemplateOverride{Subject: "Hello {{ .name }}", Body: "Hi **{{ .name }}**.", Layout: "unsafe"},
Layouts: map[string]LayoutOverride{
"unsafe": {HTML: `<div>{{ .Content }}<a href="javascript&#58;alert(1)">x</a></div>`, Text: "{{ .Content }}"},
},
}}}, true)
})
t.Run("lookup_error", func(t *testing.T) {
drv := NewMemoryDriver()

View File

@@ -320,15 +320,23 @@ func TestMailPartialsSmoke(t *testing.T) {
body string
want []string
}{
"unknown": {`{{ partial "nope" "a" "b" }}`, []string{"unknown partial", "postcard::mail.partials.nope"}},
"unknown_ns": {`{{ partial "acme.blog::mail.partials.nope" }}`, []string{"unknown partial", "acme.blog::mail.partials.nope"}},
"odd": {`{{ partial "button" "url" }}`, []string{"postcard::mail.partials.button", "key and a value"}},
"key_type": {`{{ partial "button" 1 "x" }}`, []string{"postcard::mail.partials.button", "not a string"}},
"unsafe_html": {`{{ partial "panel" "body" "Type javascript: here" }}`, []string{"dangerous"}},
"unknown": {`{{ partial "nope" "a" "b" }}`, []string{"unknown partial", "postcard::mail.partials.nope"}},
"unknown_ns": {`{{ partial "acme.blog::mail.partials.nope" }}`, []string{"unknown partial", "acme.blog::mail.partials.nope"}},
"odd": {`{{ partial "button" "url" }}`, []string{"postcard::mail.partials.button", "key and a value"}},
"key_type": {`{{ partial "button" 1 "x" }}`, []string{"postcard::mail.partials.button", "not a string"}},
// The partial's own markup carries an entity-encoded javascript:
// link; prose in a body is not a URL and passes.
"unsafe_html": {`{{ partial "acme.blog::mail.partials.link" "text" "Go" }}`, []string{"dangerous"}},
}
for name, tc := range cases {
cat := NewCatalog()
fsys := fstest.MapFS{"views/mail/x.htm": {Data: []byte("subject = \"X\"\n==\n" + tc.body + "\n")}}
fsys := fstest.MapFS{
"views/mail/x.htm": {Data: []byte("subject = \"X\"\n==\n" + tc.body + "\n")},
"views/mail/partials/link.htm": {Data: []byte("name = \"Link\"\n==\n{{ .text }}\n==\n<a href=\"javascript&#58;alert(1)\">{{ .text }}</a>\n")},
}
if err := cat.RegisterPartials("acme.blog", fsys, []string{"acme.blog::mail.partials.link"}); err != nil {
t.Fatalf("%s: RegisterPartials: %v", name, err)
}
if err := cat.Register("acme.blog", fsys, []string{"acme.blog::mail.x"}, nil); err != nil {
t.Fatalf("%s: Register: %v", name, err)
}

125
modules/postcard/safety.go Normal file
View File

@@ -0,0 +1,125 @@
package postcard
import (
"strings"
xhtml "golang.org/x/net/html"
)
// urlAttributes are the attributes that hold one URL. Their decoded value is
// refused when it starts with a script or data scheme.
var urlAttributes = map[string]bool{
"action": true,
"background": true,
"cite": true,
"codebase": true,
"data": true,
"dynsrc": true,
"formaction": true,
"href": true,
"icon": true,
"longdesc": true,
"lowsrc": true,
"manifest": true,
"poster": true,
"profile": true,
"src": true,
"usemap": true,
"xlink:href": true,
// SVG animation targets can set an href.
"from": true,
"to": true,
"by": true,
}
// urlListAttributes hold several URLs (or values that can be URLs). Their
// decoded value is refused when dangerousScheme matches anywhere in it.
var urlListAttributes = map[string]bool{
"srcset": true,
"ping": true,
"archive": true,
"values": true,
}
// hasDangerousScheme reports whether a decoded URL attribute value starts
// with javascript:, vbscript: or data:, after every ASCII whitespace and
// control character is removed and the value is lower-cased, the way
// browsers read it ("java\tscript:" is javascript:).
func hasDangerousScheme(val string) bool {
var b strings.Builder
b.Grow(len(val))
for i := 0; i < len(val); i++ {
c := val[i]
if c <= 0x20 || c == 0x7f {
continue
}
if 'A' <= c && c <= 'Z' {
c += 'a' - 'A'
}
b.WriteByte(c)
}
v := b.String()
return strings.HasPrefix(v, "javascript:") || strings.HasPrefix(v, "vbscript:") || strings.HasPrefix(v, "data:")
}
// unsafeMarkup checks the markup of rendered HTML: event-handler attributes
// and javascript:, vbscript: or data: URLs. It reads doc with x/net/html's
// tokenizer, which lower-cases attribute names and decodes character
// references in attribute values, so href="javascript&#58;x" is read as a
// mail client reads it.
//
// URL schemes are looked for only where a URL can be: single-URL attributes
// (urlAttributes, by prefix), list-valued attributes (urlListAttributes),
// style attributes, the content of meta elements, the text of style
// elements and comments (anywhere in the value). Text content is not a URL,
// so prose such as "metadata:" or "Big Data: Summit" is not checked. Any
// attribute whose name starts with "on" is an event handler, with or
// without whitespace before it.
func unsafeMarkup(doc string) error {
z := xhtml.NewTokenizer(strings.NewReader(doc))
offset := 0
inStyle := false
for {
tt := z.Next()
if tt == xhtml.ErrorToken {
return nil
}
start := offset
offset += len(z.Raw())
loc := []int{start, offset}
t := z.Token()
switch tt {
case xhtml.StartTagToken, xhtml.SelfClosingTagToken:
for _, a := range t.Attr {
key := a.Key
if a.Namespace != "" {
key = a.Namespace + ":" + a.Key
}
switch {
case strings.HasPrefix(key, "on"):
return &unsafeError{msg: "rendered HTML contains event handlers", snippet: snippetAt(doc, loc)}
case urlAttributes[key] && hasDangerousScheme(a.Val),
urlListAttributes[key] && dangerousScheme.MatchString(a.Val),
key == "style" && dangerousScheme.MatchString(a.Val),
t.Data == "meta" && key == "content" && dangerousScheme.MatchString(a.Val):
return &unsafeError{msg: "rendered HTML contains a dangerous URL scheme", snippet: snippetAt(doc, loc)}
}
}
if tt == xhtml.StartTagToken && t.Data == "style" {
inStyle = true
}
case xhtml.EndTagToken:
if t.Data == "style" {
inStyle = false
}
case xhtml.TextToken:
if inStyle && dangerousScheme.MatchString(t.Data) {
return &unsafeError{msg: "rendered HTML contains a dangerous URL scheme", snippet: snippetAt(doc, loc)}
}
case xhtml.CommentToken:
if dangerousScheme.MatchString(t.Data) {
return &unsafeError{msg: "rendered HTML contains a dangerous URL scheme", snippet: snippetAt(doc, loc)}
}
}
}
}

View File

@@ -0,0 +1,104 @@
package postcard
import (
"bytes"
"log/slog"
"strings"
"testing"
)
// safetyLayouts are the blog fixture's templates on the default and the
// system layout.
var safetyLayouts = []struct{ layout, template string }{
{"default", "acme.blog::mail.welcome"},
{"system", "acme.blog::mail.auto"},
}
// captureLog points a mailer's log at a buffer and returns it.
func captureLog(m Mailer) *bytes.Buffer {
var logs bytes.Buffer
m.(*mailer).log = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
return &logs
}
// assertSiteName checks that msg shows name in its header, its footer and
// its text part.
func assertSiteName(t *testing.T, msg RenderedMessage, name string) {
t.Helper()
cell, ok := headerCell(msg.HTML)
if !ok {
t.Fatalf("no header row:\n%s", msg.HTML)
}
if m := logoSpan.FindStringSubmatch(cell); m == nil || m[1] != name {
t.Errorf("header = %q, want the site name %q", cell, name)
}
if got, want := footerText(t, msg.HTML), copyright()+" "+name; got != want {
t.Errorf("footer = %q, want %q", got, want)
}
if !strings.Contains(msg.Text, name) {
t.Errorf("text part lacks %q:\n%s", name, msg.Text)
}
}
// TestMailSafetySmoke covers the 35-08 gap closure: prose in a site name or
// a body is not a URL, encoded script URLs are refused, unsafe site names
// never stop a send, the inliner never stops mail and the footer prints the
// site name literally.
func TestMailSafetySmoke(t *testing.T) {
t.Parallel()
t.Run("prose_site_name", func(t *testing.T) {
const from = `"Metadata: Weekly" <x@example.com>`
brand := &Brand{SiteName: "Big Data: Summit"}
for _, l := range safetyLayouts {
// The display name of mail.from, no Branding: the file version.
m, drv := partialsMailer(t, Options{From: from}, nil)
assertSiteName(t, sendTemplate(t, m, drv, l.template, inlineVars), "Metadata: Weekly")
// The Branding name, still the file version.
m, drv = partialsMailer(t, Options{From: from}, &Overrides{Brand: brand})
assertSiteName(t, sendTemplate(t, m, drv, l.template, inlineVars), "Big Data: Summit")
// A template override as well: the override path.
m, drv = partialsMailer(t, Options{From: from}, &Overrides{Brand: brand, Template: &TemplateOverride{Subject: "S", Body: "Override **{{ .Name }}**."}})
msg := sendTemplate(t, m, drv, l.template, inlineVars)
if !strings.Contains(msg.HTML, "Override <strong>Ada</strong>") {
t.Fatalf("%s: the override was not sent:\n%s", l.layout, msg.HTML)
}
assertSiteName(t, msg, "Big Data: Summit")
// Prose with a scheme-like word in a body is not a URL.
m, drv = partialsMailer(t, Options{From: from}, &Overrides{Brand: brand, Template: &TemplateOverride{Subject: "S", Body: "See the metadata: field."}})
msg = sendTemplate(t, m, drv, l.template, inlineVars)
if !strings.Contains(msg.HTML, "See the metadata: field.") {
t.Fatalf("%s: the prose body was not sent:\n%s", l.layout, msg.HTML)
}
}
})
t.Run("encoded_scheme", func(t *testing.T) {
fileMailer, fileDrv := partialsMailer(t, Options{}, nil)
file := sendTemplate(t, fileMailer, fileDrv, "acme.blog::mail.welcome", inlineVars)
for _, optOut := range []bool{false, true} {
ov := &Overrides{Layouts: map[string]LayoutOverride{defaultLayoutName: {
HTML: `<div>{{ .Content }}<a href="javascript&#58;alert(1)">x</a></div>`,
Text: "{{ .Content }}",
DisableAutoInlineCSS: optOut,
}}}
m, drv := partialsMailer(t, Options{}, ov)
logs := captureLog(m)
got := sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars)
if got.HTML != file.HTML || got.Text != file.Text {
t.Errorf("opt-out %v: the file version was not sent:\n%s", optOut, got.HTML)
}
for _, msg := range drv.Messages() {
if strings.Contains(msg.HTML, "javascript") || strings.Contains(msg.HTML, "&#58;") {
t.Errorf("opt-out %v: the encoded link reached the driver:\n%s", optOut, msg.HTML)
}
}
if !strings.Contains(logs.String(), "override failed") || !strings.Contains(logs.String(), "dangerous URL scheme") {
t.Errorf("opt-out %v: log = %q, want the override failure", optOut, logs)
}
}
})
}

View File

@@ -42,6 +42,9 @@ var builtinLayoutAliases = map[string]string{
var builtinPartials = []string{"button", "panel", "subcopy", "table", "header", "footer"}
var (
// dangerousScheme finds a script or data URL scheme anywhere in a value.
// 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`)
@@ -810,6 +813,11 @@ func markdownHTML(src string) (string, error) {
return buf.String(), nil
}
// 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.
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)}
@@ -817,10 +825,7 @@ func validateHTML(html string) error {
if loc := eventHandler.FindStringIndex(html); loc != nil {
return &unsafeError{msg: "rendered HTML contains event handlers", snippet: snippetAt(html, loc)}
}
if loc := dangerousScheme.FindStringIndex(html); loc != nil {
return &unsafeError{msg: "rendered HTML contains a dangerous URL scheme", snippet: snippetAt(html, loc)}
}
return nil
return unsafeMarkup(html)
}
// snippetAt returns the match at loc with up to snippetContext bytes on