Debian Codegraph @

tpl/internal/go_templates/htmltemplate/js_test.go

raw
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build !windows
6
7 package template
8
9 import (
10 "errors"
11 "math"
12 "strings"
13 "testing"
14 )
15
16 func TestNextJsCtx(t *testing.T) {
17 tests := []struct {
18 jsCtx jsCtx
19 s string
20 }{
21 // Statement terminators precede regexps.
22 {jsCtxRegexp, ";"},
23 // This is not airtight.
24 // ({ valueOf: function () { return 1 } } / 2)
25 // is valid JavaScript but in practice, devs do not do this.
26 // A block followed by a statement starting with a RegExp is
27 // much more common:
28 // while (x) {...} /foo/.test(x) || panic()
29 {jsCtxRegexp, "}"},
30 // But member, call, grouping, and array expression terminators
31 // precede div ops.
32 {jsCtxDivOp, ")"},
33 {jsCtxDivOp, "]"},
34 // At the start of a primary expression, array, or expression
35 // statement, expect a regexp.
36 {jsCtxRegexp, "("},
37 {jsCtxRegexp, "["},
38 {jsCtxRegexp, "{"},
39 // Assignment operators precede regexps as do all exclusively
40 // prefix and binary operators.
41 {jsCtxRegexp, "="},
42 {jsCtxRegexp, "+="},
43 {jsCtxRegexp, "*="},
44 {jsCtxRegexp, "*"},
45 {jsCtxRegexp, "!"},
46 // Whether the + or - is infix or prefix, it cannot precede a
47 // div op.
48 {jsCtxRegexp, "+"},
49 {jsCtxRegexp, "-"},
50 // An incr/decr op precedes a div operator.
51 // This is not airtight. In (g = ++/h/i) a regexp follows a
52 // pre-increment operator, but in practice devs do not try to
53 // increment or decrement regular expressions.
54 // (g++/h/i) where ++ is a postfix operator on g is much more
55 // common.
56 {jsCtxDivOp, "--"},
57 {jsCtxDivOp, "++"},
58 {jsCtxDivOp, "x--"},
59 // When we have many dashes or pluses, then they are grouped
60 // left to right.
61 {jsCtxRegexp, "x---"}, // A postfix -- then a -.
62 // return followed by a slash returns the regexp literal or the
63 // slash starts a regexp literal in an expression statement that
64 // is dead code.
65 {jsCtxRegexp, "return"},
66 {jsCtxRegexp, "return "},
67 {jsCtxRegexp, "return\t"},
68 {jsCtxRegexp, "return\n"},
69 {jsCtxRegexp, "return\u2028"},
70 // Identifiers can be divided and cannot validly be preceded by
71 // a regular expressions. Semicolon insertion cannot happen
72 // between an identifier and a regular expression on a new line
73 // because the one token lookahead for semicolon insertion has
74 // to conclude that it could be a div binary op and treat it as
75 // such.
76 {jsCtxDivOp, "x"},
77 {jsCtxDivOp, "x "},
78 {jsCtxDivOp, "x\t"},
79 {jsCtxDivOp, "x\n"},
80 {jsCtxDivOp, "x\u2028"},
81 {jsCtxDivOp, "preturn"},
82 // Numbers precede div ops.
83 {jsCtxDivOp, "0"},
84 // Dots that are part of a number are div preceders.
85 {jsCtxDivOp, "0."},
86 // Some JS interpreters treat NBSP as a normal space, so
87 // we must too in order to properly escape things.
88 {jsCtxRegexp, "=\u00A0"},
89 }
90
91 for _, test := range tests {
92 if ctx := nextJSCtx([]byte(test.s), jsCtxRegexp); ctx != test.jsCtx {
93 t.Errorf("%q: want %s got %s", test.s, test.jsCtx, ctx)
94 }
95 if ctx := nextJSCtx([]byte(test.s), jsCtxDivOp); ctx != test.jsCtx {
96 t.Errorf("%q: want %s got %s", test.s, test.jsCtx, ctx)
97 }
98 }
99
100 if nextJSCtx([]byte(" "), jsCtxRegexp) != jsCtxRegexp {
101 t.Error("Blank tokens")
102 }
103
104 if nextJSCtx([]byte(" "), jsCtxDivOp) != jsCtxDivOp {
105 t.Error("Blank tokens")
106 }
107 }
108
109 type jsonErrType struct{}
110
111 func (e *jsonErrType) MarshalJSON() ([]byte, error) {
112 return nil, errors.New("a */ b <script c </script d <!-- e <sCrIpT f </sCrIpT")
113 }
114
115 func TestJSValEscaper(t *testing.T) {
116 tests := []struct {
117 x any
118 js string
119 skipNest bool
120 }{
121 {int(42), " 42 ", false},
122 {uint(42), " 42 ", false},
123 {int16(42), " 42 ", false},
124 {uint16(42), " 42 ", false},
125 {int32(-42), " -42 ", false},
126 {uint32(42), " 42 ", false},
127 {int16(-42), " -42 ", false},
128 {uint16(42), " 42 ", false},
129 {int64(-42), " -42 ", false},
130 {uint64(42), " 42 ", false},
131 {uint64(1) << 53, " 9007199254740992 ", false},
132 // ulp(1 << 53) > 1 so this loses precision in JS
133 // but it is still a representable integer literal.
134 {uint64(1)<<53 + 1, " 9007199254740993 ", false},
135 {float32(1.0), " 1 ", false},
136 {float32(-1.0), " -1 ", false},
137 {float32(0.5), " 0.5 ", false},
138 {float32(-0.5), " -0.5 ", false},
139 {float32(1.0) / float32(256), " 0.00390625 ", false},
140 {float32(0), " 0 ", false},
141 {math.Copysign(0, -1), " -0 ", false},
142 {float64(1.0), " 1 ", false},
143 {float64(-1.0), " -1 ", false},
144 {float64(0.5), " 0.5 ", false},
145 {float64(-0.5), " -0.5 ", false},
146 {float64(0), " 0 ", false},
147 {math.Copysign(0, -1), " -0 ", false},
148 {"", `""`, false},
149 {"foo", `"foo"`, false},
150 // Newlines.
151 {"\r\n\u2028\u2029", `"\r\n\u2028\u2029"`, false},
152 // "\v" == "v" on IE 6 so use "\u000b" instead.
153 {"\t\x0b", `"\t\u000b"`, false},
154 {struct{ X, Y int }{1, 2}, `{"X":1,"Y":2}`, false},
155 {[]any{}, "[]", false},
156 {[]any{42, "foo", nil}, `[42,"foo",null]`, false},
157 {[]string{"<!--", "</script>", "-->"}, `["\u003c!--","\u003c/script\u003e","--\u003e"]`, false},
158 {"<!--", `"\u003c!--"`, false},
159 {"-->", `"--\u003e"`, false},
160 {"<![CDATA[", `"\u003c![CDATA["`, false},
161 {"]]>", `"]]\u003e"`, false},
162 {"</script", `"\u003c/script"`, false},
163 {"\U0001D11E", "\"\U0001D11E\"", false}, // or "\uD834\uDD1E"
164 {nil, " null ", false},
165 {&jsonErrType{}, " /* json: error calling MarshalJSON for type *template.jsonErrType: a * / b \\x3Cscript c \\x3C/script d \\x3C!-- e \\x3Cscript f \\x3C/script */null ", true},
166 }
167
168 for _, test := range tests {
169 if js := jsValEscaper(test.x); js != test.js {
170 t.Errorf("%+v: want\n\t%q\ngot\n\t%q", test.x, test.js, js)
171 }
172 if test.skipNest {
173 continue
174 }
175 // Make sure that escaping corner cases are not broken
176 // by nesting.
177 a := []any{test.x}
178 want := "[" + strings.TrimSpace(test.js) + "]"
179 if js := jsValEscaper(a); js != want {
180 t.Errorf("%+v: want\n\t%q\ngot\n\t%q", a, want, js)
181 }
182 }
183 }
184
185 func TestJSStrEscaper(t *testing.T) {
186 tests := []struct {
187 x any
188 esc string
189 }{
190 {"", ``},
191 {"foo", `foo`},
192 {"\u0000", `\u0000`},
193 {"\t", `\t`},
194 {"\n", `\n`},
195 {"\r", `\r`},
196 {"\u2028", `\u2028`},
197 {"\u2029", `\u2029`},
198 {"\\", `\\`},
199 {"\\n", `\\n`},
200 {"foo\r\nbar", `foo\r\nbar`},
201 // Preserve attribute boundaries.
202 {`"`, `\u0022`},
203 {`'`, `\u0027`},
204 // Allow embedding in HTML without further escaping.
205 {`&amp;`, `\u0026amp;`},
206 // Prevent breaking out of text node and element boundaries.
207 {"</script>", `\u003c\/script\u003e`},
208 {"<![CDATA[", `\u003c![CDATA[`},
209 {"]]>", `]]\u003e`},
210 // https://dev.w3.org/html5/markup/aria/syntax.html#escaping-text-span
211 // "The text in style, script, title, and textarea elements
212 // must not have an escaping text span start that is not
213 // followed by an escaping text span end."
214 // Furthermore, spoofing an escaping text span end could lead
215 // to different interpretation of a </script> sequence otherwise
216 // masked by the escaping text span, and spoofing a start could
217 // allow regular text content to be interpreted as script
218 // allowing script execution via a combination of a JS string
219 // injection followed by an HTML text injection.
220 {"<!--", `\u003c!--`},
221 {"-->", `--\u003e`},
222 // From https://code.google.com/p/doctype/wiki/ArticleUtf7
223 {"+ADw-script+AD4-alert(1)+ADw-/script+AD4-",
224 `\u002bADw-script\u002bAD4-alert(1)\u002bADw-\/script\u002bAD4-`,
225 },
226 // Invalid UTF-8 sequence
227 {"foo\xA0bar", "foo\xA0bar"},
228 // Invalid unicode scalar value.
229 {"foo\xed\xa0\x80bar", "foo\xed\xa0\x80bar"},
230 }
231
232 for _, test := range tests {
233 esc := jsStrEscaper(test.x)
234 if esc != test.esc {
235 t.Errorf("%q: want %q got %q", test.x, test.esc, esc)
236 }
237 }
238 }
239
240 func TestJSRegexpEscaper(t *testing.T) {
241 tests := []struct {
242 x any
243 esc string
244 }{
245 {"", `(?:)`},
246 {"foo", `foo`},
247 {"\u0000", `\u0000`},
248 {"\t", `\t`},
249 {"\n", `\n`},
250 {"\r", `\r`},
251 {"\u2028", `\u2028`},
252 {"\u2029", `\u2029`},
253 {"\\", `\\`},
254 {"\\n", `\\n`},
255 {"foo\r\nbar", `foo\r\nbar`},
256 // Preserve attribute boundaries.
257 {`"`, `\u0022`},
258 {`'`, `\u0027`},
259 // Allow embedding in HTML without further escaping.
260 {`&amp;`, `\u0026amp;`},
261 // Prevent breaking out of text node and element boundaries.
262 {"</script>", `\u003c\/script\u003e`},
263 {"<![CDATA[", `\u003c!\[CDATA\[`},
264 {"]]>", `\]\]\u003e`},
265 // Escaping text spans.
266 {"<!--", `\u003c!\-\-`},
267 {"-->", `\-\-\u003e`},
268 {"*", `\*`},
269 {"+", `\u002b`},
270 {"?", `\?`},
271 {"[](){}", `\[\]\(\)\{\}`},
272 {"$foo|x.y", `\$foo\|x\.y`},
273 {"x^y", `x\^y`},
274 }
275
276 for _, test := range tests {
277 esc := jsRegexpEscaper(test.x)
278 if esc != test.esc {
279 t.Errorf("%q: want %q got %q", test.x, test.esc, esc)
280 }
281 }
282 }
283
284 func TestEscapersOnLower7AndSelectHighCodepoints(t *testing.T) {
285 input := ("\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" +
286 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" +
287 ` !"#$%&'()*+,-./` +
288 `0123456789:;<=>?` +
289 `@ABCDEFGHIJKLMNO` +
290 `PQRSTUVWXYZ[\]^_` +
291 "`abcdefghijklmno" +
292 "pqrstuvwxyz{|}~\x7f" +
293 "\u00A0\u0100\u2028\u2029\ufeff\U0001D11E")
294
295 tests := []struct {
296 name string
297 escaper func(...any) string
298 escaped string
299 }{
300 {
301 "jsStrEscaper",
302 jsStrEscaper,
303 `\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007` +
304 `\u0008\t\n\u000b\f\r\u000e\u000f` +
305 `\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017` +
306 `\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f` +
307 ` !\u0022#$%\u0026\u0027()*\u002b,-.\/` +
308 `0123456789:;\u003c=\u003e?` +
309 `@ABCDEFGHIJKLMNO` +
310 `PQRSTUVWXYZ[\\]^_` +
311 "\\u0060abcdefghijklmno" +
312 "pqrstuvwxyz{|}~\u007f" +
313 "\u00A0\u0100\\u2028\\u2029\ufeff\U0001D11E",
314 },
315 {
316 "jsRegexpEscaper",
317 jsRegexpEscaper,
318 `\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007` +
319 `\u0008\t\n\u000b\f\r\u000e\u000f` +
320 `\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017` +
321 `\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f` +
322 ` !\u0022#\$%\u0026\u0027\(\)\*\u002b,\-\.\/` +
323 `0123456789:;\u003c=\u003e\?` +
324 `@ABCDEFGHIJKLMNO` +
325 `PQRSTUVWXYZ\[\\\]\^_` +
326 "`abcdefghijklmno" +
327 `pqrstuvwxyz\{\|\}~` + "\u007f" +
328 "\u00A0\u0100\\u2028\\u2029\ufeff\U0001D11E",
329 },
330 }
331
332 for _, test := range tests {
333 if s := test.escaper(input); s != test.escaped {
334 t.Errorf("%s once: want\n\t%q\ngot\n\t%q", test.name, test.escaped, s)
335 continue
336 }
337
338 // Escape it rune by rune to make sure that any
339 // fast-path checking does not break escaping.
340 var buf strings.Builder
341 for _, c := range input {
342 buf.WriteString(test.escaper(string(c)))
343 }
344
345 if s := buf.String(); s != test.escaped {
346 t.Errorf("%s rune-wise: want\n\t%q\ngot\n\t%q", test.name, test.escaped, s)
347 continue
348 }
349 }
350 }
351
352 func TestIsJsMimeType(t *testing.T) {
353 tests := []struct {
354 in string
355 out bool
356 }{
357 {"application/javascript;version=1.8", true},
358 {"application/javascript;version=1.8;foo=bar", true},
359 {"application/javascript/version=1.8", false},
360 {"text/javascript", true},
361 {"application/json", true},
362 {"application/ld+json", true},
363 {"module", true},
364 }
365
366 for _, test := range tests {
367 if isJSType(test.in) != test.out {
368 t.Errorf("isJSType(%q) = %v, want %v", test.in, !test.out, test.out)
369 }
370 }
371 }
372
373 func BenchmarkJSValEscaperWithNum(b *testing.B) {
374 for i := 0; i < b.N; i++ {
375 jsValEscaper(3.141592654)
376 }
377 }
378
379 func BenchmarkJSValEscaperWithStr(b *testing.B) {
380 for i := 0; i < b.N; i++ {
381 jsValEscaper("The <i>quick</i>,\r\n<span style='color:brown'>brown</span> fox jumps\u2028over the <canine class=\"lazy\">dog</canine>")
382 }
383 }
384
385 func BenchmarkJSValEscaperWithStrNoSpecials(b *testing.B) {
386 for i := 0; i < b.N; i++ {
387 jsValEscaper("The quick, brown fox jumps over the lazy dog")
388 }
389 }
390
391 func BenchmarkJSValEscaperWithObj(b *testing.B) {
392 o := struct {
393 S string
394 N int
395 }{
396 "The <i>quick</i>,\r\n<span style='color:brown'>brown</span> fox jumps\u2028over the <canine class=\"lazy\">dog</canine>\u2028",
397 42,
398 }
399 for i := 0; i < b.N; i++ {
400 jsValEscaper(o)
401 }
402 }
403
404 func BenchmarkJSValEscaperWithObjNoSpecials(b *testing.B) {
405 o := struct {
406 S string
407 N int
408 }{
409 "The quick, brown fox jumps over the lazy dog",
410 42,
411 }
412 for i := 0; i < b.N; i++ {
413 jsValEscaper(o)
414 }
415 }
416
417 func BenchmarkJSStrEscaperNoSpecials(b *testing.B) {
418 for i := 0; i < b.N; i++ {
419 jsStrEscaper("The quick, brown fox jumps over the lazy dog.")
420 }
421 }
422
423 func BenchmarkJSStrEscaper(b *testing.B) {
424 for i := 0; i < b.N; i++ {
425 jsStrEscaper("The <i>quick</i>,\r\n<span style='color:brown'>brown</span> fox jumps\u2028over the <canine class=\"lazy\">dog</canine>")
426 }
427 }
428
429 func BenchmarkJSRegexpEscaperNoSpecials(b *testing.B) {
430 for i := 0; i < b.N; i++ {
431 jsRegexpEscaper("The quick, brown fox jumps over the lazy dog")
432 }
433 }
434
435 func BenchmarkJSRegexpEscaper(b *testing.B) {
436 for i := 0; i < b.N; i++ {
437 jsRegexpEscaper("The <i>quick</i>,\r\n<span style='color:brown'>brown</span> fox jumps\u2028over the <canine class=\"lazy\">dog</canine>")
438 }
439 }