Debian Codegraph @

tpl/internal/go_templates/htmltemplate/escape_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 "bytes"
11 "encoding/json"
12 "fmt"
13 htmltemplate "html/template"
14 "os"
15 "strings"
16 "testing"
17
18 template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
19 "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
20 )
21
22 type badMarshaler struct{}
23
24 func (x *badMarshaler) MarshalJSON() ([]byte, error) {
25 // Keys in valid JSON must be double quoted as must all strings.
26 return []byte("{ foo: 'not quite valid JSON' }"), nil
27 }
28
29 type goodMarshaler struct{}
30
31 func (x *goodMarshaler) MarshalJSON() ([]byte, error) {
32 return []byte(`{ "<foo>": "O'Reilly" }`), nil
33 }
34
35 func TestEscape(t *testing.T) {
36 data := struct {
37 F, T bool
38 C, G, H, I string
39 A, E []string
40 B, M json.Marshaler
41 N int
42 U any // untyped nil
43 Z *int // typed nil
44 W htmltemplate.HTML
45 }{
46 F: false,
47 T: true,
48 C: "<Cincinnati>",
49 G: "<Goodbye>",
50 H: "<Hello>",
51 A: []string{"<a>", "<b>"},
52 E: []string{},
53 N: 42,
54 B: &badMarshaler{},
55 M: &goodMarshaler{},
56 U: nil,
57 Z: nil,
58 W: htmltemplate.HTML(`&iexcl;<b class="foo">Hello</b>, <textarea>O'World</textarea>!`),
59 I: "${ asd `` }",
60 }
61 pdata := &data
62
63 tests := []struct {
64 name string
65 input string
66 output string
67 }{
68 {
69 "if",
70 "{{if .T}}Hello{{end}}, {{.C}}!",
71 "Hello, &lt;Cincinnati&gt;!",
72 },
73 {
74 "else",
75 "{{if .F}}{{.H}}{{else}}{{.G}}{{end}}!",
76 "&lt;Goodbye&gt;!",
77 },
78 {
79 "overescaping1",
80 "Hello, {{.C | html}}!",
81 "Hello, &lt;Cincinnati&gt;!",
82 },
83 {
84 "overescaping2",
85 "Hello, {{html .C}}!",
86 "Hello, &lt;Cincinnati&gt;!",
87 },
88 {
89 "overescaping3",
90 "{{with .C}}{{$msg := .}}Hello, {{$msg}}!{{end}}",
91 "Hello, &lt;Cincinnati&gt;!",
92 },
93 {
94 "assignment",
95 "{{if $x := .H}}{{$x}}{{end}}",
96 "&lt;Hello&gt;",
97 },
98 {
99 "withBody",
100 "{{with .H}}{{.}}{{end}}",
101 "&lt;Hello&gt;",
102 },
103 {
104 "withElse",
105 "{{with .E}}{{.}}{{else}}{{.H}}{{end}}",
106 "&lt;Hello&gt;",
107 },
108 {
109 "rangeBody",
110 "{{range .A}}{{.}}{{end}}",
111 "&lt;a&gt;&lt;b&gt;",
112 },
113 {
114 "rangeElse",
115 "{{range .E}}{{.}}{{else}}{{.H}}{{end}}",
116 "&lt;Hello&gt;",
117 },
118 {
119 "nonStringValue",
120 "{{.T}}",
121 "true",
122 },
123 {
124 "untypedNilValue",
125 "{{.U}}",
126 "",
127 },
128 {
129 "typedNilValue",
130 "{{.Z}}",
131 "&lt;nil&gt;",
132 },
133 {
134 "constant",
135 `<a href="/search?q={{"'a<b'"}}">`,
136 `<a href="/search?q=%27a%3cb%27">`,
137 },
138 {
139 "multipleAttrs",
140 "<a b=1 c={{.H}}>",
141 "<a b=1 c=&lt;Hello&gt;>",
142 },
143 {
144 "urlStartRel",
145 `<a href='{{"/foo/bar?a=b&c=d"}}'>`,
146 `<a href='/foo/bar?a=b&amp;c=d'>`,
147 },
148 {
149 "urlStartAbsOk",
150 `<a href='{{"http://example.com/foo/bar?a=b&c=d"}}'>`,
151 `<a href='http://example.com/foo/bar?a=b&amp;c=d'>`,
152 },
153 {
154 "protocolRelativeURLStart",
155 `<a href='{{"//example.com:8000/foo/bar?a=b&c=d"}}'>`,
156 `<a href='//example.com:8000/foo/bar?a=b&amp;c=d'>`,
157 },
158 {
159 "pathRelativeURLStart",
160 `<a href="{{"/javascript:80/foo/bar"}}">`,
161 `<a href="/javascript:80/foo/bar">`,
162 },
163 {
164 "dangerousURLStart",
165 `<a href='{{"javascript:alert(%22pwned%22)"}}'>`,
166 `<a href='#ZgotmplZ'>`,
167 },
168 {
169 "dangerousURLStart2",
170 `<a href=' {{"javascript:alert(%22pwned%22)"}}'>`,
171 `<a href=' #ZgotmplZ'>`,
172 },
173 {
174 "nonHierURL",
175 `<a href={{"mailto:Muhammed \"The Greatest\" Ali <[email protected]>"}}>`,
176 `<a href=mailto:Muhammed%20%22The%20Greatest%22%20Ali%20%[email protected]%3e>`,
177 },
178 {
179 "urlPath",
180 `<a href='http://{{"javascript:80"}}/foo'>`,
181 `<a href='http://javascript:80/foo'>`,
182 },
183 {
184 "urlQuery",
185 `<a href='/search?q={{.H}}'>`,
186 `<a href='/search?q=%3cHello%3e'>`,
187 },
188 {
189 "urlFragment",
190 `<a href='/faq#{{.H}}'>`,
191 `<a href='/faq#%3cHello%3e'>`,
192 },
193 {
194 "urlBranch",
195 `<a href="{{if .F}}/foo?a=b{{else}}/bar{{end}}">`,
196 `<a href="/bar">`,
197 },
198 {
199 "urlBranchConflictMoot",
200 `<a href="{{if .T}}/foo?a={{else}}/bar#{{end}}{{.C}}">`,
201 `<a href="/foo?a=%3cCincinnati%3e">`,
202 },
203 {
204 "jsStrValue",
205 "<button onclick='alert({{.H}})'>",
206 `<button onclick='alert(&#34;\u003cHello\u003e&#34;)'>`,
207 },
208 {
209 "jsNumericValue",
210 "<button onclick='alert({{.N}})'>",
211 `<button onclick='alert( 42 )'>`,
212 },
213 {
214 "jsBoolValue",
215 "<button onclick='alert({{.T}})'>",
216 `<button onclick='alert( true )'>`,
217 },
218 {
219 "jsNilValueTyped",
220 "<button onclick='alert(typeof{{.Z}})'>",
221 `<button onclick='alert(typeof null )'>`,
222 },
223 {
224 "jsNilValueUntyped",
225 "<button onclick='alert(typeof{{.U}})'>",
226 `<button onclick='alert(typeof null )'>`,
227 },
228 {
229 "jsObjValue",
230 "<button onclick='alert({{.A}})'>",
231 `<button onclick='alert([&#34;\u003ca\u003e&#34;,&#34;\u003cb\u003e&#34;])'>`,
232 },
233 {
234 "jsObjValueScript",
235 "<script>alert({{.A}})</script>",
236 `<script>alert(["\u003ca\u003e","\u003cb\u003e"])</script>`,
237 },
238 {
239 "scriptTypeSpace",
240 "<script type=\" \">{{.H}}</script>",
241 "<script type=\" \">\"\\u003cHello\\u003e\"</script>",
242 },
243 {
244 "scriptTypeTab",
245 "<script type=\"\t\">{{.H}}</script>",
246 "<script type=\"\t\">\"\\u003cHello\\u003e\"</script>",
247 },
248 {
249 "scriptTypeEmpty",
250 "<script type=\"\">{{.H}}</script>",
251 "<script type=\"\">\"\\u003cHello\\u003e\"</script>",
252 },
253 {
254 "jsObjValueNotOverEscaped",
255 "<button onclick='alert({{.A | html}})'>",
256 `<button onclick='alert([&#34;\u003ca\u003e&#34;,&#34;\u003cb\u003e&#34;])'>`,
257 },
258 {
259 "jsStr",
260 "<button onclick='alert(&quot;{{.H}}&quot;)'>",
261 `<button onclick='alert(&quot;\u003cHello\u003e&quot;)'>`,
262 },
263 {
264 "badMarshaler",
265 `<button onclick='alert(1/{{.B}}in numbers)'>`,
266 `<button onclick='alert(1/ /* json: error calling MarshalJSON for type *template.badMarshaler: invalid character &#39;f&#39; looking for beginning of object key string */null in numbers)'>`,
267 },
268 {
269 "jsMarshaler",
270 `<button onclick='alert({{.M}})'>`,
271 `<button onclick='alert({&#34;\u003cfoo\u003e&#34;:&#34;O&#39;Reilly&#34;})'>`,
272 },
273 {
274 "jsStrNotUnderEscaped",
275 "<button onclick='alert({{.C | urlquery}})'>",
276 // URL escaped, then quoted for JS.
277 `<button onclick='alert(&#34;%3CCincinnati%3E&#34;)'>`,
278 },
279 {
280 "jsRe",
281 `<button onclick='alert(/{{"foo+bar"}}/.test(""))'>`,
282 `<button onclick='alert(/foo\u002bbar/.test(""))'>`,
283 },
284 {
285 "jsReBlank",
286 `<script>alert(/{{""}}/.test(""));</script>`,
287 `<script>alert(/(?:)/.test(""));</script>`,
288 },
289 {
290 "jsReAmbigOk",
291 `<script>{{if true}}var x = 1{{end}}</script>`,
292 // The {if} ends in an ambiguous jsCtx but there is
293 // no slash following so we shouldn't care.
294 `<script>var x = 1</script>`,
295 },
296 {
297 "styleBidiKeywordPassed",
298 `<p style="dir: {{"ltr"}}">`,
299 `<p style="dir: ltr">`,
300 },
301 {
302 "styleBidiPropNamePassed",
303 `<p style="border-{{"left"}}: 0; border-{{"right"}}: 1in">`,
304 `<p style="border-left: 0; border-right: 1in">`,
305 },
306 {
307 "styleExpressionBlocked",
308 `<p style="width: {{"expression(alert(1337))"}}">`,
309 `<p style="width: ZgotmplZ">`,
310 },
311 {
312 "styleTagSelectorPassed",
313 `<style>{{"p"}} { color: pink }</style>`,
314 `<style>p { color: pink }</style>`,
315 },
316 {
317 "styleIDPassed",
318 `<style>p{{"#my-ID"}} { font: Arial }</style>`,
319 `<style>p#my-ID { font: Arial }</style>`,
320 },
321 {
322 "styleClassPassed",
323 `<style>p{{".my_class"}} { font: Arial }</style>`,
324 `<style>p.my_class { font: Arial }</style>`,
325 },
326 {
327 "styleQuantityPassed",
328 `<a style="left: {{"2em"}}; top: {{0}}">`,
329 `<a style="left: 2em; top: 0">`,
330 },
331 {
332 "stylePctPassed",
333 `<table style=width:{{"100%"}}>`,
334 `<table style=width:100%>`,
335 },
336 {
337 "styleColorPassed",
338 `<p style="color: {{"#8ff"}}; background: {{"#000"}}">`,
339 `<p style="color: #8ff; background: #000">`,
340 },
341 {
342 "styleObfuscatedExpressionBlocked",
343 `<p style="width: {{" e\\78preS\x00Sio/**/n(alert(1337))"}}">`,
344 `<p style="width: ZgotmplZ">`,
345 },
346 {
347 "styleMozBindingBlocked",
348 `<p style="{{"-moz-binding(alert(1337))"}}: ...">`,
349 `<p style="ZgotmplZ: ...">`,
350 },
351 {
352 "styleObfuscatedMozBindingBlocked",
353 `<p style="{{" -mo\\7a-B\x00I/**/nding(alert(1337))"}}: ...">`,
354 `<p style="ZgotmplZ: ...">`,
355 },
356 {
357 "styleFontNameString",
358 `<p style='font-family: "{{"Times New Roman"}}"'>`,
359 `<p style='font-family: "Times New Roman"'>`,
360 },
361 {
362 "styleFontNameString",
363 `<p style='font-family: "{{"Times New Roman"}}", "{{"sans-serif"}}"'>`,
364 `<p style='font-family: "Times New Roman", "sans-serif"'>`,
365 },
366 {
367 "styleFontNameUnquoted",
368 `<p style='font-family: {{"Times New Roman"}}'>`,
369 `<p style='font-family: Times New Roman'>`,
370 },
371 {
372 "styleURLQueryEncoded",
373 `<p style="background: url(/img?name={{"O'Reilly Animal(1)<2>.png"}})">`,
374 `<p style="background: url(/img?name=O%27Reilly%20Animal%281%29%3c2%3e.png)">`,
375 },
376 {
377 "styleQuotedURLQueryEncoded",
378 `<p style="background: url('/img?name={{"O'Reilly Animal(1)<2>.png"}}')">`,
379 `<p style="background: url('/img?name=O%27Reilly%20Animal%281%29%3c2%3e.png')">`,
380 },
381 {
382 "styleStrQueryEncoded",
383 `<p style="background: '/img?name={{"O'Reilly Animal(1)<2>.png"}}'">`,
384 `<p style="background: '/img?name=O%27Reilly%20Animal%281%29%3c2%3e.png'">`,
385 },
386 {
387 "styleURLBadProtocolBlocked",
388 `<a style="background: url('{{"javascript:alert(1337)"}}')">`,
389 `<a style="background: url('#ZgotmplZ')">`,
390 },
391 {
392 "styleStrBadProtocolBlocked",
393 `<a style="background: '{{"vbscript:alert(1337)"}}'">`,
394 `<a style="background: '#ZgotmplZ'">`,
395 },
396 {
397 "styleStrEncodedProtocolEncoded",
398 `<a style="background: '{{"javascript\\3a alert(1337)"}}'">`,
399 // The CSS string 'javascript\\3a alert(1337)' does not contain a colon.
400 `<a style="background: 'javascript\\3a alert\28 1337\29 '">`,
401 },
402 {
403 "styleURLGoodProtocolPassed",
404 `<a style="background: url('{{"http://oreilly.com/O'Reilly Animals(1)<2>;{}.html"}}')">`,
405 `<a style="background: url('http://oreilly.com/O%27Reilly%20Animals%281%29%3c2%3e;%7b%7d.html')">`,
406 },
407 {
408 "styleStrGoodProtocolPassed",
409 `<a style="background: '{{"http://oreilly.com/O'Reilly Animals(1)<2>;{}.html"}}'">`,
410 `<a style="background: 'http\3a\2f\2foreilly.com\2fO\27Reilly Animals\28 1\29\3c 2\3e\3b\7b\7d.html'">`,
411 },
412 {
413 "styleURLEncodedForHTMLInAttr",
414 `<a style="background: url('{{"/search?img=foo&size=icon"}}')">`,
415 `<a style="background: url('/search?img=foo&amp;size=icon')">`,
416 },
417 {
418 "styleURLNotEncodedForHTMLInCdata",
419 `<style>body { background: url('{{"/search?img=foo&size=icon"}}') }</style>`,
420 `<style>body { background: url('/search?img=foo&size=icon') }</style>`,
421 },
422 {
423 "styleURLMixedCase",
424 `<p style="background: URL(#{{.H}})">`,
425 `<p style="background: URL(#%3cHello%3e)">`,
426 },
427 {
428 "stylePropertyPairPassed",
429 `<a style='{{"color: red"}}'>`,
430 `<a style='color: red'>`,
431 },
432 {
433 "styleStrSpecialsEncoded",
434 `<a style="font-family: '{{"/**/'\";:// \\"}}', &quot;{{"/**/'\";:// \\"}}&quot;">`,
435 `<a style="font-family: '\2f**\2f\27\22\3b\3a\2f\2f \\', &quot;\2f**\2f\27\22\3b\3a\2f\2f \\&quot;">`,
436 },
437 {
438 "styleURLSpecialsEncoded",
439 `<a style="border-image: url({{"/**/'\";:// \\"}}), url(&quot;{{"/**/'\";:// \\"}}&quot;), url('{{"/**/'\";:// \\"}}'), 'http://www.example.com/?q={{"/**/'\";:// \\"}}''">`,
440 `<a style="border-image: url(/**/%27%22;://%20%5c), url(&quot;/**/%27%22;://%20%5c&quot;), url('/**/%27%22;://%20%5c'), 'http://www.example.com/?q=%2f%2a%2a%2f%27%22%3b%3a%2f%2f%20%5c''">`,
441 },
442 {
443 "HTML comment",
444 "<b>Hello, <!-- name of world -->{{.C}}</b>",
445 "<b>Hello, &lt;Cincinnati&gt;</b>",
446 },
447 {
448 "HTML comment not first < in text node.",
449 "<<!-- -->!--",
450 "&lt;!--",
451 },
452 {
453 "HTML normalization 1",
454 "a < b",
455 "a &lt; b",
456 },
457 {
458 "HTML normalization 2",
459 "a << b",
460 "a &lt;&lt; b",
461 },
462 {
463 "HTML normalization 3",
464 "a<<!-- --><!-- -->b",
465 "a&lt;b",
466 },
467 {
468 "HTML doctype not normalized",
469 "<!DOCTYPE html>Hello, World!",
470 "<!DOCTYPE html>Hello, World!",
471 },
472 {
473 "HTML doctype not case-insensitive",
474 "<!doCtYPE htMl>Hello, World!",
475 "<!doCtYPE htMl>Hello, World!",
476 },
477 {
478 "No doctype injection",
479 `<!{{"DOCTYPE"}}`,
480 "&lt;!DOCTYPE",
481 },
482 {
483 "Split HTML comment",
484 "<b>Hello, <!-- name of {{if .T}}city -->{{.C}}{{else}}world -->{{.W}}{{end}}</b>",
485 "<b>Hello, &lt;Cincinnati&gt;</b>",
486 },
487 {
488 "JS line comment",
489 "<script>for (;;) { if (c()) break// foo not a label\n" +
490 "foo({{.T}});}</script>",
491 "<script>for (;;) { if (c()) break\n" +
492 "foo( true );}</script>",
493 },
494 {
495 "JS multiline block comment",
496 "<script>for (;;) { if (c()) break/* foo not a label\n" +
497 " */foo({{.T}});}</script>",
498 // Newline separates break from call. If newline
499 // removed, then break will consume label leaving
500 // code invalid.
501 "<script>for (;;) { if (c()) break\n" +
502 "foo( true );}</script>",
503 },
504 {
505 "JS single-line block comment",
506 "<script>for (;;) {\n" +
507 "if (c()) break/* foo a label */foo;" +
508 "x({{.T}});}</script>",
509 // Newline separates break from call. If newline
510 // removed, then break will consume label leaving
511 // code invalid.
512 "<script>for (;;) {\n" +
513 "if (c()) break foo;" +
514 "x( true );}</script>",
515 },
516 {
517 "JS block comment flush with mathematical division",
518 "<script>var a/*b*//c\nd</script>",
519 "<script>var a /c\nd</script>",
520 },
521 {
522 "JS mixed comments",
523 "<script>var a/*b*///c\nd</script>",
524 "<script>var a \nd</script>",
525 },
526 {
527 "JS HTML-like comments",
528 "<script>before <!-- beep\nbetween\nbefore-->boop\n</script>",
529 "<script>before \nbetween\nbefore\n</script>",
530 },
531 {
532 "JS hashbang comment",
533 "<script>#! beep\n</script>",
534 "<script>\n</script>",
535 },
536 {
537 "Special tags in <script> string literals",
538 `<script>var a = "asd < 123 <!-- 456 < fgh <script jkl < 789 </script"</script>`,
539 `<script>var a = "asd < 123 \x3C!-- 456 < fgh \x3Cscript jkl < 789 \x3C/script"</script>`,
540 },
541 {
542 "Special tags in <script> string literals (mixed case)",
543 `<script>var a = "<!-- <ScripT </ScripT"</script>`,
544 `<script>var a = "\x3C!-- \x3CScripT \x3C/ScripT"</script>`,
545 },
546 {
547 "Special tags in <script> regex literals (mixed case)",
548 `<script>var a = /<!-- <ScripT </ScripT/</script>`,
549 `<script>var a = /\x3C!-- \x3CScripT \x3C/ScripT/</script>`,
550 },
551 {
552 "CSS comments",
553 "<style>p// paragraph\n" +
554 `{border: 1px/* color */{{"#00f"}}}</style>`,
555 "<style>p\n" +
556 "{border: 1px #00f}</style>",
557 },
558 {
559 "JS attr block comment",
560 `<a onclick="f(&quot;&quot;); /* alert({{.H}}) */">`,
561 // Attribute comment tests should pass if the comments
562 // are successfully elided.
563 `<a onclick="f(&quot;&quot;); /* alert() */">`,
564 },
565 {
566 "JS attr line comment",
567 `<a onclick="// alert({{.G}})">`,
568 `<a onclick="// alert()">`,
569 },
570 {
571 "CSS attr block comment",
572 `<a style="/* color: {{.H}} */">`,
573 `<a style="/* color: */">`,
574 },
575 {
576 "CSS attr line comment",
577 `<a style="// color: {{.G}}">`,
578 `<a style="// color: ">`,
579 },
580 {
581 "HTML substitution commented out",
582 "<p><!-- {{.H}} --></p>",
583 "<p></p>",
584 },
585 {
586 "Comment ends flush with start",
587 "<!--{{.}}--><script>/*{{.}}*///{{.}}\n</script><style>/*{{.}}*///{{.}}\n</style><a onclick='/*{{.}}*///{{.}}' style='/*{{.}}*///{{.}}'>",
588 "<script> \n</script><style> \n</style><a onclick='/**///' style='/**///'>",
589 },
590 {
591 "typed HTML in text",
592 `{{.W}}`,
593 `&iexcl;<b class="foo">Hello</b>, <textarea>O'World</textarea>!`,
594 },
595 {
596 "typed HTML in attribute",
597 `<div title="{{.W}}">`,
598 `<div title="&iexcl;Hello, O&#39;World!">`,
599 },
600 {
601 "typed HTML in script",
602 `<button onclick="alert({{.W}})">`,
603 `<button onclick="alert(&#34;\u0026iexcl;\u003cb class=\&#34;foo\&#34;\u003eHello\u003c/b\u003e, \u003ctextarea\u003eO&#39;World\u003c/textarea\u003e!&#34;)">`,
604 },
605 {
606 "typed HTML in RCDATA",
607 `<textarea>{{.W}}</textarea>`,
608 `<textarea>&iexcl;&lt;b class=&#34;foo&#34;&gt;Hello&lt;/b&gt;, &lt;textarea&gt;O&#39;World&lt;/textarea&gt;!</textarea>`,
609 },
610 {
611 "range in textarea",
612 "<textarea>{{range .A}}{{.}}{{end}}</textarea>",
613 "<textarea>&lt;a&gt;&lt;b&gt;</textarea>",
614 },
615 {
616 "No tag injection",
617 `{{"10$"}}<{{"script src,evil.org/pwnd.js"}}...`,
618 `10$&lt;script src,evil.org/pwnd.js...`,
619 },
620 {
621 "No comment injection",
622 `<{{"!--"}}`,
623 `&lt;!--`,
624 },
625 {
626 "No RCDATA end tag injection",
627 `<textarea><{{"/textarea "}}...</textarea>`,
628 `<textarea>&lt;/textarea ...</textarea>`,
629 },
630 {
631 "optional attrs",
632 `<img class="{{"iconClass"}}"` +
633 `{{if .T}} id="{{"<iconId>"}}"{{end}}` +
634 // Double quotes inside if/else.
635 ` src=` +
636 `{{if .T}}"?{{"<iconPath>"}}"` +
637 `{{else}}"images/cleardot.gif"{{end}}` +
638 // Missing space before title, but it is not a
639 // part of the src attribute.
640 `{{if .T}}title="{{"<title>"}}"{{end}}` +
641 // Quotes outside if/else.
642 ` alt="` +
643 `{{if .T}}{{"<alt>"}}` +
644 `{{else}}{{if .F}}{{"<title>"}}{{end}}` +
645 `{{end}}"` +
646 `>`,
647 `<img class="iconClass" id="&lt;iconId&gt;" src="?%3ciconPath%3e"title="&lt;title&gt;" alt="&lt;alt&gt;">`,
648 },
649 {
650 "conditional valueless attr name",
651 `<input{{if .T}} checked{{end}} name=n>`,
652 `<input checked name=n>`,
653 },
654 {
655 "conditional dynamic valueless attr name 1",
656 `<input{{if .T}} {{"checked"}}{{end}} name=n>`,
657 `<input checked name=n>`,
658 },
659 {
660 "conditional dynamic valueless attr name 2",
661 `<input {{if .T}}{{"checked"}} {{end}}name=n>`,
662 `<input checked name=n>`,
663 },
664 {
665 "dynamic attribute name",
666 `<img on{{"load"}}="alert({{"loaded"}})">`,
667 // Treated as JS since quotes are inserted.
668 `<img onload="alert(&#34;loaded&#34;)">`,
669 },
670 {
671 "bad dynamic attribute name 1",
672 // Allow checked, selected, disabled, but not JS or
673 // CSS attributes.
674 `<input {{"onchange"}}="{{"doEvil()"}}">`,
675 `<input ZgotmplZ="doEvil()">`,
676 },
677 {
678 "bad dynamic attribute name 2",
679 `<div {{"sTyle"}}="{{"color: expression(alert(1337))"}}">`,
680 `<div ZgotmplZ="color: expression(alert(1337))">`,
681 },
682 {
683 "bad dynamic attribute name 3",
684 // Allow title or alt, but not a URL.
685 `<img {{"src"}}="{{"javascript:doEvil()"}}">`,
686 `<img ZgotmplZ="javascript:doEvil()">`,
687 },
688 {
689 "bad dynamic attribute name 4",
690 // Structure preservation requires values to associate
691 // with a consistent attribute.
692 `<input checked {{""}}="Whose value am I?">`,
693 `<input checked ZgotmplZ="Whose value am I?">`,
694 },
695 {
696 "dynamic element name",
697 `<h{{3}}><table><t{{"head"}}>...</h{{3}}>`,
698 `<h3><table><thead>...</h3>`,
699 },
700 {
701 "bad dynamic element name",
702 // Dynamic element names are typically used to switch
703 // between (thead, tfoot, tbody), (ul, ol), (th, td),
704 // and other replaceable sets.
705 // We do not currently easily support (ul, ol).
706 // If we do change to support that, this test should
707 // catch failures to filter out special tag names which
708 // would violate the structure preservation property --
709 // if any special tag name could be substituted, then
710 // the content could be raw text/RCDATA for some inputs
711 // and regular HTML content for others.
712 `<{{"script"}}>{{"doEvil()"}}</{{"script"}}>`,
713 `&lt;script>doEvil()&lt;/script>`,
714 },
715 {
716 "srcset bad URL in second position",
717 `<img srcset="{{"/not-an-image#,javascript:alert(1)"}}">`,
718 // The second URL is also filtered.
719 `<img srcset="/not-an-image#,#ZgotmplZ">`,
720 },
721 {
722 "srcset buffer growth",
723 `<img srcset={{",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}}>`,
724 `<img srcset=,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,>`,
725 },
726 {
727 "unquoted empty attribute value (plaintext)",
728 "<p name={{.U}}>",
729 "<p name=ZgotmplZ>",
730 },
731 {
732 "unquoted empty attribute value (url)",
733 "<p href={{.U}}>",
734 "<p href=ZgotmplZ>",
735 },
736 {
737 "quoted empty attribute value",
738 "<p name=\"{{.U}}\">",
739 "<p name=\"\">",
740 },
741 {
742 "JS template lit special characters",
743 "<script>var a = `{{.I}}`</script>",
744 "<script>var a = `\\u0024\\u007b asd \\u0060\\u0060 \\u007d`</script>",
745 },
746 {
747 "JS template lit special characters, nested lit",
748 "<script>var a = `${ `{{.I}}` }`</script>",
749 "<script>var a = `${ `\\u0024\\u007b asd \\u0060\\u0060 \\u007d` }`</script>",
750 },
751 {
752 "JS template lit, nested JS",
753 "<script>var a = `${ var a = \"{{\"a \\\" d\"}}\" }`</script>",
754 "<script>var a = `${ var a = \"a \\u0022 d\" }`</script>",
755 },
756 {
757 "meta content attribute url",
758 `<meta http-equiv="refresh" content="asd; url={{"javascript:alert(1)"}}; asd; url={{"vbscript:alert(1)"}}; asd">`,
759 `<meta http-equiv="refresh" content="asd; url=#ZgotmplZ; asd; url=#ZgotmplZ; asd">`,
760 },
761 {
762 "meta content string",
763 `<meta http-equiv="refresh" content="{{"asd: 123"}}">`,
764 `<meta http-equiv="refresh" content="asd: 123">`,
765 },
766 {
767 "meta content url with whitespace before equals",
768 `<meta http-equiv="refresh" content="0;url ={{"javascript:alert(1)"}}">`,
769 `<meta http-equiv="refresh" content="0;url =#ZgotmplZ">`,
770 },
771 {
772 "meta content url with tab before equals",
773 "<meta http-equiv=\"refresh\" content=\"0;url\t={{\"javascript:alert(1)\"}}\">",
774 "<meta http-equiv=\"refresh\" content=\"0;url\t=#ZgotmplZ\">",
775 },
776 {
777 "meta content url with space after equals",
778 `<meta http-equiv="refresh" content="0;url= {{"javascript:alert(1)"}}">`,
779 `<meta http-equiv="refresh" content="0;url= #ZgotmplZ">`,
780 },
781 {
782 "meta content url with whitespace both sides of equals",
783 "<meta http-equiv=\"refresh\" content=\"0;url \t= {{\"javascript:alert(1)\"}}\">",
784 "<meta http-equiv=\"refresh\" content=\"0;url \t= #ZgotmplZ\">",
785 },
786 }
787
788 for _, test := range tests {
789 t.Run(test.name, func(t *testing.T) {
790 tmpl := New(test.name)
791 tmpl = Must(tmpl.Parse(test.input))
792 // Check for bug 6459: Tree field was not set in Parse.
793 if tmpl.Tree != tmpl.text.Tree {
794 t.Fatalf("%s: tree not set properly", test.name)
795 }
796 b := new(strings.Builder)
797 if err := tmpl.Execute(b, data); err != nil {
798 t.Fatalf("%s: template execution failed: %s", test.name, err)
799 }
800 if w, g := test.output, b.String(); w != g {
801 t.Fatalf("%s: escaped output: want\n\t%q\ngot\n\t%q", test.name, w, g)
802 }
803 b.Reset()
804 if err := tmpl.Execute(b, pdata); err != nil {
805 t.Fatalf("%s: template execution failed for pointer: %s", test.name, err)
806 }
807 if w, g := test.output, b.String(); w != g {
808 t.Fatalf("%s: escaped output for pointer: want\n\t%q\ngot\n\t%q", test.name, w, g)
809 }
810 if tmpl.Tree != tmpl.text.Tree {
811 t.Fatalf("%s: tree mismatch", test.name)
812 }
813 })
814 }
815 }
816
817 func TestEscapeMap(t *testing.T) {
818 data := map[string]string{
819 "html": `<h1>Hi!</h1>`,
820 "urlquery": `http://www.foo.com/index.html?title=main`,
821 }
822 for _, test := range [...]struct {
823 desc, input, output string
824 }{
825 // covering issue 20323
826 {
827 "field with predefined escaper name 1",
828 `{{.html | print}}`,
829 `&lt;h1&gt;Hi!&lt;/h1&gt;`,
830 },
831 // covering issue 20323
832 {
833 "field with predefined escaper name 2",
834 `{{.urlquery | print}}`,
835 `http://www.foo.com/index.html?title=main`,
836 },
837 } {
838 tmpl := Must(New("").Parse(test.input))
839 b := new(strings.Builder)
840 if err := tmpl.Execute(b, data); err != nil {
841 t.Errorf("%s: template execution failed: %s", test.desc, err)
842 continue
843 }
844 if w, g := test.output, b.String(); w != g {
845 t.Errorf("%s: escaped output: want\n\t%q\ngot\n\t%q", test.desc, w, g)
846 continue
847 }
848 }
849 }
850
851 func TestEscapeSet(t *testing.T) {
852 type dataItem struct {
853 Children []*dataItem
854 X string
855 }
856
857 data := dataItem{
858 Children: []*dataItem{
859 {X: "foo"},
860 {X: "<bar>"},
861 {
862 Children: []*dataItem{
863 {X: "baz"},
864 },
865 },
866 },
867 }
868
869 tests := []struct {
870 inputs map[string]string
871 want string
872 }{
873 // The trivial set.
874 {
875 map[string]string{
876 "main": ``,
877 },
878 ``,
879 },
880 // A template called in the start context.
881 {
882 map[string]string{
883 "main": `Hello, {{template "helper"}}!`,
884 // Not a valid top level HTML template.
885 // "<b" is not a full tag.
886 "helper": `{{"<World>"}}`,
887 },
888 `Hello, &lt;World&gt;!`,
889 },
890 // A template called in a context other than the start.
891 {
892 map[string]string{
893 "main": `<a onclick='a = {{template "helper"}};'>`,
894 // Not a valid top level HTML template.
895 // "<b" is not a full tag.
896 "helper": `{{"<a>"}}<b`,
897 },
898 `<a onclick='a = &#34;\u003ca\u003e&#34;<b;'>`,
899 },
900 // A recursive template that ends in its start context.
901 {
902 map[string]string{
903 "main": `{{range .Children}}{{template "main" .}}{{else}}{{.X}} {{end}}`,
904 },
905 `foo &lt;bar&gt; baz `,
906 },
907 // A recursive helper template that ends in its start context.
908 {
909 map[string]string{
910 "main": `{{template "helper" .}}`,
911 "helper": `{{if .Children}}<ul>{{range .Children}}<li>{{template "main" .}}</li>{{end}}</ul>{{else}}{{.X}}{{end}}`,
912 },
913 `<ul><li>foo</li><li>&lt;bar&gt;</li><li><ul><li>baz</li></ul></li></ul>`,
914 },
915 // Co-recursive templates that end in its start context.
916 {
917 map[string]string{
918 "main": `<blockquote>{{range .Children}}{{template "helper" .}}{{end}}</blockquote>`,
919 "helper": `{{if .Children}}{{template "main" .}}{{else}}{{.X}}<br>{{end}}`,
920 },
921 `<blockquote>foo<br>&lt;bar&gt;<br><blockquote>baz<br></blockquote></blockquote>`,
922 },
923 // A template that is called in two different contexts.
924 {
925 map[string]string{
926 "main": `<button onclick="title='{{template "helper"}}'; ...">{{template "helper"}}</button>`,
927 "helper": `{{11}} of {{"<100>"}}`,
928 },
929 `<button onclick="title='11 of \u003c100\u003e'; ...">11 of &lt;100&gt;</button>`,
930 },
931 // A non-recursive template that ends in a different context.
932 // helper starts in jsCtxRegexp and ends in jsCtxDivOp.
933 {
934 map[string]string{
935 "main": `<script>var x={{template "helper"}}/{{"42"}};</script>`,
936 "helper": "{{126}}",
937 },
938 `<script>var x= 126 /"42";</script>`,
939 },
940 // A recursive template that ends in a similar context.
941 {
942 map[string]string{
943 "main": `<script>var x=[{{template "countdown" 4}}];</script>`,
944 "countdown": `{{.}}{{if .}},{{template "countdown" . | pred}}{{end}}`,
945 },
946 `<script>var x=[ 4 , 3 , 2 , 1 , 0 ];</script>`,
947 },
948 // A recursive template that ends in a different context.
949 /*
950 {
951 map[string]string{
952 "main": `<a href="/foo{{template "helper" .}}">`,
953 "helper": `{{if .Children}}{{range .Children}}{{template "helper" .}}{{end}}{{else}}?x={{.X}}{{end}}`,
954 },
955 `<a href="/foo?x=foo?x=%3cbar%3e?x=baz">`,
956 },
957 */
958 }
959
960 // pred is a template function that returns the predecessor of a
961 // natural number for testing recursive templates.
962 fns := FuncMap{"pred": func(a ...any) (any, error) {
963 if len(a) == 1 {
964 if i, _ := a[0].(int); i > 0 {
965 return i - 1, nil
966 }
967 }
968 return nil, fmt.Errorf("undefined pred(%v)", a)
969 }}
970
971 for _, test := range tests {
972 source := ""
973 for name, body := range test.inputs {
974 source += fmt.Sprintf("{{define %q}}%s{{end}} ", name, body)
975 }
976 tmpl, err := New("root").Funcs(fns).Parse(source)
977 if err != nil {
978 t.Errorf("error parsing %q: %v", source, err)
979 continue
980 }
981 var b strings.Builder
982
983 if err := tmpl.ExecuteTemplate(&b, "main", data); err != nil {
984 t.Errorf("%q executing %v", err.Error(), tmpl.Lookup("main"))
985 continue
986 }
987 if got := b.String(); test.want != got {
988 t.Errorf("want\n\t%q\ngot\n\t%q", test.want, got)
989 }
990 }
991 }
992
993 func TestErrors(t *testing.T) {
994 tests := []struct {
995 input string
996 err string
997 }{
998 // Non-error cases.
999 {
1000 "{{if .Cond}}<a>{{else}}<b>{{end}}",
1001 "",
1002 },
1003 {
1004 "{{if .Cond}}<a>{{end}}",
1005 "",
1006 },
1007 {
1008 "{{if .Cond}}{{else}}<b>{{end}}",
1009 "",
1010 },
1011 {
1012 "{{with .Cond}}<div>{{end}}",
1013 "",
1014 },
1015 {
1016 "{{range .Items}}<a>{{end}}",
1017 "",
1018 },
1019 {
1020 "<a href='/foo?{{range .Items}}&{{.K}}={{.V}}{{end}}'>",
1021 "",
1022 },
1023 {
1024 "{{range .Items}}<a{{if .X}}{{end}}>{{end}}",
1025 "",
1026 },
1027 {
1028 "{{range .Items}}<a{{if .X}}{{end}}>{{continue}}{{end}}",
1029 "",
1030 },
1031 {
1032 "{{range .Items}}<a{{if .X}}{{end}}>{{break}}{{end}}",
1033 "",
1034 },
1035 {
1036 "{{range .Items}}<a{{if .X}}{{end}}>{{if .X}}{{break}}{{end}}{{end}}",
1037 "",
1038 },
1039 {
1040 "<script>var a = `${a+b}`</script>`",
1041 "",
1042 },
1043 {
1044 "<script>var tmpl = `asd`;</script>",
1045 ``,
1046 },
1047 {
1048 "<script>var tmpl = `${1}`;</script>",
1049 ``,
1050 },
1051 {
1052 "<script>var tmpl = `${return ``}`;</script>",
1053 ``,
1054 },
1055 {
1056 "<script>var tmpl = `${return {{.}} }`;</script>",
1057 ``,
1058 },
1059 {
1060 "<script>var tmpl = `${ let a = {1:1} {{.}} }`;</script>",
1061 ``,
1062 },
1063 {
1064 "<script>var tmpl = `asd ${return \"{\"}`;</script>",
1065 ``,
1066 },
1067 {
1068 `{{if eq "" ""}}<meta>{{end}}`,
1069 ``,
1070 },
1071 {
1072 `{{if eq "" ""}}<meta content="url={{"asd"}}">{{end}}`,
1073 ``,
1074 },
1075
1076 // Error cases.
1077 {
1078 "{{if .Cond}}<a{{end}}",
1079 "z:1:5: {{if}} branches",
1080 },
1081 {
1082 "{{if .Cond}}\n{{else}}\n<a{{end}}",
1083 "z:1:5: {{if}} branches",
1084 },
1085 {
1086 // Missing quote in the else branch.
1087 `{{if .Cond}}<a href="foo">{{else}}<a href="bar>{{end}}`,
1088 "z:1:5: {{if}} branches",
1089 },
1090 {
1091 // Different kind of attribute: href implies a URL.
1092 "<a {{if .Cond}}href='{{else}}title='{{end}}{{.X}}'>",
1093 "z:1:8: {{if}} branches",
1094 },
1095 {
1096 "\n{{with .X}}<a{{end}}",
1097 "z:2:7: {{with}} branches",
1098 },
1099 {
1100 "\n{{with .X}}<a>{{else}}<a{{end}}",
1101 "z:2:7: {{with}} branches",
1102 },
1103 {
1104 "{{range .Items}}<a{{end}}",
1105 `z:1: on range loop re-entry: "<" in attribute name: "<a"`,
1106 },
1107 {
1108 "\n{{range .Items}} x='<a{{end}}",
1109 "z:2:8: on range loop re-entry: {{range}} branches",
1110 },
1111 {
1112 "{{range .Items}}<a{{if .X}}{{break}}{{end}}>{{end}}",
1113 "z:1:29: at range loop break: {{range}} branches end in different contexts",
1114 },
1115 {
1116 "{{range .Items}}<a{{if .X}}{{continue}}{{end}}>{{end}}",
1117 "z:1:29: at range loop continue: {{range}} branches end in different contexts",
1118 },
1119 {
1120 "{{range .Items}}{{if .X}}{{break}}{{end}}<a{{if .Y}}{{continue}}{{end}}>{{if .Z}}{{continue}}{{end}}{{end}}",
1121 "z:1:54: at range loop continue: {{range}} branches end in different contexts",
1122 },
1123 {
1124 "<a b=1 c={{.H}}",
1125 "z: ends in a non-text context: {stateAttr delimSpaceOrTagEnd",
1126 },
1127 {
1128 "<script>foo();",
1129 "z: ends in a non-text context: {stateJS",
1130 },
1131 {
1132 `<a href="{{if .F}}/foo?a={{else}}/bar/{{end}}{{.H}}">`,
1133 "z:1:47: {{.H}} appears in an ambiguous context within a URL",
1134 },
1135 {
1136 `<a onclick="alert('Hello \`,
1137 `unfinished escape sequence in JS string: "Hello \\"`,
1138 },
1139 {
1140 `<a onclick='alert("Hello\, World\`,
1141 `unfinished escape sequence in JS string: "Hello\\, World\\"`,
1142 },
1143 {
1144 `<a onclick='alert(/x+\`,
1145 `unfinished escape sequence in JS string: "x+\\"`,
1146 },
1147 {
1148 `<a onclick="/foo[\]/`,
1149 `unfinished JS regexp charset: "foo[\\]/"`,
1150 },
1151 {
1152 // It is ambiguous whether 1.5 should be 1\.5 or 1.5.
1153 // Either `var x = 1/- 1.5 /i.test(x)`
1154 // where `i.test(x)` is a method call of reference i,
1155 // or `/-1\.5/i.test(x)` which is a method call on a
1156 // case insensitive regular expression.
1157 `<script>{{if false}}var x = 1{{end}}/-{{"1.5"}}/i.test(x)</script>`,
1158 `'/' could start a division or regexp: "/-"`,
1159 },
1160 {
1161 `{{template "foo"}}`,
1162 "z:1:11: no such template \"foo\"",
1163 },
1164 {
1165 `<div{{template "y"}}>` +
1166 // Illegal starting in stateTag but not in stateText.
1167 `{{define "y"}} foo<b{{end}}`,
1168 `"<" in attribute name: " foo<b"`,
1169 },
1170 {
1171 `<script>reverseList = [{{template "t"}}]</script>` +
1172 // Missing " after recursive call.
1173 `{{define "t"}}{{if .Tail}}{{template "t" .Tail}}{{end}}{{.Head}}",{{end}}`,
1174 `: cannot compute output context for template t$htmltemplate_stateJS_elementScript`,
1175 },
1176 {
1177 `<input type=button value=onclick=>`,
1178 `html/template:z: "=" in unquoted attr: "onclick="`,
1179 },
1180 {
1181 `<input type=button value= onclick=>`,
1182 `html/template:z: "=" in unquoted attr: "onclick="`,
1183 },
1184 {
1185 `<input type=button value= 1+1=2>`,
1186 `html/template:z: "=" in unquoted attr: "1+1=2"`,
1187 },
1188 {
1189 "<a class=`foo>",
1190 "html/template:z: \"`\" in unquoted attr: \"`foo\"",
1191 },
1192 {
1193 `<a style=font:'Arial'>`,
1194 `html/template:z: "'" in unquoted attr: "font:'Arial'"`,
1195 },
1196 {
1197 `<a=foo>`,
1198 `: expected space, attr name, or end of tag, but got "=foo>"`,
1199 },
1200 {
1201 `Hello, {{. | urlquery | print}}!`,
1202 // urlquery is disallowed if it is not the last command in the pipeline.
1203 `predefined escaper "urlquery" disallowed in template`,
1204 },
1205 {
1206 `Hello, {{. | html | print}}!`,
1207 // html is disallowed if it is not the last command in the pipeline.
1208 `predefined escaper "html" disallowed in template`,
1209 },
1210 {
1211 `Hello, {{html . | print}}!`,
1212 // A direct call to html is disallowed if it is not the last command in the pipeline.
1213 `predefined escaper "html" disallowed in template`,
1214 },
1215 {
1216 `<div class={{. | html}}>Hello<div>`,
1217 // html is disallowed in a pipeline that is in an unquoted attribute context,
1218 // even if it is the last command in the pipeline.
1219 `predefined escaper "html" disallowed in template`,
1220 },
1221 {
1222 `Hello, {{. | urlquery | html}}!`,
1223 // html is allowed since it is the last command in the pipeline, but urlquery is not.
1224 `predefined escaper "urlquery" disallowed in template`,
1225 },
1226 {
1227 "<script>var a = `{{if .X}}`{{end}}",
1228 `{{if}} branches end in different contexts`,
1229 },
1230 {
1231 "<script>var a = `{{if .X}}a{{else}}`{{end}}",
1232 `{{if}} branches end in different contexts`,
1233 },
1234 {
1235 "<script>var a = `{{if .X}}a{{else}}b{{end}}`</script>",
1236 ``,
1237 },
1238 }
1239 for _, test := range tests {
1240 buf := new(bytes.Buffer)
1241 tmpl, err := New("z").Parse(test.input)
1242 if err != nil {
1243 t.Errorf("input=%q: unexpected parse error %s\n", test.input, err)
1244 continue
1245 }
1246 err = tmpl.Execute(buf, nil)
1247 var got string
1248 if err != nil {
1249 got = err.Error()
1250 }
1251 if test.err == "" {
1252 if got != "" {
1253 t.Errorf("input=%q: unexpected error %q", test.input, got)
1254 }
1255 continue
1256 }
1257 if !strings.Contains(got, test.err) {
1258 t.Errorf("input=%q: error\n\t%q\ndoes not contain expected string\n\t%q", test.input, got, test.err)
1259 continue
1260 }
1261 // Check that we get the same error if we call Execute again.
1262 if err := tmpl.Execute(buf, nil); err == nil || err.Error() != got {
1263 t.Errorf("input=%q: unexpected error on second call %q", test.input, err)
1264 }
1265 }
1266 }
1267
1268 func TestEscapeText(t *testing.T) {
1269 tests := []struct {
1270 input string
1271 output context
1272 }{
1273 {
1274 ``,
1275 context{},
1276 },
1277 {
1278 `Hello, World!`,
1279 context{},
1280 },
1281 {
1282 // An orphaned "<" is OK.
1283 `I <3 Ponies!`,
1284 context{},
1285 },
1286 {
1287 `<a`,
1288 context{state: stateTag},
1289 },
1290 {
1291 `<a `,
1292 context{state: stateTag},
1293 },
1294 {
1295 `<a>`,
1296 context{state: stateText},
1297 },
1298 {
1299 `<a href`,
1300 context{state: stateAttrName, attr: attrURL},
1301 },
1302 {
1303 `<a on`,
1304 context{state: stateAttrName, attr: attrScript},
1305 },
1306 {
1307 `<a href `,
1308 context{state: stateAfterName, attr: attrURL},
1309 },
1310 {
1311 `<a style = `,
1312 context{state: stateBeforeValue, attr: attrStyle},
1313 },
1314 {
1315 `<a href=`,
1316 context{state: stateBeforeValue, attr: attrURL},
1317 },
1318 {
1319 `<a href=x`,
1320 context{state: stateURL, delim: delimSpaceOrTagEnd, urlPart: urlPartPreQuery, attr: attrURL},
1321 },
1322 {
1323 `<a href=x `,
1324 context{state: stateTag},
1325 },
1326 {
1327 `<a href=>`,
1328 context{state: stateText},
1329 },
1330 {
1331 `<a href=x>`,
1332 context{state: stateText},
1333 },
1334 {
1335 `<a href ='`,
1336 context{state: stateURL, delim: delimSingleQuote, attr: attrURL},
1337 },
1338 {
1339 `<a href=''`,
1340 context{state: stateTag},
1341 },
1342 {
1343 `<a href= "`,
1344 context{state: stateURL, delim: delimDoubleQuote, attr: attrURL},
1345 },
1346 {
1347 `<a href=""`,
1348 context{state: stateTag},
1349 },
1350 {
1351 `<a title="`,
1352 context{state: stateAttr, delim: delimDoubleQuote},
1353 },
1354 {
1355 `<a HREF='http:`,
1356 context{state: stateURL, delim: delimSingleQuote, urlPart: urlPartPreQuery, attr: attrURL},
1357 },
1358 {
1359 `<a Href='/`,
1360 context{state: stateURL, delim: delimSingleQuote, urlPart: urlPartPreQuery, attr: attrURL},
1361 },
1362 {
1363 `<a href='"`,
1364 context{state: stateURL, delim: delimSingleQuote, urlPart: urlPartPreQuery, attr: attrURL},
1365 },
1366 {
1367 `<a href="'`,
1368 context{state: stateURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrURL},
1369 },
1370 {
1371 `<a href='&apos;`,
1372 context{state: stateURL, delim: delimSingleQuote, urlPart: urlPartPreQuery, attr: attrURL},
1373 },
1374 {
1375 `<a href="&quot;`,
1376 context{state: stateURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrURL},
1377 },
1378 {
1379 `<a href="&#34;`,
1380 context{state: stateURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrURL},
1381 },
1382 {
1383 `<a href=&quot;`,
1384 context{state: stateURL, delim: delimSpaceOrTagEnd, urlPart: urlPartPreQuery, attr: attrURL},
1385 },
1386 {
1387 `<img alt="1">`,
1388 context{state: stateText},
1389 },
1390 {
1391 `<img alt="1>"`,
1392 context{state: stateTag},
1393 },
1394 {
1395 `<img alt="1>">`,
1396 context{state: stateText},
1397 },
1398 {
1399 `<input checked type="checkbox"`,
1400 context{state: stateTag},
1401 },
1402 {
1403 `<a onclick="`,
1404 context{state: stateJS, delim: delimDoubleQuote, attr: attrScript},
1405 },
1406 {
1407 `<a onclick="//foo`,
1408 context{state: stateJSLineCmt, delim: delimDoubleQuote, attr: attrScript},
1409 },
1410 {
1411 "<a onclick='//\n",
1412 context{state: stateJS, delim: delimSingleQuote, attr: attrScript},
1413 },
1414 {
1415 "<a onclick='//\r\n",
1416 context{state: stateJS, delim: delimSingleQuote, attr: attrScript},
1417 },
1418 {
1419 "<a onclick='//\u2028",
1420 context{state: stateJS, delim: delimSingleQuote, attr: attrScript},
1421 },
1422 {
1423 `<a onclick="/*`,
1424 context{state: stateJSBlockCmt, delim: delimDoubleQuote, attr: attrScript},
1425 },
1426 {
1427 `<a onclick="/*/`,
1428 context{state: stateJSBlockCmt, delim: delimDoubleQuote, attr: attrScript},
1429 },
1430 {
1431 `<a onclick="/**/`,
1432 context{state: stateJS, delim: delimDoubleQuote, attr: attrScript},
1433 },
1434 {
1435 `<a onkeypress="&quot;`,
1436 context{state: stateJSDqStr, delim: delimDoubleQuote, attr: attrScript},
1437 },
1438 {
1439 `<a onclick='&quot;foo&quot;`,
1440 context{state: stateJS, delim: delimSingleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
1441 },
1442 {
1443 `<a onclick=&#39;foo&#39;`,
1444 context{state: stateJS, delim: delimSpaceOrTagEnd, jsCtx: jsCtxDivOp, attr: attrScript},
1445 },
1446 {
1447 `<a onclick=&#39;foo`,
1448 context{state: stateJSSqStr, delim: delimSpaceOrTagEnd, attr: attrScript},
1449 },
1450 {
1451 `<a onclick="&quot;foo'`,
1452 context{state: stateJSDqStr, delim: delimDoubleQuote, attr: attrScript},
1453 },
1454 {
1455 `<a onclick="'foo&quot;`,
1456 context{state: stateJSSqStr, delim: delimDoubleQuote, attr: attrScript},
1457 },
1458 {
1459 "<a onclick=\"`foo",
1460 context{state: stateJSTmplLit, delim: delimDoubleQuote, attr: attrScript},
1461 },
1462 {
1463 `<A ONCLICK="'`,
1464 context{state: stateJSSqStr, delim: delimDoubleQuote, attr: attrScript},
1465 },
1466 {
1467 `<a onclick="/`,
1468 context{state: stateJSRegexp, delim: delimDoubleQuote, attr: attrScript},
1469 },
1470 {
1471 `<a onclick="'foo'`,
1472 context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
1473 },
1474 {
1475 `<a onclick="'foo\'`,
1476 context{state: stateJSSqStr, delim: delimDoubleQuote, attr: attrScript},
1477 },
1478 {
1479 `<a onclick="'foo\'`,
1480 context{state: stateJSSqStr, delim: delimDoubleQuote, attr: attrScript},
1481 },
1482 {
1483 `<a onclick="/foo/`,
1484 context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
1485 },
1486 {
1487 `<script>/foo/ /=`,
1488 context{state: stateJS, element: elementScript},
1489 },
1490 {
1491 `<a onclick="1 /foo`,
1492 context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
1493 },
1494 {
1495 `<a onclick="1 /*c*/ /foo`,
1496 context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
1497 },
1498 {
1499 `<a onclick="/foo[/]`,
1500 context{state: stateJSRegexp, delim: delimDoubleQuote, attr: attrScript},
1501 },
1502 {
1503 `<a onclick="/foo\/`,
1504 context{state: stateJSRegexp, delim: delimDoubleQuote, attr: attrScript},
1505 },
1506 {
1507 `<a onclick="/foo/`,
1508 context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
1509 },
1510 {
1511 `<input checked style="`,
1512 context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
1513 },
1514 {
1515 `<a style="//`,
1516 context{state: stateCSSLineCmt, delim: delimDoubleQuote, attr: attrStyle},
1517 },
1518 {
1519 `<a style="//</script>`,
1520 context{state: stateCSSLineCmt, delim: delimDoubleQuote, attr: attrStyle},
1521 },
1522 {
1523 "<a style='//\n",
1524 context{state: stateCSS, delim: delimSingleQuote, attr: attrStyle},
1525 },
1526 {
1527 "<a style='//\r",
1528 context{state: stateCSS, delim: delimSingleQuote, attr: attrStyle},
1529 },
1530 {
1531 `<a style="/*`,
1532 context{state: stateCSSBlockCmt, delim: delimDoubleQuote, attr: attrStyle},
1533 },
1534 {
1535 `<a style="/*/`,
1536 context{state: stateCSSBlockCmt, delim: delimDoubleQuote, attr: attrStyle},
1537 },
1538 {
1539 `<a style="/**/`,
1540 context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
1541 },
1542 {
1543 `<a style="background: '`,
1544 context{state: stateCSSSqStr, delim: delimDoubleQuote, attr: attrStyle},
1545 },
1546 {
1547 `<a style="background: &quot;`,
1548 context{state: stateCSSDqStr, delim: delimDoubleQuote, attr: attrStyle},
1549 },
1550 {
1551 `<a style="background: '/foo?img=`,
1552 context{state: stateCSSSqStr, delim: delimDoubleQuote, urlPart: urlPartQueryOrFrag, attr: attrStyle},
1553 },
1554 {
1555 `<a style="background: '/`,
1556 context{state: stateCSSSqStr, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
1557 },
1558 {
1559 `<a style="background: url(&#x22;/`,
1560 context{state: stateCSSDqURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
1561 },
1562 {
1563 `<a style="background: url('/`,
1564 context{state: stateCSSSqURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
1565 },
1566 {
1567 `<a style="background: url('/)`,
1568 context{state: stateCSSSqURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
1569 },
1570 {
1571 `<a style="background: url('/ `,
1572 context{state: stateCSSSqURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
1573 },
1574 {
1575 `<a style="background: url(/`,
1576 context{state: stateCSSURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
1577 },
1578 {
1579 `<a style="background: url( `,
1580 context{state: stateCSSURL, delim: delimDoubleQuote, attr: attrStyle},
1581 },
1582 {
1583 `<a style="background: url( /image?name=`,
1584 context{state: stateCSSURL, delim: delimDoubleQuote, urlPart: urlPartQueryOrFrag, attr: attrStyle},
1585 },
1586 {
1587 `<a style="background: url(x)`,
1588 context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
1589 },
1590 {
1591 `<a style="background: url('x'`,
1592 context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
1593 },
1594 {
1595 `<a style="background: url( x `,
1596 context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
1597 },
1598 {
1599 `<!-- foo`,
1600 context{state: stateHTMLCmt},
1601 },
1602 {
1603 `<!-->`,
1604 context{state: stateHTMLCmt},
1605 },
1606 {
1607 `<!--->`,
1608 context{state: stateHTMLCmt},
1609 },
1610 {
1611 `<!-- foo -->`,
1612 context{state: stateText},
1613 },
1614 {
1615 `<script`,
1616 context{state: stateTag, element: elementScript},
1617 },
1618 {
1619 `<script `,
1620 context{state: stateTag, element: elementScript},
1621 },
1622 {
1623 `<script src="foo.js" `,
1624 context{state: stateTag, element: elementScript},
1625 },
1626 {
1627 `<script src='foo.js' `,
1628 context{state: stateTag, element: elementScript},
1629 },
1630 {
1631 `<script type=text/javascript `,
1632 context{state: stateTag, element: elementScript},
1633 },
1634 {
1635 `<script>`,
1636 context{state: stateJS, jsCtx: jsCtxRegexp, element: elementScript},
1637 },
1638 {
1639 `<script>foo`,
1640 context{state: stateJS, jsCtx: jsCtxDivOp, element: elementScript},
1641 },
1642 {
1643 `<script>foo</script>`,
1644 context{state: stateText},
1645 },
1646 {
1647 `<script>foo</script><!--`,
1648 context{state: stateHTMLCmt},
1649 },
1650 {
1651 `<script>document.write("<p>foo</p>");`,
1652 context{state: stateJS, element: elementScript},
1653 },
1654 {
1655 `<script>document.write("<p>foo<\/script>");`,
1656 context{state: stateJS, element: elementScript},
1657 },
1658 {
1659 // <script and </script tags are escaped, so </script> should not
1660 // cause us to exit the JS state.
1661 `<script>document.write("<script>alert(1)</script>");`,
1662 context{state: stateJS, element: elementScript},
1663 },
1664 {
1665 `<script>document.write("<script>`,
1666 context{state: stateJSDqStr, element: elementScript},
1667 },
1668 {
1669 `<script>document.write("<script>alert(1)</script>`,
1670 context{state: stateJSDqStr, element: elementScript},
1671 },
1672 {
1673 `<script>document.write("<script>alert(1)<!--`,
1674 context{state: stateJSDqStr, element: elementScript},
1675 },
1676 {
1677 `<script>document.write("<script>alert(1)</Script>");`,
1678 context{state: stateJS, element: elementScript},
1679 },
1680 {
1681 `<script>document.write("<!--");`,
1682 context{state: stateJS, element: elementScript},
1683 },
1684 {
1685 `<script>let a = /</script`,
1686 context{state: stateJSRegexp, element: elementScript},
1687 },
1688 {
1689 `<script>let a = /</script/`,
1690 context{state: stateJS, element: elementScript, jsCtx: jsCtxDivOp},
1691 },
1692 {
1693 `<script type="text/template">`,
1694 context{state: stateText},
1695 },
1696 // covering issue 19968
1697 {
1698 `<script type="TEXT/JAVASCRIPT">`,
1699 context{state: stateJS, element: elementScript},
1700 },
1701 // covering issue 19965
1702 {
1703 `<script TYPE="text/template">`,
1704 context{state: stateText},
1705 },
1706 {
1707 `<script type="notjs">`,
1708 context{state: stateText},
1709 },
1710 {
1711 `<Script>`,
1712 context{state: stateJS, element: elementScript},
1713 },
1714 {
1715 `<SCRIPT>foo`,
1716 context{state: stateJS, jsCtx: jsCtxDivOp, element: elementScript},
1717 },
1718 {
1719 `<textarea>value`,
1720 context{state: stateRCDATA, element: elementTextarea},
1721 },
1722 {
1723 `<textarea>value</TEXTAREA>`,
1724 context{state: stateText},
1725 },
1726 {
1727 `<textarea name=html><b`,
1728 context{state: stateRCDATA, element: elementTextarea},
1729 },
1730 {
1731 `<title>value`,
1732 context{state: stateRCDATA, element: elementTitle},
1733 },
1734 {
1735 `<style>value`,
1736 context{state: stateCSS, element: elementStyle},
1737 },
1738 {
1739 `<a xlink:href`,
1740 context{state: stateAttrName, attr: attrURL},
1741 },
1742 {
1743 `<a xmlns`,
1744 context{state: stateAttrName, attr: attrURL},
1745 },
1746 {
1747 `<a xmlns:foo`,
1748 context{state: stateAttrName, attr: attrURL},
1749 },
1750 {
1751 `<a xmlnsxyz`,
1752 context{state: stateAttrName},
1753 },
1754 {
1755 `<a data-url`,
1756 context{state: stateAttrName, attr: attrURL},
1757 },
1758 {
1759 `<a data-iconUri`,
1760 context{state: stateAttrName, attr: attrURL},
1761 },
1762 {
1763 `<a data-urlItem`,
1764 context{state: stateAttrName, attr: attrURL},
1765 },
1766 {
1767 `<a g:`,
1768 context{state: stateAttrName},
1769 },
1770 {
1771 `<a g:url`,
1772 context{state: stateAttrName, attr: attrURL},
1773 },
1774 {
1775 `<a g:iconUri`,
1776 context{state: stateAttrName, attr: attrURL},
1777 },
1778 {
1779 `<a g:urlItem`,
1780 context{state: stateAttrName, attr: attrURL},
1781 },
1782 {
1783 `<a g:value`,
1784 context{state: stateAttrName},
1785 },
1786 {
1787 `<a svg:style='`,
1788 context{state: stateCSS, delim: delimSingleQuote, attr: attrStyle},
1789 },
1790 {
1791 `<svg:font-face`,
1792 context{state: stateTag},
1793 },
1794 {
1795 `<svg:a svg:onclick="`,
1796 context{state: stateJS, delim: delimDoubleQuote, attr: attrScript},
1797 },
1798 {
1799 `<svg:a svg:onclick="x()">`,
1800 context{},
1801 },
1802 {
1803 "<script>var a = `",
1804 context{state: stateJSTmplLit, element: elementScript},
1805 },
1806 {
1807 "<script>var a = `${",
1808 context{state: stateJS, element: elementScript, jsBraceDepth: []int{0}},
1809 },
1810 {
1811 "<script>var a = `${}",
1812 context{state: stateJSTmplLit, element: elementScript},
1813 },
1814 {
1815 "<script>var a = `${`",
1816 context{state: stateJSTmplLit, element: elementScript, jsBraceDepth: []int{0}},
1817 },
1818 {
1819 "<script>var a = `${var a = \"",
1820 context{state: stateJSDqStr, element: elementScript, jsBraceDepth: []int{0}},
1821 },
1822 {
1823 "<script>var a = `${var a = \"`",
1824 context{state: stateJSDqStr, element: elementScript, jsBraceDepth: []int{0}},
1825 },
1826 {
1827 "<script>var a = `${var a = \"}",
1828 context{state: stateJSDqStr, element: elementScript, jsBraceDepth: []int{0}},
1829 },
1830 {
1831 "<script>var a = `${``",
1832 context{state: stateJS, element: elementScript, jsBraceDepth: []int{0}},
1833 },
1834 {
1835 "<script>var a = `${`}",
1836 context{state: stateJSTmplLit, element: elementScript, jsBraceDepth: []int{0}},
1837 },
1838 {
1839 "<script>`${ {} } asd`</script><script>`${ {} }",
1840 context{state: stateJSTmplLit, element: elementScript},
1841 },
1842 {
1843 "<script>var foo = `${ (_ => { return \"x\" })() + \"${",
1844 context{state: stateJSDqStr, element: elementScript, jsBraceDepth: []int{0}},
1845 },
1846 {
1847 "<script>var a = `${ {</script><script>var b = `${ x }",
1848 context{state: stateJSTmplLit, element: elementScript, jsCtx: jsCtxDivOp},
1849 },
1850 {
1851 "<script>var foo = `x` + \"${",
1852 context{state: stateJSDqStr, element: elementScript},
1853 },
1854 {
1855 "<script>function f() { var a = `${}`; }",
1856 context{state: stateJS, element: elementScript},
1857 },
1858 {
1859 "<script>{`${}`}",
1860 context{state: stateJS, element: elementScript},
1861 },
1862 {
1863 "<script>`${ function f() { return `${1}` }() }`",
1864 context{state: stateJS, element: elementScript, jsCtx: jsCtxDivOp},
1865 },
1866 {
1867 "<script>function f() {`${ function f() { `${1}` } }`}",
1868 context{state: stateJS, element: elementScript, jsCtx: jsCtxRegexp},
1869 },
1870 {
1871 "<script>`${ { `` }",
1872 context{state: stateJS, element: elementScript, jsBraceDepth: []int{0}},
1873 },
1874 {
1875 "<script>`${ { }`",
1876 context{state: stateJSTmplLit, element: elementScript, jsBraceDepth: []int{0}},
1877 },
1878 {
1879 "<script>var foo = `${ foo({ a: { c: `${",
1880 context{state: stateJS, element: elementScript, jsBraceDepth: []int{2, 0}},
1881 },
1882 {
1883 "<script>var foo = `${ foo({ a: { c: `${ {{.}} }` }, b: ",
1884 context{state: stateJS, element: elementScript, jsBraceDepth: []int{1}},
1885 },
1886 {
1887 "<script>`${ `}",
1888 context{state: stateJSTmplLit, element: elementScript, jsBraceDepth: []int{0}},
1889 },
1890 }
1891
1892 for _, test := range tests {
1893 b, e := []byte(test.input), makeEscaper(nil)
1894 c := e.escapeText(context{}, &parse.TextNode{NodeType: parse.NodeText, Text: b})
1895 if !test.output.eq(c) {
1896 t.Errorf("input %q: want context\n\t%v\ngot\n\t%v", test.input, test.output, c)
1897 continue
1898 }
1899 if test.input != string(b) {
1900 t.Errorf("input %q: text node was modified: want %q got %q", test.input, test.input, b)
1901 continue
1902 }
1903 }
1904 }
1905
1906 func TestEnsurePipelineContains(t *testing.T) {
1907 tests := []struct {
1908 input, output string
1909 ids []string
1910 }{
1911 {
1912 "{{.X}}",
1913 ".X",
1914 []string{},
1915 },
1916 {
1917 "{{.X | html}}",
1918 ".X | html",
1919 []string{},
1920 },
1921 {
1922 "{{.X}}",
1923 ".X | html",
1924 []string{"html"},
1925 },
1926 {
1927 "{{html .X}}",
1928 "_eval_args_ .X | html | urlquery",
1929 []string{"html", "urlquery"},
1930 },
1931 {
1932 "{{html .X .Y .Z}}",
1933 "_eval_args_ .X .Y .Z | html | urlquery",
1934 []string{"html", "urlquery"},
1935 },
1936 {
1937 "{{.X | print}}",
1938 ".X | print | urlquery",
1939 []string{"urlquery"},
1940 },
1941 {
1942 "{{.X | print | urlquery}}",
1943 ".X | print | urlquery",
1944 []string{"urlquery"},
1945 },
1946 {
1947 "{{.X | urlquery}}",
1948 ".X | html | urlquery",
1949 []string{"html", "urlquery"},
1950 },
1951 {
1952 "{{.X | print 2 | .f 3}}",
1953 ".X | print 2 | .f 3 | urlquery | html",
1954 []string{"urlquery", "html"},
1955 },
1956 {
1957 // covering issue 10801
1958 "{{.X | println.x }}",
1959 ".X | println.x | urlquery | html",
1960 []string{"urlquery", "html"},
1961 },
1962 {
1963 // covering issue 10801
1964 "{{.X | (print 12 | println).x }}",
1965 ".X | (print 12 | println).x | urlquery | html",
1966 []string{"urlquery", "html"},
1967 },
1968 // The following test cases ensure that the merging of internal escapers
1969 // with the predefined "html" and "urlquery" escapers is correct.
1970 {
1971 "{{.X | urlquery}}",
1972 ".X | _html_template_urlfilter | urlquery",
1973 []string{"_html_template_urlfilter", "_html_template_urlnormalizer"},
1974 },
1975 {
1976 "{{.X | urlquery}}",
1977 ".X | urlquery | _html_template_urlfilter | _html_template_cssescaper",
1978 []string{"_html_template_urlfilter", "_html_template_cssescaper"},
1979 },
1980 {
1981 "{{.X | urlquery}}",
1982 ".X | urlquery",
1983 []string{"_html_template_urlnormalizer"},
1984 },
1985 {
1986 "{{.X | urlquery}}",
1987 ".X | urlquery",
1988 []string{"_html_template_urlescaper"},
1989 },
1990 {
1991 "{{.X | html}}",
1992 ".X | html",
1993 []string{"_html_template_htmlescaper"},
1994 },
1995 {
1996 "{{.X | html}}",
1997 ".X | html",
1998 []string{"_html_template_rcdataescaper"},
1999 },
2000 }
2001 for i, test := range tests {
2002 tmpl := template.Must(template.New("test").Parse(test.input))
2003 action, ok := (tmpl.Tree.Root.Nodes[0].(*parse.ActionNode))
2004 if !ok {
2005 t.Errorf("First node is not an action: %s", test.input)
2006 continue
2007 }
2008 pipe := action.Pipe
2009 originalIDs := make([]string, len(test.ids))
2010 copy(originalIDs, test.ids)
2011 ensurePipelineContains(pipe, test.ids)
2012 got := pipe.String()
2013 if got != test.output {
2014 t.Errorf("#%d: %s, %v: want\n\t%s\ngot\n\t%s", i, test.input, originalIDs, test.output, got)
2015 }
2016 }
2017 }
2018
2019 func TestEscapeMalformedPipelines(t *testing.T) {
2020 tests := []string{
2021 "{{ 0 | $ }}",
2022 "{{ 0 | $ | urlquery }}",
2023 "{{ 0 | (nil) }}",
2024 "{{ 0 | (nil) | html }}",
2025 }
2026 for _, test := range tests {
2027 var b bytes.Buffer
2028 tmpl, err := New("test").Parse(test)
2029 if err != nil {
2030 t.Errorf("failed to parse set: %q", err)
2031 }
2032 err = tmpl.Execute(&b, nil)
2033 if err == nil {
2034 t.Errorf("Expected error for %q", test)
2035 }
2036 }
2037 }
2038
2039 func TestEscapeErrorsNotIgnorable(t *testing.T) {
2040 var b bytes.Buffer
2041 tmpl, _ := New("dangerous").Parse("<a")
2042 err := tmpl.Execute(&b, nil)
2043 if err == nil {
2044 t.Errorf("Expected error")
2045 } else if b.Len() != 0 {
2046 t.Errorf("Emitted output despite escaping failure")
2047 }
2048 }
2049
2050 func TestEscapeSetErrorsNotIgnorable(t *testing.T) {
2051 var b bytes.Buffer
2052 tmpl, err := New("root").Parse(`{{define "t"}}<a{{end}}`)
2053 if err != nil {
2054 t.Errorf("failed to parse set: %q", err)
2055 }
2056 err = tmpl.ExecuteTemplate(&b, "t", nil)
2057 if err == nil {
2058 t.Errorf("Expected error")
2059 } else if b.Len() != 0 {
2060 t.Errorf("Emitted output despite escaping failure")
2061 }
2062 }
2063
2064 func TestRedundantFuncs(t *testing.T) {
2065 inputs := []any{
2066 "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" +
2067 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" +
2068 ` !"#$%&'()*+,-./` +
2069 `0123456789:;<=>?` +
2070 `@ABCDEFGHIJKLMNO` +
2071 `PQRSTUVWXYZ[\]^_` +
2072 "`abcdefghijklmno" +
2073 "pqrstuvwxyz{|}~\x7f" +
2074 "\u00A0\u0100\u2028\u2029\ufeff\ufdec\ufffd\uffff\U0001D11E" +
2075 "&amp;%22\\",
2076 htmltemplate.CSS(`a[href =~ "//example.com"]#foo`),
2077 htmltemplate.HTML(`Hello, <b>World</b> &amp;tc!`),
2078 htmltemplate.HTMLAttr(` dir="ltr"`),
2079 htmltemplate.JS(`c && alert("Hello, World!");`),
2080 htmltemplate.JSStr(`Hello, World & O'Reilly\x21`),
2081 htmltemplate.URL(`greeting=H%69&addressee=(World)`),
2082 }
2083
2084 for n0, m := range redundantFuncs {
2085 f0 := funcMap[n0].(func(...any) string)
2086 for n1 := range m {
2087 f1 := funcMap[n1].(func(...any) string)
2088 for _, input := range inputs {
2089 want := f0(input)
2090 if got := f1(want); want != got {
2091 t.Errorf("%s %s with %T %q: want\n\t%q,\ngot\n\t%q", n0, n1, input, input, want, got)
2092 }
2093 }
2094 }
2095 }
2096 }
2097
2098 func TestIndirectPrint(t *testing.T) {
2099 a := 3
2100 ap := &a
2101 b := "hello"
2102 bp := &b
2103 bpp := &bp
2104 tmpl := Must(New("t").Parse(`{{.}}`))
2105 var buf strings.Builder
2106 err := tmpl.Execute(&buf, ap)
2107 if err != nil {
2108 t.Errorf("Unexpected error: %s", err)
2109 } else if buf.String() != "3" {
2110 t.Errorf(`Expected "3"; got %q`, buf.String())
2111 }
2112 buf.Reset()
2113 err = tmpl.Execute(&buf, bpp)
2114 if err != nil {
2115 t.Errorf("Unexpected error: %s", err)
2116 } else if buf.String() != "hello" {
2117 t.Errorf(`Expected "hello"; got %q`, buf.String())
2118 }
2119 }
2120
2121 // This is a test for issue 3272.
2122 func TestEmptyTemplateHTML(t *testing.T) {
2123 page := Must(New("page").ParseFiles(os.DevNull))
2124 if err := page.ExecuteTemplate(os.Stdout, "page", "nothing"); err == nil {
2125 t.Fatal("expected error")
2126 }
2127 }
2128
2129 type Issue7379 int
2130
2131 func (Issue7379) SomeMethod(x int) string {
2132 return fmt.Sprintf("<%d>", x)
2133 }
2134
2135 // This is a test for issue 7379: type assertion error caused panic, and then
2136 // the code to handle the panic breaks escaping. It's hard to see the second
2137 // problem once the first is fixed, but its fix is trivial so we let that go. See
2138 // the discussion for issue 7379.
2139 func TestPipeToMethodIsEscaped(t *testing.T) {
2140 tmpl := Must(New("x").Parse("<html>{{0 | .SomeMethod}}</html>\n"))
2141 tryExec := func() string {
2142 defer func() {
2143 panicValue := recover()
2144 if panicValue != nil {
2145 t.Errorf("panicked: %v\n", panicValue)
2146 }
2147 }()
2148 var b strings.Builder
2149 tmpl.Execute(&b, Issue7379(0))
2150 return b.String()
2151 }
2152 for i := 0; i < 3; i++ {
2153 str := tryExec()
2154 const expect = "<html>&lt;0&gt;</html>\n"
2155 if str != expect {
2156 t.Errorf("expected %q got %q", expect, str)
2157 }
2158 }
2159 }
2160
2161 // Unlike text/template, html/template crashed if given an incomplete
2162 // template, that is, a template that had been named but not given any content.
2163 // This is issue #10204.
2164 func TestErrorOnUndefined(t *testing.T) {
2165 tmpl := New("undefined")
2166
2167 err := tmpl.Execute(nil, nil)
2168 if err == nil {
2169 t.Error("expected error")
2170 } else if !strings.Contains(err.Error(), "incomplete") {
2171 t.Errorf("expected error about incomplete template; got %s", err)
2172 }
2173 }
2174
2175 // This covers issue #20842.
2176 func TestIdempotentExecute(t *testing.T) {
2177 tmpl := Must(New("").
2178 Parse(`{{define "main"}}<body>{{template "hello"}}</body>{{end}}`))
2179 Must(tmpl.
2180 Parse(`{{define "hello"}}Hello, {{"Ladies & Gentlemen!"}}{{end}}`))
2181 got := new(strings.Builder)
2182 var err error
2183 // Ensure that "hello" produces the same output when executed twice.
2184 want := "Hello, Ladies &amp; Gentlemen!"
2185 for i := 0; i < 2; i++ {
2186 err = tmpl.ExecuteTemplate(got, "hello", nil)
2187 if err != nil {
2188 t.Errorf("unexpected error: %s", err)
2189 }
2190 if got.String() != want {
2191 t.Errorf("after executing template \"hello\", got:\n\t%q\nwant:\n\t%q\n", got.String(), want)
2192 }
2193 got.Reset()
2194 }
2195 // Ensure that the implicit re-execution of "hello" during the execution of
2196 // "main" does not cause the output of "hello" to change.
2197 err = tmpl.ExecuteTemplate(got, "main", nil)
2198 if err != nil {
2199 t.Errorf("unexpected error: %s", err)
2200 }
2201 // If the HTML escaper is added again to the action {{"Ladies & Gentlemen!"}},
2202 // we would expected to see the ampersand overescaped to "&amp;amp;".
2203 want = "<body>Hello, Ladies &amp; Gentlemen!</body>"
2204 if got.String() != want {
2205 t.Errorf("after executing template \"main\", got:\n\t%q\nwant:\n\t%q\n", got.String(), want)
2206 }
2207 }
2208
2209 func BenchmarkEscapedExecute(b *testing.B) {
2210 tmpl := Must(New("t").Parse(`<a onclick="alert('{{.}}')">{{.}}</a>`))
2211 var buf bytes.Buffer
2212 b.ResetTimer()
2213 for i := 0; i < b.N; i++ {
2214 tmpl.Execute(&buf, "foo & 'bar' & baz")
2215 buf.Reset()
2216 }
2217 }
2218
2219 // Covers issue 22780.
2220 func TestOrphanedTemplate(t *testing.T) {
2221 t1 := Must(New("foo").Parse(`<a href="{{.}}">link1</a>`))
2222 t2 := Must(t1.New("foo").Parse(`bar`))
2223
2224 var b strings.Builder
2225 const wantError = `template: "foo" is an incomplete or empty template`
2226 if err := t1.Execute(&b, "javascript:alert(1)"); err == nil {
2227 t.Fatal("expected error executing t1")
2228 } else if gotError := err.Error(); gotError != wantError {
2229 t.Fatalf("got t1 execution error:\n\t%s\nwant:\n\t%s", gotError, wantError)
2230 }
2231 b.Reset()
2232 if err := t2.Execute(&b, nil); err != nil {
2233 t.Fatalf("error executing t2: %s", err)
2234 }
2235 const want = "bar"
2236 if got := b.String(); got != want {
2237 t.Fatalf("t2 rendered %q, want %q", got, want)
2238 }
2239 }
2240
2241 // Covers issue 21844.
2242 func TestAliasedParseTreeDoesNotOverescape(t *testing.T) {
2243 const (
2244 tmplText = `{{.}}`
2245 data = `<baz>`
2246 want = `&lt;baz&gt;`
2247 )
2248 // Templates "foo" and "bar" both alias the same underlying parse tree.
2249 tpl := Must(New("foo").Parse(tmplText))
2250 if _, err := tpl.AddParseTree("bar", tpl.Tree); err != nil {
2251 t.Fatalf("AddParseTree error: %v", err)
2252 }
2253 var b1, b2 strings.Builder
2254 if err := tpl.ExecuteTemplate(&b1, "foo", data); err != nil {
2255 t.Fatalf(`ExecuteTemplate failed for "foo": %v`, err)
2256 }
2257 if err := tpl.ExecuteTemplate(&b2, "bar", data); err != nil {
2258 t.Fatalf(`ExecuteTemplate failed for "foo": %v`, err)
2259 }
2260 got1, got2 := b1.String(), b2.String()
2261 if got1 != want {
2262 t.Fatalf(`Template "foo" rendered %q, want %q`, got1, want)
2263 }
2264 if got1 != got2 {
2265 t.Fatalf(`Template "foo" and "bar" rendered %q and %q respectively, expected equal values`, got1, got2)
2266 }
2267 }
2268
2269 func TestCVE202656858(t *testing.T) {
2270 tests := []struct {
2271 name string
2272 tmpl string
2273 input string
2274 want string
2275 }{
2276 {
2277 name: "regexp after open brace in if block",
2278 tmpl: `<script>if(true){/{{.}}/g.test("x")}</script>`,
2279 input: "a.b",
2280 want: `<script>if(true){/a\.b/g.test("x")}</script>`,
2281 },
2282 {
2283 name: "regexp after close brace",
2284 tmpl: `<script>if(true){x=1}/{{.}}/g.test("x")</script>`,
2285 input: "a.b",
2286 want: `<script>if(true){x=1}/a\.b/g.test("x")</script>`,
2287 },
2288 {
2289 name: "regexp pathological attacker input",
2290 tmpl: `<script>if(true){/{{.}}/g.test("x")}</script>`,
2291 input: `./;alert(1);var q=/.`,
2292 want: `<script>if(true){/\.\/;alert\(1\);var q=\/\./g.test("x")}</script>`,
2293 },
2294 {
2295 name: "regexp after open brace in template literal",
2296 tmpl: "<script>`${ (function(){/{{.}}/g.test(x)}) }`</script>",
2297 input: "a.b",
2298 want: "<script>`${ (function(){/a\\.b/g.test(x)}) }`</script>",
2299 },
2300 {
2301 name: "regexp after close brace in template literal",
2302 tmpl: "<script>`${ (function(){}/{{.}}/g.test(x)) }`</script>",
2303 input: "a.b",
2304 want: "<script>`${ (function(){}/a\\.b/g.test(x)) }`</script>",
2305 },
2306 }
2307 for _, tt := range tests {
2308 t.Run(tt.name, func(t *testing.T) {
2309 tmpl := Must(New("test").Parse(tt.tmpl))
2310 var buf bytes.Buffer
2311 if err := tmpl.Execute(&buf, tt.input); err != nil {
2312 t.Fatalf("Execute: %v", err)
2313 }
2314 if got := buf.String(); got != tt.want {
2315 t.Errorf("got: %s\nwant: %s", got, tt.want)
2316 }
2317 })
2318 }
2319 }