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