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