Debian Codegraph @

tpl/internal/go_templates/htmltemplate/escape_test.go

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