Debian Codegraph @

tpl/internal/go_templates/htmltemplate/escape.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 package template
6
7 import (
8 "bytes"
9 "fmt"
10 "html"
11 //"internal/godebug"
12 "io"
13 "maps"
14 "regexp"
15
16 template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
17 "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
18 )
19
20 // escapeTemplate rewrites the named template, which must be
21 // associated with t, to guarantee that the output of any of the named
22 // templates is properly escaped. If no error is returned, then the named templates have
23 // been modified. Otherwise the named templates have been rendered
24 // unusable.
25 func escapeTemplate(tmpl *Template, node parse.Node, name string) error {
26 c, _ := tmpl.esc.escapeTree(context{}, node, name, 0)
27 var err error
28 if c.err != nil {
29 err, c.err.Name = c.err, name
30 } else if c.state != stateText {
31 err = &Error{ErrEndContext, nil, name, 0, fmt.Sprintf("ends in a non-text context: %v", c)}
32 }
33 if err != nil {
34 // Prevent execution of unsafe templates.
35 if t := tmpl.set[name]; t != nil {
36 t.escapeErr = err
37 t.text.Tree = nil
38 t.Tree = nil
39 }
40 return err
41 }
42 tmpl.esc.commit()
43 if t := tmpl.set[name]; t != nil {
44 t.escapeErr = escapeOK
45 t.Tree = t.text.Tree
46 }
47 return nil
48 }
49
50 // evalArgs formats the list of arguments into a string. It is equivalent to
51 // fmt.Sprint(args...), except that it dereferences all pointers.
52 func evalArgs(args ...any) string {
53 // Optimization for simple common case of a single string argument.
54 if len(args) == 1 {
55 if s, ok := args[0].(string); ok {
56 return s
57 }
58 }
59 for i, arg := range args {
60 args[i] = indirectToStringerOrError(arg)
61 }
62 return fmt.Sprint(args...)
63 }
64
65 // funcMap maps command names to functions that render their inputs safe.
66 var funcMap = template.FuncMap{
67 "_html_template_attrescaper": attrEscaper,
68 "_html_template_commentescaper": commentEscaper,
69 "_html_template_cssescaper": cssEscaper,
70 "_html_template_cssvaluefilter": cssValueFilter,
71 "_html_template_htmlnamefilter": htmlNameFilter,
72 "_html_template_htmlescaper": htmlEscaper,
73 "_html_template_jsregexpescaper": jsRegexpEscaper,
74 "_html_template_jsstrescaper": jsStrEscaper,
75 "_html_template_jstmpllitescaper": jsTmplLitEscaper,
76 "_html_template_jsvalescaper": jsValEscaper,
77 "_html_template_nospaceescaper": htmlNospaceEscaper,
78 "_html_template_rcdataescaper": rcdataEscaper,
79 "_html_template_srcsetescaper": srcsetFilterAndEscaper,
80 "_html_template_urlescaper": urlEscaper,
81 "_html_template_urlfilter": urlFilter,
82 "_html_template_urlnormalizer": urlNormalizer,
83 "_eval_args_": evalArgs,
84 }
85
86 // escaper collects type inferences about templates and changes needed to make
87 // templates injection safe.
88 type escaper struct {
89 // ns is the nameSpace that this escaper is associated with.
90 ns *nameSpace
91 // output[templateName] is the output context for a templateName that
92 // has been mangled to include its input context.
93 output map[string]context
94 // derived[c.mangle(name)] maps to a template derived from the template
95 // named name templateName for the start context c.
96 derived map[string]*template.Template
97 // called[templateName] is a set of called mangled template names.
98 called map[string]bool
99 // xxxNodeEdits are the accumulated edits to apply during commit.
100 // Such edits are not applied immediately in case a template set
101 // executes a given template in different escaping contexts.
102 actionNodeEdits map[*parse.ActionNode][]string
103 templateNodeEdits map[*parse.TemplateNode]string
104 textNodeEdits map[*parse.TextNode][]byte
105 // rangeContext holds context about the current range loop.
106 rangeContext *rangeContext
107 }
108
109 // rangeContext holds information about the current range loop.
110 type rangeContext struct {
111 outer *rangeContext // outer loop
112 breaks []context // context at each break action
113 continues []context // context at each continue action
114 }
115
116 // makeEscaper creates a blank escaper for the given set.
117 func makeEscaper(n *nameSpace) escaper {
118 return escaper{
119 n,
120 map[string]context{},
121 map[string]*template.Template{},
122 map[string]bool{},
123 map[*parse.ActionNode][]string{},
124 map[*parse.TemplateNode]string{},
125 map[*parse.TextNode][]byte{},
126 nil,
127 }
128 }
129
130 // filterFailsafe is an innocuous word that is emitted in place of unsafe values
131 // by sanitizer functions. It is not a keyword in any programming language,
132 // contains no special characters, is not empty, and when it appears in output
133 // it is distinct enough that a developer can find the source of the problem
134 // via a search engine.
135 const filterFailsafe = "ZgotmplZ"
136
137 // escape escapes a template node.
138 func (e *escaper) escape(c context, n parse.Node) context {
139 switch n := n.(type) {
140 case *parse.ActionNode:
141 return e.escapeAction(c, n)
142 case *parse.BreakNode:
143 c.n = n
144 e.rangeContext.breaks = append(e.rangeContext.breaks, c)
145 return context{state: stateDead}
146 case *parse.CommentNode:
147 return c
148 case *parse.ContinueNode:
149 c.n = n
150 e.rangeContext.continues = append(e.rangeContext.continues, c)
151 return context{state: stateDead}
152 case *parse.IfNode:
153 return e.escapeBranch(c, &n.BranchNode, "if")
154 case *parse.ListNode:
155 return e.escapeList(c, n)
156 case *parse.RangeNode:
157 return e.escapeBranch(c, &n.BranchNode, "range")
158 case *parse.TemplateNode:
159 return e.escapeTemplate(c, n)
160 case *parse.TextNode:
161 return e.escapeText(c, n)
162 case *parse.WithNode:
163 return e.escapeBranch(c, &n.BranchNode, "with")
164 }
165 panic("escaping " + n.String() + " is unimplemented")
166 }
167
168 //var debugAllowActionJSTmpl = godebug.New("jstmpllitinterp")
169
170 var htmlmetacontenturlescape = true //godebug.New("htmlmetacontenturlescape")
171
172 // escapeAction escapes an action template node.
173 func (e *escaper) escapeAction(c context, n *parse.ActionNode) context {
174 if len(n.Pipe.Decl) != 0 {
175 // A local variable assignment, not an interpolation.
176 return c
177 }
178 c = nudge(c)
179 // Check for disallowed use of predefined escapers in the pipeline.
180 for pos, idNode := range n.Pipe.Cmds {
181 node, ok := idNode.Args[0].(*parse.IdentifierNode)
182 if !ok {
183 // A predefined escaper "esc" will never be found as an identifier in a
184 // Chain or Field node, since:
185 // - "esc.x ..." is invalid, since predefined escapers return strings, and
186 // strings do not have methods, keys or fields.
187 // - "... .esc" is invalid, since predefined escapers are global functions,
188 // not methods or fields of any types.
189 // Therefore, it is safe to ignore these two node types.
190 continue
191 }
192 ident := node.Ident
193 if _, ok := predefinedEscapers[ident]; ok {
194 if pos < len(n.Pipe.Cmds)-1 ||
195 c.state == stateAttr && c.delim == delimSpaceOrTagEnd && ident == "html" {
196 return context{
197 state: stateError,
198 err: errorf(ErrPredefinedEscaper, n, n.Line, "predefined escaper %q disallowed in template", ident),
199 }
200 }
201 }
202 }
203 s := make([]string, 0, 3)
204 switch c.state {
205 case stateError:
206 return c
207 case stateURL, stateCSSDqStr, stateCSSSqStr, stateCSSDqURL, stateCSSSqURL, stateCSSURL:
208 switch c.urlPart {
209 case urlPartNone:
210 s = append(s, "_html_template_urlfilter")
211 fallthrough
212 case urlPartPreQuery:
213 switch c.state {
214 case stateCSSDqStr, stateCSSSqStr:
215 s = append(s, "_html_template_cssescaper")
216 default:
217 s = append(s, "_html_template_urlnormalizer")
218 }
219 case urlPartQueryOrFrag:
220 s = append(s, "_html_template_urlescaper")
221 case urlPartUnknown:
222 return context{
223 state: stateError,
224 err: errorf(ErrAmbigContext, n, n.Line, "%s appears in an ambiguous context within a URL", n),
225 }
226 default:
227 panic(c.urlPart.String())
228 }
229 case stateMetaContent:
230 // Handled below in delim check.
231 case stateMetaContentURL:
232 if htmlmetacontenturlescape {
233 s = append(s, "_html_template_urlfilter")
234 }
235 case stateJS:
236 s = append(s, "_html_template_jsvalescaper")
237 // A slash after a value starts a div operator.
238 c.jsCtx = jsCtxDivOp
239 case stateJSDqStr, stateJSSqStr:
240 s = append(s, "_html_template_jsstrescaper")
241 case stateJSTmplLit:
242 s = append(s, "_html_template_jstmpllitescaper")
243 case stateJSRegexp:
244 s = append(s, "_html_template_jsregexpescaper")
245 case stateCSS:
246 s = append(s, "_html_template_cssvaluefilter")
247 case stateText:
248 s = append(s, "_html_template_htmlescaper")
249 case stateRCDATA:
250 s = append(s, "_html_template_rcdataescaper")
251 case stateAttr:
252 // Handled below in delim check.
253 case stateAttrName, stateTag:
254 c.state = stateAttrName
255 s = append(s, "_html_template_htmlnamefilter")
256 case stateSrcset:
257 s = append(s, "_html_template_srcsetescaper")
258 default:
259 if isComment(c.state) {
260 s = append(s, "_html_template_commentescaper")
261 } else {
262 panic("unexpected state " + c.state.String())
263 }
264 }
265 switch c.delim {
266 case delimNone:
267 // No extra-escaping needed for raw text content.
268 case delimSpaceOrTagEnd:
269 s = append(s, "_html_template_nospaceescaper")
270 default:
271 s = append(s, "_html_template_attrescaper")
272 }
273 e.editActionNode(n, s)
274 return c
275 }
276
277 // ensurePipelineContains ensures that the pipeline ends with the commands with
278 // the identifiers in s in order. If the pipeline ends with a predefined escaper
279 // (i.e. "html" or "urlquery"), merge it with the identifiers in s.
280 func ensurePipelineContains(p *parse.PipeNode, s []string) {
281 if len(s) == 0 {
282 // Do not rewrite pipeline if we have no escapers to insert.
283 return
284 }
285 // Precondition: p.Cmds contains at most one predefined escaper and the
286 // escaper will be present at p.Cmds[len(p.Cmds)-1]. This precondition is
287 // always true because of the checks in escapeAction.
288 pipelineLen := len(p.Cmds)
289 if pipelineLen > 0 {
290 lastCmd := p.Cmds[pipelineLen-1]
291 if idNode, ok := lastCmd.Args[0].(*parse.IdentifierNode); ok {
292 if esc := idNode.Ident; predefinedEscapers[esc] {
293 // Pipeline ends with a predefined escaper.
294 if len(p.Cmds) == 1 && len(lastCmd.Args) > 1 {
295 // Special case: pipeline is of the form {{ esc arg1 arg2 ... argN }},
296 // where esc is the predefined escaper, and arg1...argN are its arguments.
297 // Convert this into the equivalent form
298 // {{ _eval_args_ arg1 arg2 ... argN | esc }}, so that esc can be easily
299 // merged with the escapers in s.
300 lastCmd.Args[0] = parse.NewIdentifier("_eval_args_").SetTree(nil).SetPos(lastCmd.Args[0].Position())
301 p.Cmds = appendCmd(p.Cmds, newIdentCmd(esc, p.Position()))
302 pipelineLen++
303 }
304 // If any of the commands in s that we are about to insert is equivalent
305 // to the predefined escaper, use the predefined escaper instead.
306 dup := false
307 for i, escaper := range s {
308 if escFnsEq(esc, escaper) {
309 s[i] = idNode.Ident
310 dup = true
311 }
312 }
313 if dup {
314 // The predefined escaper will already be inserted along with the
315 // escapers in s, so do not copy it to the rewritten pipeline.
316 pipelineLen--
317 }
318 }
319 }
320 }
321 // Rewrite the pipeline, creating the escapers in s at the end of the pipeline.
322 newCmds := make([]*parse.CommandNode, pipelineLen, pipelineLen+len(s))
323 insertedIdents := make(map[string]bool)
324 for i := 0; i < pipelineLen; i++ {
325 cmd := p.Cmds[i]
326 newCmds[i] = cmd
327 if idNode, ok := cmd.Args[0].(*parse.IdentifierNode); ok {
328 insertedIdents[normalizeEscFn(idNode.Ident)] = true
329 }
330 }
331 for _, name := range s {
332 if !insertedIdents[normalizeEscFn(name)] {
333 // When two templates share an underlying parse tree via the use of
334 // AddParseTree and one template is executed after the other, this check
335 // ensures that escapers that were already inserted into the pipeline on
336 // the first escaping pass do not get inserted again.
337 newCmds = appendCmd(newCmds, newIdentCmd(name, p.Position()))
338 }
339 }
340 p.Cmds = newCmds
341 }
342
343 // predefinedEscapers contains template predefined escapers that are equivalent
344 // to some contextual escapers. Keep in sync with equivEscapers.
345 var predefinedEscapers = map[string]bool{
346 "html": true,
347 "urlquery": true,
348 }
349
350 // equivEscapers matches contextual escapers to equivalent predefined
351 // template escapers.
352 var equivEscapers = map[string]string{
353 // The following pairs of HTML escapers provide equivalent security
354 // guarantees, since they all escape '\000', '\'', '"', '&', '<', and '>'.
355 "_html_template_attrescaper": "html",
356 "_html_template_htmlescaper": "html",
357 "_html_template_rcdataescaper": "html",
358 // These two URL escapers produce URLs safe for embedding in a URL query by
359 // percent-encoding all the reserved characters specified in RFC 3986 Section
360 // 2.2
361 "_html_template_urlescaper": "urlquery",
362 // These two functions are not actually equivalent; urlquery is stricter as it
363 // escapes reserved characters (e.g. '#'), while _html_template_urlnormalizer
364 // does not. It is therefore only safe to replace _html_template_urlnormalizer
365 // with urlquery (this happens in ensurePipelineContains), but not the otherI've
366 // way around. We keep this entry around to preserve the behavior of templates
367 // written before Go 1.9, which might depend on this substitution taking place.
368 "_html_template_urlnormalizer": "urlquery",
369 }
370
371 // escFnsEq reports whether the two escaping functions are equivalent.
372 func escFnsEq(a, b string) bool {
373 return normalizeEscFn(a) == normalizeEscFn(b)
374 }
375
376 // normalizeEscFn(a) is equal to normalizeEscFn(b) for any pair of names of
377 // escaper functions a and b that are equivalent.
378 func normalizeEscFn(e string) string {
379 if norm := equivEscapers[e]; norm != "" {
380 return norm
381 }
382 return e
383 }
384
385 // redundantFuncs[a][b] implies that funcMap[b](funcMap[a](x)) == funcMap[a](x)
386 // for all x.
387 var redundantFuncs = map[string]map[string]bool{
388 "_html_template_commentescaper": {
389 "_html_template_attrescaper": true,
390 "_html_template_htmlescaper": true,
391 },
392 "_html_template_cssescaper": {
393 "_html_template_attrescaper": true,
394 },
395 "_html_template_jsregexpescaper": {
396 "_html_template_attrescaper": true,
397 },
398 "_html_template_jsstrescaper": {
399 "_html_template_attrescaper": true,
400 },
401 "_html_template_jstmpllitescaper": {
402 "_html_template_attrescaper": true,
403 },
404 "_html_template_urlescaper": {
405 "_html_template_urlnormalizer": true,
406 },
407 }
408
409 // appendCmd appends the given command to the end of the command pipeline
410 // unless it is redundant with the last command.
411 func appendCmd(cmds []*parse.CommandNode, cmd *parse.CommandNode) []*parse.CommandNode {
412 if n := len(cmds); n != 0 {
413 last, okLast := cmds[n-1].Args[0].(*parse.IdentifierNode)
414 next, okNext := cmd.Args[0].(*parse.IdentifierNode)
415 if okLast && okNext && redundantFuncs[last.Ident][next.Ident] {
416 return cmds
417 }
418 }
419 return append(cmds, cmd)
420 }
421
422 // newIdentCmd produces a command containing a single identifier node.
423 func newIdentCmd(identifier string, pos parse.Pos) *parse.CommandNode {
424 return &parse.CommandNode{
425 NodeType: parse.NodeCommand,
426 Args: []parse.Node{parse.NewIdentifier(identifier).SetTree(nil).SetPos(pos)}, // TODO: SetTree.
427 }
428 }
429
430 // nudge returns the context that would result from following empty string
431 // transitions from the input context.
432 // For example, parsing:
433 //
434 // `<a href=`
435 //
436 // will end in context{stateBeforeValue, attrURL}, but parsing one extra rune:
437 //
438 // `<a href=x`
439 //
440 // will end in context{stateURL, delimSpaceOrTagEnd, ...}.
441 // There are two transitions that happen when the 'x' is seen:
442 // (1) Transition from a before-value state to a start-of-value state without
443 //
444 // consuming any character.
445 //
446 // (2) Consume 'x' and transition past the first value character.
447 // In this case, nudging produces the context after (1) happens.
448 func nudge(c context) context {
449 switch c.state {
450 case stateTag:
451 // In `<foo {{.}}`, the action should emit an attribute.
452 c.state = stateAttrName
453 case stateBeforeValue:
454 // In `<foo bar={{.}}`, the action is an undelimited value.
455 c.state, c.delim, c.attr = attrStartStates[c.attr], delimSpaceOrTagEnd, attrNone
456 case stateAfterName:
457 // In `<foo bar {{.}}`, the action is an attribute name.
458 c.state, c.attr = stateAttrName, attrNone
459 }
460 return c
461 }
462
463 // join joins the two contexts of a branch template node. The result is an
464 // error context if either of the input contexts are error contexts, or if the
465 // input contexts differ.
466 func join(a, b context, node parse.Node, nodeName string) context {
467 if a.state == stateError {
468 return a
469 }
470 if b.state == stateError {
471 return b
472 }
473 if a.state == stateDead {
474 return b
475 }
476 if b.state == stateDead {
477 return a
478 }
479 if a.eq(b) {
480 return a
481 }
482
483 c := a
484 c.urlPart = b.urlPart
485 if c.eq(b) {
486 // The contexts differ only by urlPart.
487 c.urlPart = urlPartUnknown
488 return c
489 }
490
491 c = a
492 c.jsCtx = b.jsCtx
493 if c.eq(b) {
494 // The contexts differ only by jsCtx.
495 c.jsCtx = jsCtxUnknown
496 return c
497 }
498
499 // Allow a nudged context to join with an unnudged one.
500 // This means that
501 // <p title={{if .C}}{{.}}{{end}}
502 // ends in an unquoted value state even though the else branch
503 // ends in stateBeforeValue.
504 if c, d := nudge(a), nudge(b); !(c.eq(a) && d.eq(b)) {
505 if e := join(c, d, node, nodeName); e.state != stateError {
506 return e
507 }
508 }
509
510 return context{
511 state: stateError,
512 err: errorf(ErrBranchEnd, node, 0, "{{%s}} branches end in different contexts: %v, %v", nodeName, a, b),
513 }
514 }
515
516 // escapeBranch escapes a branch template node: "if", "range" and "with".
517 func (e *escaper) escapeBranch(c context, n *parse.BranchNode, nodeName string) context {
518 if nodeName == "range" {
519 e.rangeContext = &rangeContext{outer: e.rangeContext}
520 }
521 c0 := e.escapeList(c.clone(), n.List)
522 if nodeName == "range" {
523 if c0.state != stateError {
524 c0 = joinRange(c0, e.rangeContext)
525 }
526 e.rangeContext = e.rangeContext.outer
527 if c0.state == stateError {
528 return c0
529 }
530
531 // The "true" branch of a "range" node can execute multiple times.
532 // We check that executing n.List once results in the same context
533 // as executing n.List twice.
534 e.rangeContext = &rangeContext{outer: e.rangeContext}
535 c1, _ := e.escapeListConditionally(c0, n.List, nil)
536 c0 = join(c0, c1, n, nodeName)
537 if c0.state == stateError {
538 e.rangeContext = e.rangeContext.outer
539 // Make clear that this is a problem on loop re-entry
540 // since developers tend to overlook that branch when
541 // debugging templates.
542 c0.err.Line = n.Line
543 c0.err.Description = "on range loop re-entry: " + c0.err.Description
544 return c0
545 }
546 c0 = joinRange(c0, e.rangeContext)
547 e.rangeContext = e.rangeContext.outer
548 if c0.state == stateError {
549 return c0
550 }
551 }
552 c1 := e.escapeList(c.clone(), n.ElseList)
553 return join(c0, c1, n, nodeName)
554 }
555
556 func joinRange(c0 context, rc *rangeContext) context {
557 // Merge contexts at break and continue statements into overall body context.
558 // In theory we could treat breaks differently from continues, but for now it is
559 // enough to treat them both as going back to the start of the loop (which may then stop).
560 for _, c := range rc.breaks {
561 c0 = join(c0, c, c.n, "range")
562 if c0.state == stateError {
563 c0.err.Line = c.n.(*parse.BreakNode).Line
564 c0.err.Description = "at range loop break: " + c0.err.Description
565 return c0
566 }
567 }
568 for _, c := range rc.continues {
569 c0 = join(c0, c, c.n, "range")
570 if c0.state == stateError {
571 c0.err.Line = c.n.(*parse.ContinueNode).Line
572 c0.err.Description = "at range loop continue: " + c0.err.Description
573 return c0
574 }
575 }
576 return c0
577 }
578
579 // escapeList escapes a list template node.
580 func (e *escaper) escapeList(c context, n *parse.ListNode) context {
581 if n == nil {
582 return c
583 }
584 for _, m := range n.Nodes {
585 c = e.escape(c, m)
586 if c.state == stateDead {
587 break
588 }
589 }
590 return c
591 }
592
593 // escapeListConditionally escapes a list node but only preserves edits and
594 // inferences in e if the inferences and output context satisfy filter.
595 // It returns the best guess at an output context, and the result of the filter
596 // which is the same as whether e was updated.
597 func (e *escaper) escapeListConditionally(c context, n *parse.ListNode, filter func(*escaper, context) bool) (context, bool) {
598 e1 := makeEscaper(e.ns)
599 e1.rangeContext = e.rangeContext
600 // Make type inferences available to f.
601 maps.Copy(e1.output, e.output)
602 c = e1.escapeList(c, n)
603 ok := filter != nil && filter(&e1, c)
604 if ok {
605 // Copy inferences and edits from e1 back into e.
606 maps.Copy(e.output, e1.output)
607 maps.Copy(e.derived, e1.derived)
608 maps.Copy(e.called, e1.called)
609 for k, v := range e1.actionNodeEdits {
610 e.editActionNode(k, v)
611 }
612 for k, v := range e1.templateNodeEdits {
613 e.editTemplateNode(k, v)
614 }
615 for k, v := range e1.textNodeEdits {
616 e.editTextNode(k, v)
617 }
618 }
619 return c, ok
620 }
621
622 // escapeTemplate escapes a {{template}} call node.
623 func (e *escaper) escapeTemplate(c context, n *parse.TemplateNode) context {
624 c, name := e.escapeTree(c, n, n.Name, n.Line)
625 if name != n.Name {
626 e.editTemplateNode(n, name)
627 }
628 return c
629 }
630
631 // escapeTree escapes the named template starting in the given context as
632 // necessary and returns its output context.
633 func (e *escaper) escapeTree(c context, node parse.Node, name string, line int) (context, string) {
634 // Mangle the template name with the input context to produce a reliable
635 // identifier.
636 dname := c.mangle(name)
637 e.called[dname] = true
638 if out, ok := e.output[dname]; ok {
639 // Already escaped.
640 return out, dname
641 }
642 t := e.template(name)
643 if t == nil {
644 // Two cases: The template exists but is empty, or has never been mentioned at
645 // all. Distinguish the cases in the error messages.
646 if e.ns.set[name] != nil {
647 return context{
648 state: stateError,
649 err: errorf(ErrNoSuchTemplate, node, line, "%q is an incomplete or empty template", name),
650 }, dname
651 }
652 return context{
653 state: stateError,
654 err: errorf(ErrNoSuchTemplate, node, line, "no such template %q", name),
655 }, dname
656 }
657 if dname != name {
658 // Use any template derived during an earlier call to escapeTemplate
659 // with different top level templates, or clone if necessary.
660 dt := e.template(dname)
661 if dt == nil {
662 dt = template.New(dname)
663 dt.Tree = &parse.Tree{Name: dname, Root: t.Root.CopyList()}
664 e.derived[dname] = dt
665 }
666 t = dt
667 }
668 return e.computeOutCtx(c, t), dname
669 }
670
671 // computeOutCtx takes a template and its start context and computes the output
672 // context while storing any inferences in e.
673 func (e *escaper) computeOutCtx(c context, t *template.Template) context {
674 // Propagate context over the body.
675 c1, ok := e.escapeTemplateBody(c, t)
676 if !ok {
677 // Look for a fixed point by assuming c1 as the output context.
678 if c2, ok2 := e.escapeTemplateBody(c1, t); ok2 {
679 c1, ok = c2, true
680 }
681 // Use c1 as the error context if neither assumption worked.
682 }
683 if !ok && c1.state != stateError {
684 return context{
685 state: stateError,
686 err: errorf(ErrOutputContext, t.Tree.Root, 0, "cannot compute output context for template %s", t.Name()),
687 }
688 }
689 return c1
690 }
691
692 // escapeTemplateBody escapes the given template assuming the given output
693 // context, and returns the best guess at the output context and whether the
694 // assumption was correct.
695 func (e *escaper) escapeTemplateBody(c context, t *template.Template) (context, bool) {
696 filter := func(e1 *escaper, c1 context) bool {
697 if c1.state == stateError {
698 // Do not update the input escaper, e.
699 return false
700 }
701 if !e1.called[t.Name()] {
702 // If t is not recursively called, then c1 is an
703 // accurate output context.
704 return true
705 }
706 // c1 is accurate if it matches our assumed output context.
707 return c.eq(c1)
708 }
709 // We need to assume an output context so that recursive template calls
710 // take the fast path out of escapeTree instead of infinitely recurring.
711 // Naively assuming that the input context is the same as the output
712 // works >90% of the time.
713 e.output[t.Name()] = c
714 return e.escapeListConditionally(c, t.Tree.Root, filter)
715 }
716
717 // delimEnds maps each delim to a string of characters that terminate it.
718 var delimEnds = [...]string{
719 delimDoubleQuote: `"`,
720 delimSingleQuote: "'",
721 // Determined empirically by running the below in various browsers.
722 // var div = document.createElement("DIV");
723 // for (var i = 0; i < 0x10000; ++i) {
724 // div.innerHTML = "<span title=x" + String.fromCharCode(i) + "-bar>";
725 // if (div.getElementsByTagName("SPAN")[0].title.indexOf("bar") < 0)
726 // document.write("<p>U+" + i.toString(16));
727 // }
728 delimSpaceOrTagEnd: " \t\n\f\r>",
729 }
730
731 var (
732 // Per WHATWG HTML specification, section 4.12.1.3, there are extremely
733 // complicated rules for how to handle the set of opening tags <!--,
734 // <script, and </script when they appear in JS literals (i.e. strings,
735 // regexs, and comments). The specification suggests a simple solution,
736 // rather than implementing the arcane ABNF, which involves simply escaping
737 // the opening bracket with \x3C. We use the below regex for this, since it
738 // makes doing the case-insensitive find-replace much simpler.
739 specialScriptTagRE = regexp.MustCompile("(?i)<(script|/script|!--)")
740 specialScriptTagReplacement = []byte("\\x3C$1")
741 )
742
743 func containsSpecialScriptTag(s []byte) bool {
744 return specialScriptTagRE.Match(s)
745 }
746
747 func escapeSpecialScriptTags(s []byte) []byte {
748 return specialScriptTagRE.ReplaceAll(s, specialScriptTagReplacement)
749 }
750
751 var doctypeBytes = []byte("<!DOCTYPE")
752
753 // escapeText escapes a text template node.
754 func (e *escaper) escapeText(c context, n *parse.TextNode) context {
755 s, written, i, b := n.Text, 0, 0, new(bytes.Buffer)
756 for i != len(s) {
757 c1, nread := contextAfterText(c, s[i:])
758 i1 := i + nread
759 if c.state == stateText || c.state == stateRCDATA {
760 end := i1
761 if c1.state != c.state {
762 for j := end - 1; j >= i; j-- {
763 if s[j] == '<' {
764 end = j
765 break
766 }
767 }
768 }
769 for j := i; j < end; j++ {
770 if s[j] == '<' && !bytes.HasPrefix(bytes.ToUpper(s[j:]), doctypeBytes) {
771 b.Write(s[written:j])
772 b.WriteString("&lt;")
773 written = j + 1
774 }
775 }
776 } else if isComment(c.state) && c.delim == delimNone {
777 switch c.state {
778 case stateJSBlockCmt:
779 // https://es5.github.io/#x7.4:
780 // "Comments behave like white space and are
781 // discarded except that, if a MultiLineComment
782 // contains a line terminator character, then
783 // the entire comment is considered to be a
784 // LineTerminator for purposes of parsing by
785 // the syntactic grammar."
786 if bytes.ContainsAny(s[written:i1], "\n\r\u2028\u2029") {
787 b.WriteByte('\n')
788 } else {
789 b.WriteByte(' ')
790 }
791 case stateCSSBlockCmt:
792 b.WriteByte(' ')
793 }
794 written = i1
795 }
796 if c.state != c1.state && isComment(c1.state) && c1.delim == delimNone {
797 // Preserve the portion between written and the comment start.
798 cs := i1 - 2
799 if c1.state == stateHTMLCmt || c1.state == stateJSHTMLOpenCmt {
800 // "<!--" instead of "/*" or "//"
801 cs -= 2
802 } else if c1.state == stateJSHTMLCloseCmt {
803 // "-->" instead of "/*" or "//"
804 cs -= 1
805 }
806 b.Write(s[written:cs])
807 written = i1
808 }
809 if isInScriptLiteral(c.state) && containsSpecialScriptTag(s[i:i1]) {
810 b.Write(s[written:i])
811 b.Write(escapeSpecialScriptTags(s[i:i1]))
812 written = i1
813 }
814 if i == i1 && c.state == c1.state {
815 panic(fmt.Sprintf("infinite loop from %v to %v on %q..%q", c, c1, s[:i], s[i:]))
816 }
817 c, i = c1, i1
818 }
819
820 if written != 0 && c.state != stateError {
821 if !isComment(c.state) || c.delim != delimNone {
822 b.Write(n.Text[written:])
823 }
824 e.editTextNode(n, b.Bytes())
825 }
826 return c
827 }
828
829 // contextAfterText starts in context c, consumes some tokens from the front of
830 // s, then returns the context after those tokens and the unprocessed suffix.
831 func contextAfterText(c context, s []byte) (context, int) {
832 if c.delim == delimNone {
833 c1, i := tSpecialTagEnd(c, s)
834 if i == 0 {
835 // A special end tag (`</script>`) has been seen and
836 // all content preceding it has been consumed.
837 return c1, 0
838 }
839 // Consider all content up to any end tag.
840 return transitionFunc[c.state](c, s[:i])
841 }
842
843 // We are at the beginning of an attribute value.
844
845 i := bytes.IndexAny(s, delimEnds[c.delim])
846 if i == -1 {
847 i = len(s)
848 }
849 if c.delim == delimSpaceOrTagEnd {
850 // https://www.w3.org/TR/html5/syntax.html#attribute-value-(unquoted)-state
851 // lists the runes below as error characters.
852 // Error out because HTML parsers may differ on whether
853 // "<a id= onclick=f(" ends inside id's or onclick's value,
854 // "<a class=`foo " ends inside a value,
855 // "<a style=font:'Arial'" needs open-quote fixup.
856 // IE treats '`' as a quotation character.
857 if j := bytes.IndexAny(s[:i], "\"'<=`"); j >= 0 {
858 return context{
859 state: stateError,
860 err: errorf(ErrBadHTML, nil, 0, "%q in unquoted attr: %q", s[j:j+1], s[:i]),
861 }, len(s)
862 }
863 }
864 if i == len(s) {
865 // Remain inside the attribute.
866 // Decode the value so non-HTML rules can easily handle
867 // <button onclick="alert(&quot;Hi!&quot;)">
868 // without having to entity decode token boundaries.
869 for u := []byte(html.UnescapeString(string(s))); len(u) != 0; {
870 c1, i1 := transitionFunc[c.state](c, u)
871 c, u = c1, u[i1:]
872 }
873 return c, len(s)
874 }
875
876 element := c.element
877
878 // If this is a non-JS "type" attribute inside "script" tag, do not treat the contents as JS.
879 if c.state == stateAttr && c.element == elementScript && c.attr == attrScriptType && !isJSType(string(s[:i])) {
880 element = elementNone
881 }
882
883 if c.delim != delimSpaceOrTagEnd {
884 // Consume any quote.
885 i++
886 }
887 // On exiting an attribute, we discard all state information
888 // except the state and element.
889 return context{state: stateTag, element: element}, i
890 }
891
892 // editActionNode records a change to an action pipeline for later commit.
893 func (e *escaper) editActionNode(n *parse.ActionNode, cmds []string) {
894 if _, ok := e.actionNodeEdits[n]; ok {
895 panic(fmt.Sprintf("node %s shared between templates", n))
896 }
897 e.actionNodeEdits[n] = cmds
898 }
899
900 // editTemplateNode records a change to a {{template}} callee for later commit.
901 func (e *escaper) editTemplateNode(n *parse.TemplateNode, callee string) {
902 if _, ok := e.templateNodeEdits[n]; ok {
903 panic(fmt.Sprintf("node %s shared between templates", n))
904 }
905 e.templateNodeEdits[n] = callee
906 }
907
908 // editTextNode records a change to a text node for later commit.
909 func (e *escaper) editTextNode(n *parse.TextNode, text []byte) {
910 if _, ok := e.textNodeEdits[n]; ok {
911 panic(fmt.Sprintf("node %s shared between templates", n))
912 }
913 e.textNodeEdits[n] = text
914 }
915
916 // commit applies changes to actions and template calls needed to contextually
917 // autoescape content and adds any derived templates to the set.
918 func (e *escaper) commit() {
919 for name := range e.output {
920 e.template(name).Funcs(funcMap)
921 }
922 // Any template from the name space associated with this escaper can be used
923 // to add derived templates to the underlying text/template name space.
924 tmpl := e.arbitraryTemplate()
925 for _, t := range e.derived {
926 if _, err := tmpl.text.AddParseTree(t.Name(), t.Tree); err != nil {
927 panic("error adding derived template")
928 }
929 }
930 for n, s := range e.actionNodeEdits {
931 ensurePipelineContains(n.Pipe, s)
932 }
933 for n, name := range e.templateNodeEdits {
934 n.Name = name
935 }
936 for n, s := range e.textNodeEdits {
937 n.Text = s
938 }
939 // Reset state that is specific to this commit so that the same changes are
940 // not re-applied to the template on subsequent calls to commit.
941 e.called = make(map[string]bool)
942 e.actionNodeEdits = make(map[*parse.ActionNode][]string)
943 e.templateNodeEdits = make(map[*parse.TemplateNode]string)
944 e.textNodeEdits = make(map[*parse.TextNode][]byte)
945 }
946
947 // template returns the named template given a mangled template name.
948 func (e *escaper) template(name string) *template.Template {
949 // Any template from the name space associated with this escaper can be used
950 // to look up templates in the underlying text/template name space.
951 t := e.arbitraryTemplate().text.Lookup(name)
952 if t == nil {
953 t = e.derived[name]
954 }
955 return t
956 }
957
958 // arbitraryTemplate returns an arbitrary template from the name space
959 // associated with e and panics if no templates are found.
960 func (e *escaper) arbitraryTemplate() *Template {
961 for _, t := range e.ns.set {
962 return t
963 }
964 panic("no templates in name space")
965 }
966
967 // Forwarding functions so that clients need only import this package
968 // to reach the general escaping functions of text/template.
969
970 // HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
971 func HTMLEscape(w io.Writer, b []byte) {
972 template.HTMLEscape(w, b)
973 }
974
975 // HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
976 func HTMLEscapeString(s string) string {
977 return template.HTMLEscapeString(s)
978 }
979
980 // HTMLEscaper returns the escaped HTML equivalent of the textual
981 // representation of its arguments.
982 func HTMLEscaper(args ...any) string {
983 return template.HTMLEscaper(args...)
984 }
985
986 // JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
987 func JSEscape(w io.Writer, b []byte) {
988 template.JSEscape(w, b)
989 }
990
991 // JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
992 func JSEscapeString(s string) string {
993 return template.JSEscapeString(s)
994 }
995
996 // JSEscaper returns the escaped JavaScript equivalent of the textual
997 // representation of its arguments.
998 func JSEscaper(args ...any) string {
999 return template.JSEscaper(args...)
1000 }
1001
1002 // URLQueryEscaper returns the escaped value of the textual representation of
1003 // its arguments in a form suitable for embedding in a URL query.
1004 func URLQueryEscaper(args ...any) string {
1005 return template.URLQueryEscaper(args...)
1006 }