Fix Go template script escaping

Fixes #6695
This commit is contained in:
Bjørn Erik Pedersen
2020-05-23 15:32:27 +02:00
parent c34bf48560
commit 6c3c6686f5
27 changed files with 1090 additions and 292 deletions

View File

@@ -8,6 +8,7 @@ package template_test
import (
"bytes"
"encoding/json"
"strings"
"testing"
@@ -124,6 +125,44 @@ func TestNumbers(t *testing.T) {
c.mustExecute(c.root, nil, "12.34 7.5")
}
func TestStringsInScriptsWithJsonContentTypeAreCorrectlyEscaped(t *testing.T) {
// See #33671 and #37634 for more context on this.
tests := []struct{ name, in string }{
{"empty", ""},
{"invalid", string(rune(-1))},
{"null", "\u0000"},
{"unit separator", "\u001F"},
{"tab", "\t"},
{"gt and lt", "<>"},
{"quotes", `'"`},
{"ASCII letters", "ASCII letters"},
{"Unicode", "ʕ⊙ϖ⊙ʔ"},
{"Pizza", "🍕"},
}
const (
prefix = `<script type="application/ld+json">`
suffix = `</script>`
templ = prefix + `"{{.}}"` + suffix
)
tpl := Must(New("JS string is JSON string").Parse(templ))
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
if err := tpl.Execute(&buf, tt.in); err != nil {
t.Fatalf("Cannot render template: %v", err)
}
trimmed := bytes.TrimSuffix(bytes.TrimPrefix(buf.Bytes(), []byte(prefix)), []byte(suffix))
var got string
if err := json.Unmarshal(trimmed, &got); err != nil {
t.Fatalf("Cannot parse JS string %q as JSON: %v", trimmed[1:len(trimmed)-1], err)
}
if got != tt.in {
t.Errorf("Serialization changed the string value: got %q want %q", got, tt.in)
}
})
}
}
type testCase struct {
t *testing.T
root *Template