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.
17 // escapeTemplate rewrites the named template, which must be
18 // associated with t, to guarantee that the output of any of the named
19 // templates is properly escaped. If no error is returned, then the named templates have
20 // been modified. Otherwise the named templates have been rendered
22 func escapeTemplate(tmpl *Template, node parse.Node, name string) error {
23 c, _ := tmpl.esc.escapeTree(context{}, node, name, 0)
26 err, c.err.Name = c.err, name
27 } else if c.state != stateText {
28 err = &Error{ErrEndContext, nil, name, 0, fmt.Sprintf("ends in a non-text context: %v", c)}
31 // Prevent execution of unsafe templates.
32 if t := tmpl.set[name]; t != nil {
40 if t := tmpl.set[name]; t != nil {
41 t.escapeErr = escapeOK
47 // evalArgs formats the list of arguments into a string. It is equivalent to
48 // fmt.Sprint(args...), except that it dereferences all pointers.
49 func evalArgs(args ...any) string {
50 // Optimization for simple common case of a single string argument.
52 if s, ok := args[0].(string); ok {
56 for i, arg := range args {
57 args[i] = indirectToStringerOrError(arg)
59 return fmt.Sprint(args...)
62 // funcMap maps command names to functions that render their inputs safe.
63 var funcMap = template.FuncMap{
64 "_html_template_attrescaper": attrEscaper,
65 "_html_template_commentescaper": commentEscaper,
66 "_html_template_cssescaper": cssEscaper,
67 "_html_template_cssvaluefilter": cssValueFilter,
68 "_html_template_htmlnamefilter": htmlNameFilter,
69 "_html_template_htmlescaper": htmlEscaper,
70 "_html_template_jsregexpescaper": jsRegexpEscaper,
71 "_html_template_jsstrescaper": jsStrEscaper,
72 "_html_template_jsvalescaper": jsValEscaper,
73 "_html_template_nospaceescaper": htmlNospaceEscaper,
74 "_html_template_rcdataescaper": rcdataEscaper,
75 "_html_template_srcsetescaper": srcsetFilterAndEscaper,
76 "_html_template_urlescaper": urlEscaper,
77 "_html_template_urlfilter": urlFilter,
78 "_html_template_urlnormalizer": urlNormalizer,
79 "_eval_args_": evalArgs,
82 // escaper collects type inferences about templates and changes needed to make
83 // templates injection safe.
85 // ns is the nameSpace that this escaper is associated with.
87 // output[templateName] is the output context for a templateName that
88 // has been mangled to include its input context.
89 output map[string]context
90 // derived[c.mangle(name)] maps to a template derived from the template
91 // named name templateName for the start context c.
92 derived map[string]*template.Template
93 // called[templateName] is a set of called mangled template names.
94 called map[string]bool
95 // xxxNodeEdits are the accumulated edits to apply during commit.
96 // Such edits are not applied immediately in case a template set
97 // executes a given template in different escaping contexts.
98 actionNodeEdits map[*parse.ActionNode][]string
99 templateNodeEdits map[*parse.TemplateNode]string
100 textNodeEdits map[*parse.TextNode][]byte
101 // rangeContext holds context about the current range loop.
102 rangeContext *rangeContext
105 // rangeContext holds information about the current range loop.
106 type rangeContext struct {
107 outer *rangeContext // outer loop
108 breaks []context // context at each break action
109 continues []context // context at each continue action
112 // makeEscaper creates a blank escaper for the given set.
113 func makeEscaper(n *nameSpace) escaper {
116 map[string]context{},
117 map[string]*template.Template{},
119 map[*parse.ActionNode][]string{},
120 map[*parse.TemplateNode]string{},
121 map[*parse.TextNode][]byte{},
126 // filterFailsafe is an innocuous word that is emitted in place of unsafe values
127 // by sanitizer functions. It is not a keyword in any programming language,
128 // contains no special characters, is not empty, and when it appears in output
129 // it is distinct enough that a developer can find the source of the problem
130 // via a search engine.
131 const filterFailsafe = "ZgotmplZ"
133 // escape escapes a template node.
134 func (e *escaper) escape(c context, n parse.Node) context {
135 switch n := n.(type) {
136 case *parse.ActionNode:
137 return e.escapeAction(c, n)
138 case *parse.BreakNode:
140 e.rangeContext.breaks = append(e.rangeContext.breaks, c)
141 return context{state: stateDead}
142 case *parse.CommentNode:
144 case *parse.ContinueNode:
146 e.rangeContext.continues = append(e.rangeContext.breaks, c)
147 return context{state: stateDead}
149 return e.escapeBranch(c, &n.BranchNode, "if")
150 case *parse.ListNode:
151 return e.escapeList(c, n)
152 case *parse.RangeNode:
153 return e.escapeBranch(c, &n.BranchNode, "range")
154 case *parse.TemplateNode:
155 return e.escapeTemplate(c, n)
156 case *parse.TextNode:
157 return e.escapeText(c, n)
158 case *parse.WithNode:
159 return e.escapeBranch(c, &n.BranchNode, "with")
161 panic("escaping " + n.String() + " is unimplemented")
164 var debugAllowActionJSTmpl = godebug.New("jstmpllitinterp")
166 // escapeAction escapes an action template node.
167 func (e *escaper) escapeAction(c context, n *parse.ActionNode) context {
168 if len(n.Pipe.Decl) != 0 {
169 // A local variable assignment, not an interpolation.
173 // Check for disallowed use of predefined escapers in the pipeline.
174 for pos, idNode := range n.Pipe.Cmds {
175 node, ok := idNode.Args[0].(*parse.IdentifierNode)
177 // A predefined escaper "esc" will never be found as an identifier in a
178 // Chain or Field node, since:
179 // - "esc.x ..." is invalid, since predefined escapers return strings, and
180 // strings do not have methods, keys or fields.
181 // - "... .esc" is invalid, since predefined escapers are global functions,
182 // not methods or fields of any types.
183 // Therefore, it is safe to ignore these two node types.
187 if _, ok := predefinedEscapers[ident]; ok {
188 if pos < len(n.Pipe.Cmds)-1 ||
189 c.state == stateAttr && c.delim == delimSpaceOrTagEnd && ident == "html" {
192 err: errorf(ErrPredefinedEscaper, n, n.Line, "predefined escaper %q disallowed in template", ident),
197 s := make([]string, 0, 3)
201 case stateURL, stateCSSDqStr, stateCSSSqStr, stateCSSDqURL, stateCSSSqURL, stateCSSURL:
204 s = append(s, "_html_template_urlfilter")
206 case urlPartPreQuery:
208 case stateCSSDqStr, stateCSSSqStr:
209 s = append(s, "_html_template_cssescaper")
211 s = append(s, "_html_template_urlnormalizer")
213 case urlPartQueryOrFrag:
214 s = append(s, "_html_template_urlescaper")
218 err: errorf(ErrAmbigContext, n, n.Line, "%s appears in an ambiguous context within a URL", n),
221 panic(c.urlPart.String())
224 s = append(s, "_html_template_jsvalescaper")
225 // A slash after a value starts a div operator.
227 case stateJSDqStr, stateJSSqStr:
228 s = append(s, "_html_template_jsstrescaper")
230 if debugAllowActionJSTmpl.Value() == "1" {
231 debugAllowActionJSTmpl.IncNonDefault()
232 s = append(s, "_html_template_jsstrescaper")
236 err: errorf(ErrJSTemplate, n, n.Line, "%s appears in a JS template literal", n),
240 s = append(s, "_html_template_jsregexpescaper")
242 s = append(s, "_html_template_cssvaluefilter")
244 s = append(s, "_html_template_htmlescaper")
246 s = append(s, "_html_template_rcdataescaper")
248 // Handled below in delim check.
249 case stateAttrName, stateTag:
250 c.state = stateAttrName
251 s = append(s, "_html_template_htmlnamefilter")
253 s = append(s, "_html_template_srcsetescaper")
255 if isComment(c.state) {
256 s = append(s, "_html_template_commentescaper")
258 panic("unexpected state " + c.state.String())
263 // No extra-escaping needed for raw text content.
264 case delimSpaceOrTagEnd:
265 s = append(s, "_html_template_nospaceescaper")
267 s = append(s, "_html_template_attrescaper")
269 e.editActionNode(n, s)
273 // ensurePipelineContains ensures that the pipeline ends with the commands with
274 // the identifiers in s in order. If the pipeline ends with a predefined escaper
275 // (i.e. "html" or "urlquery"), merge it with the identifiers in s.
276 func ensurePipelineContains(p *parse.PipeNode, s []string) {
278 // Do not rewrite pipeline if we have no escapers to insert.
281 // Precondition: p.Cmds contains at most one predefined escaper and the
282 // escaper will be present at p.Cmds[len(p.Cmds)-1]. This precondition is
283 // always true because of the checks in escapeAction.
284 pipelineLen := len(p.Cmds)
286 lastCmd := p.Cmds[pipelineLen-1]
287 if idNode, ok := lastCmd.Args[0].(*parse.IdentifierNode); ok {
288 if esc := idNode.Ident; predefinedEscapers[esc] {
289 // Pipeline ends with a predefined escaper.
290 if len(p.Cmds) == 1 && len(lastCmd.Args) > 1 {
291 // Special case: pipeline is of the form {{ esc arg1 arg2 ... argN }},
292 // where esc is the predefined escaper, and arg1...argN are its arguments.
293 // Convert this into the equivalent form
294 // {{ _eval_args_ arg1 arg2 ... argN | esc }}, so that esc can be easily
295 // merged with the escapers in s.
296 lastCmd.Args[0] = parse.NewIdentifier("_eval_args_").SetTree(nil).SetPos(lastCmd.Args[0].Position())
297 p.Cmds = appendCmd(p.Cmds, newIdentCmd(esc, p.Position()))
300 // If any of the commands in s that we are about to insert is equivalent
301 // to the predefined escaper, use the predefined escaper instead.
303 for i, escaper := range s {
304 if escFnsEq(esc, escaper) {
310 // The predefined escaper will already be inserted along with the
311 // escapers in s, so do not copy it to the rewritten pipeline.
317 // Rewrite the pipeline, creating the escapers in s at the end of the pipeline.
318 newCmds := make([]*parse.CommandNode, pipelineLen, pipelineLen+len(s))
319 insertedIdents := make(map[string]bool)
320 for i := 0; i < pipelineLen; i++ {
323 if idNode, ok := cmd.Args[0].(*parse.IdentifierNode); ok {
324 insertedIdents[normalizeEscFn(idNode.Ident)] = true
327 for _, name := range s {
328 if !insertedIdents[normalizeEscFn(name)] {
329 // When two templates share an underlying parse tree via the use of
330 // AddParseTree and one template is executed after the other, this check
331 // ensures that escapers that were already inserted into the pipeline on
332 // the first escaping pass do not get inserted again.
333 newCmds = appendCmd(newCmds, newIdentCmd(name, p.Position()))
339 // predefinedEscapers contains template predefined escapers that are equivalent
340 // to some contextual escapers. Keep in sync with equivEscapers.
341 var predefinedEscapers = map[string]bool{
346 // equivEscapers matches contextual escapers to equivalent predefined
347 // template escapers.
348 var equivEscapers = map[string]string{
349 // The following pairs of HTML escapers provide equivalent security
350 // guarantees, since they all escape '\000', '\'', '"', '&', '<', and '>'.
351 "_html_template_attrescaper": "html",
352 "_html_template_htmlescaper": "html",
353 "_html_template_rcdataescaper": "html",
354 // These two URL escapers produce URLs safe for embedding in a URL query by
355 // percent-encoding all the reserved characters specified in RFC 3986 Section
357 "_html_template_urlescaper": "urlquery",
358 // These two functions are not actually equivalent; urlquery is stricter as it
359 // escapes reserved characters (e.g. '#'), while _html_template_urlnormalizer
360 // does not. It is therefore only safe to replace _html_template_urlnormalizer
361 // with urlquery (this happens in ensurePipelineContains), but not the otherI've
362 // way around. We keep this entry around to preserve the behavior of templates
363 // written before Go 1.9, which might depend on this substitution taking place.
364 "_html_template_urlnormalizer": "urlquery",
367 // escFnsEq reports whether the two escaping functions are equivalent.
368 func escFnsEq(a, b string) bool {
369 return normalizeEscFn(a) == normalizeEscFn(b)
372 // normalizeEscFn(a) is equal to normalizeEscFn(b) for any pair of names of
373 // escaper functions a and b that are equivalent.
374 func normalizeEscFn(e string) string {
375 if norm := equivEscapers[e]; norm != "" {
381 // redundantFuncs[a][b] implies that funcMap[b](funcMap[a](x)) == funcMap[a](x)
383 var redundantFuncs = map[string]map[string]bool{
384 "_html_template_commentescaper": {
385 "_html_template_attrescaper": true,
386 "_html_template_htmlescaper": true,
388 "_html_template_cssescaper": {
389 "_html_template_attrescaper": true,
391 "_html_template_jsregexpescaper": {
392 "_html_template_attrescaper": true,
394 "_html_template_jsstrescaper": {
395 "_html_template_attrescaper": true,
397 "_html_template_urlescaper": {
398 "_html_template_urlnormalizer": true,
402 // appendCmd appends the given command to the end of the command pipeline
403 // unless it is redundant with the last command.
404 func appendCmd(cmds []*parse.CommandNode, cmd *parse.CommandNode) []*parse.CommandNode {
405 if n := len(cmds); n != 0 {
406 last, okLast := cmds[n-1].Args[0].(*parse.IdentifierNode)
407 next, okNext := cmd.Args[0].(*parse.IdentifierNode)
408 if okLast && okNext && redundantFuncs[last.Ident][next.Ident] {
412 return append(cmds, cmd)
415 // newIdentCmd produces a command containing a single identifier node.
416 func newIdentCmd(identifier string, pos parse.Pos) *parse.CommandNode {
417 return &parse.CommandNode{
418 NodeType: parse.NodeCommand,
419 Args: []parse.Node{parse.NewIdentifier(identifier).SetTree(nil).SetPos(pos)}, // TODO: SetTree.
423 // nudge returns the context that would result from following empty string
424 // transitions from the input context.
425 // For example, parsing:
429 // will end in context{stateBeforeValue, attrURL}, but parsing one extra rune:
433 // will end in context{stateURL, delimSpaceOrTagEnd, ...}.
434 // There are two transitions that happen when the 'x' is seen:
435 // (1) Transition from a before-value state to a start-of-value state without
437 // consuming any character.
439 // (2) Consume 'x' and transition past the first value character.
440 // In this case, nudging produces the context after (1) happens.
441 func nudge(c context) context {
444 // In `<foo {{.}}`, the action should emit an attribute.
445 c.state = stateAttrName
446 case stateBeforeValue:
447 // In `<foo bar={{.}}`, the action is an undelimited value.
448 c.state, c.delim, c.attr = attrStartStates[c.attr], delimSpaceOrTagEnd, attrNone
450 // In `<foo bar {{.}}`, the action is an attribute name.
451 c.state, c.attr = stateAttrName, attrNone
456 // join joins the two contexts of a branch template node. The result is an
457 // error context if either of the input contexts are error contexts, or if the
458 // input contexts differ.
459 func join(a, b context, node parse.Node, nodeName string) context {
460 if a.state == stateError {
463 if b.state == stateError {
466 if a.state == stateDead {
469 if b.state == stateDead {
477 c.urlPart = b.urlPart
479 // The contexts differ only by urlPart.
480 c.urlPart = urlPartUnknown
487 // The contexts differ only by jsCtx.
488 c.jsCtx = jsCtxUnknown
492 // Allow a nudged context to join with an unnudged one.
494 // <p title={{if .C}}{{.}}{{end}}
495 // ends in an unquoted value state even though the else branch
496 // ends in stateBeforeValue.
497 if c, d := nudge(a), nudge(b); !(c.eq(a) && d.eq(b)) {
498 if e := join(c, d, node, nodeName); e.state != stateError {
505 err: errorf(ErrBranchEnd, node, 0, "{{%s}} branches end in different contexts: %v, %v", nodeName, a, b),
509 // escapeBranch escapes a branch template node: "if", "range" and "with".
510 func (e *escaper) escapeBranch(c context, n *parse.BranchNode, nodeName string) context {
511 if nodeName == "range" {
512 e.rangeContext = &rangeContext{outer: e.rangeContext}
514 c0 := e.escapeList(c, n.List)
515 if nodeName == "range" {
516 if c0.state != stateError {
517 c0 = joinRange(c0, e.rangeContext)
519 e.rangeContext = e.rangeContext.outer
520 if c0.state == stateError {
524 // The "true" branch of a "range" node can execute multiple times.
525 // We check that executing n.List once results in the same context
526 // as executing n.List twice.
527 e.rangeContext = &rangeContext{outer: e.rangeContext}
528 c1, _ := e.escapeListConditionally(c0, n.List, nil)
529 c0 = join(c0, c1, n, nodeName)
530 if c0.state == stateError {
531 e.rangeContext = e.rangeContext.outer
532 // Make clear that this is a problem on loop re-entry
533 // since developers tend to overlook that branch when
534 // debugging templates.
536 c0.err.Description = "on range loop re-entry: " + c0.err.Description
539 c0 = joinRange(c0, e.rangeContext)
540 e.rangeContext = e.rangeContext.outer
541 if c0.state == stateError {
545 c1 := e.escapeList(c, n.ElseList)
546 return join(c0, c1, n, nodeName)
549 func joinRange(c0 context, rc *rangeContext) context {
550 // Merge contexts at break and continue statements into overall body context.
551 // In theory we could treat breaks differently from continues, but for now it is
552 // enough to treat them both as going back to the start of the loop (which may then stop).
553 for _, c := range rc.breaks {
554 c0 = join(c0, c, c.n, "range")
555 if c0.state == stateError {
556 c0.err.Line = c.n.(*parse.BreakNode).Line
557 c0.err.Description = "at range loop break: " + c0.err.Description
561 for _, c := range rc.continues {
562 c0 = join(c0, c, c.n, "range")
563 if c0.state == stateError {
564 c0.err.Line = c.n.(*parse.ContinueNode).Line
565 c0.err.Description = "at range loop continue: " + c0.err.Description
572 // escapeList escapes a list template node.
573 func (e *escaper) escapeList(c context, n *parse.ListNode) context {
577 for _, m := range n.Nodes {
579 if c.state == stateDead {
586 // escapeListConditionally escapes a list node but only preserves edits and
587 // inferences in e if the inferences and output context satisfy filter.
588 // It returns the best guess at an output context, and the result of the filter
589 // which is the same as whether e was updated.
590 func (e *escaper) escapeListConditionally(c context, n *parse.ListNode, filter func(*escaper, context) bool) (context, bool) {
591 e1 := makeEscaper(e.ns)
592 e1.rangeContext = e.rangeContext
593 // Make type inferences available to f.
594 for k, v := range e.output {
597 c = e1.escapeList(c, n)
598 ok := filter != nil && filter(&e1, c)
600 // Copy inferences and edits from e1 back into e.
601 for k, v := range e1.output {
604 for k, v := range e1.derived {
607 for k, v := range e1.called {
610 for k, v := range e1.actionNodeEdits {
611 e.editActionNode(k, v)
613 for k, v := range e1.templateNodeEdits {
614 e.editTemplateNode(k, v)
616 for k, v := range e1.textNodeEdits {
623 // escapeTemplate escapes a {{template}} call node.
624 func (e *escaper) escapeTemplate(c context, n *parse.TemplateNode) context {
625 c, name := e.escapeTree(c, n, n.Name, n.Line)
627 e.editTemplateNode(n, name)
632 // escapeTree escapes the named template starting in the given context as
633 // necessary and returns its output context.
634 func (e *escaper) escapeTree(c context, node parse.Node, name string, line int) (context, string) {
635 // Mangle the template name with the input context to produce a reliable
637 dname := c.mangle(name)
638 e.called[dname] = true
639 if out, ok := e.output[dname]; ok {
643 t := e.template(name)
645 // Two cases: The template exists but is empty, or has never been mentioned at
646 // all. Distinguish the cases in the error messages.
647 if e.ns.set[name] != nil {
650 err: errorf(ErrNoSuchTemplate, node, line, "%q is an incomplete or empty template", name),
655 err: errorf(ErrNoSuchTemplate, node, line, "no such template %q", name),
659 // Use any template derived during an earlier call to escapeTemplate
660 // with different top level templates, or clone if necessary.
661 dt := e.template(dname)
663 dt = template.New(dname)
664 dt.Tree = &parse.Tree{Name: dname, Root: t.Root.CopyList()}
665 e.derived[dname] = dt
669 return e.computeOutCtx(c, t), dname
672 // computeOutCtx takes a template and its start context and computes the output
673 // context while storing any inferences in e.
674 func (e *escaper) computeOutCtx(c context, t *template.Template) context {
675 // Propagate context over the body.
676 c1, ok := e.escapeTemplateBody(c, t)
678 // Look for a fixed point by assuming c1 as the output context.
679 if c2, ok2 := e.escapeTemplateBody(c1, t); ok2 {
682 // Use c1 as the error context if neither assumption worked.
684 if !ok && c1.state != stateError {
687 err: errorf(ErrOutputContext, t.Tree.Root, 0, "cannot compute output context for template %s", t.Name()),
693 // escapeTemplateBody escapes the given template assuming the given output
694 // context, and returns the best guess at the output context and whether the
695 // assumption was correct.
696 func (e *escaper) escapeTemplateBody(c context, t *template.Template) (context, bool) {
697 filter := func(e1 *escaper, c1 context) bool {
698 if c1.state == stateError {
699 // Do not update the input escaper, e.
702 if !e1.called[t.Name()] {
703 // If t is not recursively called, then c1 is an
704 // accurate output context.
707 // c1 is accurate if it matches our assumed output context.
710 // We need to assume an output context so that recursive template calls
711 // take the fast path out of escapeTree instead of infinitely recurring.
712 // Naively assuming that the input context is the same as the output
713 // works >90% of the time.
714 e.output[t.Name()] = c
715 return e.escapeListConditionally(c, t.Tree.Root, filter)
718 // delimEnds maps each delim to a string of characters that terminate it.
719 var delimEnds = [...]string{
720 delimDoubleQuote: `"`,
721 delimSingleQuote: "'",
722 // Determined empirically by running the below in various browsers.
723 // var div = document.createElement("DIV");
724 // for (var i = 0; i < 0x10000; ++i) {
725 // div.innerHTML = "<span title=x" + String.fromCharCode(i) + "-bar>";
726 // if (div.getElementsByTagName("SPAN")[0].title.indexOf("bar") < 0)
727 // document.write("<p>U+" + i.toString(16));
729 delimSpaceOrTagEnd: " \t\n\f\r>",
732 var doctypeBytes = []byte("<!DOCTYPE")
734 // escapeText escapes a text template node.
735 func (e *escaper) escapeText(c context, n *parse.TextNode) context {
736 s, written, i, b := n.Text, 0, 0, new(bytes.Buffer)
738 c1, nread := contextAfterText(c, s[i:])
740 if c.state == stateText || c.state == stateRCDATA {
742 if c1.state != c.state {
743 for j := end - 1; j >= i; j-- {
750 for j := i; j < end; j++ {
751 if s[j] == '<' && !bytes.HasPrefix(bytes.ToUpper(s[j:]), doctypeBytes) {
752 b.Write(s[written:j])
753 b.WriteString("<")
757 } else if isComment(c.state) && c.delim == delimNone {
759 case stateJSBlockCmt:
760 // https://es5.github.io/#x7.4:
761 // "Comments behave like white space and are
762 // discarded except that, if a MultiLineComment
763 // contains a line terminator character, then
764 // the entire comment is considered to be a
765 // LineTerminator for purposes of parsing by
766 // the syntactic grammar."
767 if bytes.ContainsAny(s[written:i1], "\n\r\u2028\u2029") {
772 case stateCSSBlockCmt:
777 if c.state != c1.state && isComment(c1.state) && c1.delim == delimNone {
778 // Preserve the portion between written and the comment start.
780 if c1.state == stateHTMLCmt {
781 // "<!--" instead of "/*" or "//"
784 b.Write(s[written:cs])
787 if i == i1 && c.state == c1.state {
788 panic(fmt.Sprintf("infinite loop from %v to %v on %q..%q", c, c1, s[:i], s[i:]))
793 if written != 0 && c.state != stateError {
794 if !isComment(c.state) || c.delim != delimNone {
795 b.Write(n.Text[written:])
797 e.editTextNode(n, b.Bytes())
802 // contextAfterText starts in context c, consumes some tokens from the front of
803 // s, then returns the context after those tokens and the unprocessed suffix.
804 func contextAfterText(c context, s []byte) (context, int) {
805 if c.delim == delimNone {
806 c1, i := tSpecialTagEnd(c, s)
808 // A special end tag (`</script>`) has been seen and
809 // all content preceding it has been consumed.
812 // Consider all content up to any end tag.
813 return transitionFunc[c.state](c, s[:i])
816 // We are at the beginning of an attribute value.
818 i := bytes.IndexAny(s, delimEnds[c.delim])
822 if c.delim == delimSpaceOrTagEnd {
823 // https://www.w3.org/TR/html5/syntax.html#attribute-value-(unquoted)-state
824 // lists the runes below as error characters.
825 // Error out because HTML parsers may differ on whether
826 // "<a id= onclick=f(" ends inside id's or onclick's value,
827 // "<a class=`foo " ends inside a value,
828 // "<a style=font:'Arial'" needs open-quote fixup.
829 // IE treats '`' as a quotation character.
830 if j := bytes.IndexAny(s[:i], "\"'<=`"); j >= 0 {
833 err: errorf(ErrBadHTML, nil, 0, "%q in unquoted attr: %q", s[j:j+1], s[:i]),
838 // Remain inside the attribute.
839 // Decode the value so non-HTML rules can easily handle
840 // <button onclick="alert("Hi!")">
841 // without having to entity decode token boundaries.
842 for u := []byte(html.UnescapeString(string(s))); len(u) != 0; {
843 c1, i1 := transitionFunc[c.state](c, u)
851 // If this is a non-JS "type" attribute inside "script" tag, do not treat the contents as JS.
852 if c.state == stateAttr && c.element == elementScript && c.attr == attrScriptType && !isJSType(string(s[:i])) {
853 element = elementNone
856 if c.delim != delimSpaceOrTagEnd {
857 // Consume any quote.
860 // On exiting an attribute, we discard all state information
861 // except the state and element.
862 return context{state: stateTag, element: element}, i
865 // editActionNode records a change to an action pipeline for later commit.
866 func (e *escaper) editActionNode(n *parse.ActionNode, cmds []string) {
867 if _, ok := e.actionNodeEdits[n]; ok {
868 panic(fmt.Sprintf("node %s shared between templates", n))
870 e.actionNodeEdits[n] = cmds
873 // editTemplateNode records a change to a {{template}} callee for later commit.
874 func (e *escaper) editTemplateNode(n *parse.TemplateNode, callee string) {
875 if _, ok := e.templateNodeEdits[n]; ok {
876 panic(fmt.Sprintf("node %s shared between templates", n))
878 e.templateNodeEdits[n] = callee
881 // editTextNode records a change to a text node for later commit.
882 func (e *escaper) editTextNode(n *parse.TextNode, text []byte) {
883 if _, ok := e.textNodeEdits[n]; ok {
884 panic(fmt.Sprintf("node %s shared between templates", n))
886 e.textNodeEdits[n] = text
889 // commit applies changes to actions and template calls needed to contextually
890 // autoescape content and adds any derived templates to the set.
891 func (e *escaper) commit() {
892 for name := range e.output {
893 e.template(name).Funcs(funcMap)
895 // Any template from the name space associated with this escaper can be used
896 // to add derived templates to the underlying text/template name space.
897 tmpl := e.arbitraryTemplate()
898 for _, t := range e.derived {
899 if _, err := tmpl.text.AddParseTree(t.Name(), t.Tree); err != nil {
900 panic("error adding derived template")
903 for n, s := range e.actionNodeEdits {
904 ensurePipelineContains(n.Pipe, s)
906 for n, name := range e.templateNodeEdits {
909 for n, s := range e.textNodeEdits {
912 // Reset state that is specific to this commit so that the same changes are
913 // not re-applied to the template on subsequent calls to commit.
914 e.called = make(map[string]bool)
915 e.actionNodeEdits = make(map[*parse.ActionNode][]string)
916 e.templateNodeEdits = make(map[*parse.TemplateNode]string)
917 e.textNodeEdits = make(map[*parse.TextNode][]byte)
920 // template returns the named template given a mangled template name.
921 func (e *escaper) template(name string) *template.Template {
922 // Any template from the name space associated with this escaper can be used
923 // to look up templates in the underlying text/template name space.
924 t := e.arbitraryTemplate().text.Lookup(name)
931 // arbitraryTemplate returns an arbitrary template from the name space
932 // associated with e and panics if no templates are found.
933 func (e *escaper) arbitraryTemplate() *Template {
934 for _, t := range e.ns.set {
937 panic("no templates in name space")
940 // Forwarding functions so that clients need only import this package
941 // to reach the general escaping functions of text/template.
943 // HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
944 func HTMLEscape(w io.Writer, b []byte) {
945 template.HTMLEscape(w, b)
948 // HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
949 func HTMLEscapeString(s string) string {
950 return template.HTMLEscapeString(s)
953 // HTMLEscaper returns the escaped HTML equivalent of the textual
954 // representation of its arguments.
955 func HTMLEscaper(args ...any) string {
956 return template.HTMLEscaper(args...)
959 // JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
960 func JSEscape(w io.Writer, b []byte) {
961 template.JSEscape(w, b)
964 // JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
965 func JSEscapeString(s string) string {
966 return template.JSEscapeString(s)
969 // JSEscaper returns the escaped JavaScript equivalent of the textual
970 // representation of its arguments.
971 func JSEscaper(args ...any) string {
972 return template.JSEscaper(args...)
975 // URLQueryEscaper returns the escaped value of the textual representation of
976 // its arguments in a form suitable for embedding in a URL query.
977 func URLQueryEscaper(args ...any) string {
978 return template.URLQueryEscaper(args...)