Documentation
¶
Overview ¶
Package template (html/template) implements data-driven templates for generating HTML output safe against code injection. It provides the same interface as text/template and should be used instead of text/template whenever the output is HTML.
The documentation here focuses on the security features of the package. For information about how to program the templates themselves, see the documentation for text/template.
Introduction ¶
This package wraps text/template so you can share its template API to parse and execute HTML templates safely.
tmpl, err := template.New("name").Parse(...)
// Error checking elided
err = tmpl.Execute(out, data)
If successful, tmpl will now be injection-safe. Otherwise, err is an error defined in the docs for ErrorCode.
HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts.
Comments are stripped from output, except for those passed in via the HTML, CSS, and JS types for their respective contexts.
The security model used by this package assumes that template authors are trusted, while Execute's data parameter is not. More details are provided below.
Example
import "text/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
produces
Hello, <script>alert('you have been pwned')</script>!
but the contextual autoescaping in html/template
import "html/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
produces safe, escaped HTML output
Hello, <script>alert('you have been pwned')</script>!
Contexts ¶
This package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing functions to each simple action pipeline, so given the excerpt
<a href="/search?q={{.}}">{{.}}</a>
At parse time each {{.}} is overwritten to add escaping functions as necessary. In this case it becomes
<a href="/search?q={{. | urlescaper | attrescaper}}">{{. | htmlescaper}}</a>
where urlescaper, attrescaper, and htmlescaper are aliases for internal escaping functions.
For these internal escaping functions, if an action pipeline evaluates to a nil interface value, it is treated as though it were an empty string.
Namespaced and data- attributes ¶
Attributes with a namespace are treated as if they had no namespace. Given the excerpt
<a my:href="{{.}}"></a>
At parse time the attribute will be treated as if it were just "href". So at parse time the template becomes:
<a my:href="{{. | urlescaper | attrescaper}}"></a>
Similarly to attributes with namespaces, attributes with a "data-" prefix are treated as if they had no "data-" prefix. So given
<a data-href="{{.}}"></a>
At parse time this becomes
<a data-href="{{. | urlescaper | attrescaper}}"></a>
If an attribute has both a namespace and a "data-" prefix, only the namespace will be removed when determining the context. For example
<a my:data-href="{{.}}"></a>
This is handled as if "my:data-href" was just "data-href" and not "href" as it would be if the "data-" prefix were to be ignored too. Thus at parse time this becomes just
<a my:data-href="{{. | attrescaper}}"></a>
As a special case, attributes with the namespace "xmlns" are always treated as containing URLs. Given the excerpts
<a xmlns:title="{{.}}"></a>
<a xmlns:href="{{.}}"></a>
<a xmlns:onclick="{{.}}"></a>
At parse time they become:
<a xmlns:title="{{. | urlescaper | attrescaper}}"></a>
<a xmlns:href="{{. | urlescaper | attrescaper}}"></a>
<a xmlns:onclick="{{. | urlescaper | attrescaper}}"></a>
Errors ¶
See the documentation of ErrorCode for details.
A fuller picture ¶
The rest of this package comment may be skipped on first reading; it includes details necessary to understand escaping contexts and error messages. Most users will not need to understand these details.
Contexts ¶
Assuming {{.}} is `O'Reilly: How are <i>you</i>?`, the table below shows how {{.}} appears when used in the context to the left.
Context {{.}} After
{{.}} O'Reilly: How are <i>you</i>?
<a title='{{.}}'> O'Reilly: How are you?
<a href="/{{.}}"> O'Reilly: How are %3ci%3eyou%3c/i%3e?
<a href="?q={{.}}"> O'Reilly%3a%20How%20are%3ci%3e...%3f
<a onx='f("{{.}}")'> O\x27Reilly: How are \x3ci\x3eyou...?
<a onx='f({{.}})'> "O\x27Reilly: How are \x3ci\x3eyou...?"
<a onx='pattern = /{{.}}/;'> O\x27Reilly: How are \x3ci\x3eyou...\x3f
If used in an unsafe context, then the value might be filtered out:
Context {{.}} After
<a href="{{.}}"> #ZgotmplZ
since "O'Reilly:" is not an allowed protocol like "http:".
If {{.}} is the innocuous word, `left`, then it can appear more widely,
Context {{.}} After
{{.}} left
<a title='{{.}}'> left
<a href='{{.}}'> left
<a href='/{{.}}'> left
<a href='?dir={{.}}'> left
<a style="border-{{.}}: 4px"> left
<a style="align: {{.}}"> left
<a style="background: '{{.}}'> left
<a style="background: url('{{.}}')> left
<style>p.{{.}} {color:red}</style> left
Non-string values can be used in JavaScript contexts. If {{.}} is
struct{A,B string}{ "foo", "bar" }
in the escaped template
<script>var pair = {{.}};</script>
then the template output is
<script>var pair = {"A": "foo", "B": "bar"};</script>
See package json to understand how non-string content is marshaled for embedding in JavaScript contexts.
Typed Strings ¶
By default, this package assumes that all pipelines produce a plain text string. It adds escaping pipeline stages necessary to correctly and safely embed that plain text string in the appropriate context.
When a data value is not plain text, you can make sure it is not over-escaped by marking it with its type.
Types HTML, JS, URL, and others from content.go can carry safe content that is exempted from escaping.
The template
Hello, {{.}}!
can be invoked with
tmpl.Execute(out, template.HTML(`<b>World</b>`))
to produce
Hello, <b>World</b>!
instead of the
Hello, <b>World<b>!
that would have been produced if {{.}} was a regular string.
Security Model ¶
https://web.archive.org/web/20160501113828/http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html#problem_definition defines "safe" as used by this package.
This package assumes that template authors are trusted, that Execute's data parameter is not, and seeks to preserve the properties below in the face of untrusted data:
Structure Preservation Property: "... when a template author writes an HTML tag in a safe templating language, the browser will interpret the corresponding portion of the output as a tag regardless of the values of untrusted data, and similarly for other structures such as attribute boundaries and JS and CSS string boundaries."
Code Effect Property: "... only code specified by the template author should run as a result of injecting the template output into a page and all code specified by the template author should run as a result of the same."
Least Surprise Property: "A developer (or code reviewer) familiar with HTML, CSS, and JavaScript, who knows that contextual autoescaping happens should be able to look at a {{.}} and correctly infer what sanitization happens."
Previously, ECMAScript 6 template literal were disabled by default, and could be enabled with the GODEBUG=jstmpllitinterp=1 environment variable. Template literals are now supported by default, and setting jstmpllitinterp has no effect.
Example ¶
package main
import (
"html/template"
"log"
"os"
)
func main() {
const tpl = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{.Title}}</title>
</head>
<body>
{{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}}
</body>
</html>`
check := func(err error) {
if err != nil {
log.Fatal(err)
}
}
t, err := template.New("webpage").Parse(tpl)
check(err)
data := struct {
Title string
Items []string
}{
Title: "My page",
Items: []string{
"My photos",
"My blog",
},
}
err = t.Execute(os.Stdout, data)
check(err)
noItems := struct {
Title string
Items []string
}{
Title: "My another page",
Items: []string{},
}
err = t.Execute(os.Stdout, noItems)
check(err)
}
Output: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>My page</title> </head> <body> <div>My photos</div><div>My blog</div> </body> </html> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>My another page</title> </head> <body> <div><strong>no rows</strong></div> </body> </html>
Example (Autoescaping) ¶
package main
import (
"html/template"
"log"
"os"
)
func main() {
check := func(err error) {
if err != nil {
log.Fatal(err)
}
}
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
check(err)
err = t.ExecuteTemplate(os.Stdout, "T", "<script>alert('you have been pwned')</script>")
check(err)
}
Output: Hello, <script>alert('you have been pwned')</script>!
Example (Escape) ¶
package main
import (
"fmt"
"html/template"
"os"
)
func main() {
const s = `"Fran & Freddie's Diner" <tasty@example.com>`
v := []any{`"Fran & Freddie's Diner"`, ' ', `<tasty@example.com>`}
fmt.Println(template.HTMLEscapeString(s))
template.HTMLEscape(os.Stdout, []byte(s))
fmt.Fprintln(os.Stdout, "")
fmt.Println(template.HTMLEscaper(v...))
fmt.Println(template.JSEscapeString(s))
template.JSEscape(os.Stdout, []byte(s))
fmt.Fprintln(os.Stdout, "")
fmt.Println(template.JSEscaper(v...))
fmt.Println(template.URLQueryEscaper(v...))
}
Output: "Fran & Freddie's Diner" <tasty@example.com> "Fran & Freddie's Diner" <tasty@example.com> "Fran & Freddie's Diner"32<tasty@example.com> \"Fran \u0026 Freddie\'s Diner\" \u003Ctasty@example.com\u003E \"Fran \u0026 Freddie\'s Diner\" \u003Ctasty@example.com\u003E \"Fran \u0026 Freddie\'s Diner\"32\u003Ctasty@example.com\u003E %22Fran+%26+Freddie%27s+Diner%2232%3Ctasty%40example.com%3E
Index ¶
- func HTMLEscape(w io.Writer, b []byte)
- func HTMLEscapeString(s string) string
- func HTMLEscaper(args ...any) string
- func IsTrue(val any) (truth, ok bool)
- func JSEscape(w io.Writer, b []byte)
- func JSEscapeString(s string) string
- func JSEscaper(args ...any) string
- func URLQueryEscaper(args ...any) string
- type CSS
- type Error
- type ErrorCode
- type FuncMap
- type HTML
- type HTMLAttr
- type JS
- type JSStr
- type Srcset
- type Template
- func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)
- func (t *Template) Clone() (*Template, error)
- func (t *Template) DefinedTemplates() string
- func (t *Template) Delims(left, right string) *Template
- func (t *Template) Execute(wr io.Writer, data any) error
- func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error
- func (t *Template) Funcs(funcMap FuncMap) *Template
- func (t *Template) Lookup(name string) *Template
- func (t *Template) Name() string
- func (t *Template) New(name string) *Template
- func (t *Template) Option(opt ...string) *Template
- func (t *Template) Parse(text string) (*Template, error)
- func (t *Template) ParseFS(fs fs.FS, patterns ...string) (*Template, error)
- func (t *Template) ParseFiles(filenames ...string) (*Template, error)
- func (t *Template) ParseGlob(pattern string) (*Template, error)
- func (t *Template) Templates() []*Template
- type URL
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HTMLEscape ¶
HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
func HTMLEscapeString ¶
HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
func HTMLEscaper ¶
HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments.
func IsTrue ¶ added in go1.6
IsTrue reports whether the value is 'true', in the sense of not the zero of its type, and whether the value has a meaningful truth value. This is the definition of truth used by if and other such actions.
func JSEscapeString ¶
JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
func JSEscaper ¶
JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments.
func URLQueryEscaper ¶
URLQueryEscaper returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query.
Types ¶
type CSS ¶
type CSS string
CSS encapsulates known safe content that matches any of:
- The CSS3 stylesheet production, such as `p { color: purple }`.
- The CSS3 rule production, such as `a[href=~"https:"].foo#bar`.
- CSS3 declaration productions, such as `color: red; margin: 2px`.
- The CSS3 value production, such as `rgba(0, 0, 255, 127)`.
See https://www.w3.org/TR/css3-syntax/#parsing and https://web.archive.org/web/20090211114933/http://w3.org/TR/css3-syntax#style
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
type Error ¶
type Error struct {
// ErrorCode describes the kind of error.
ErrorCode ErrorCode
// Node is the node that caused the problem, if known.
// If not nil, it overrides Name and Line.
Node parse.Node
// Name is the name of the template in which the error was encountered.
Name string
// Line is the line number of the error in the template source or 0.
Line int
// Description is a human-readable description of the problem.
Description string
}
Error describes a problem encountered during template Escaping.
type ErrorCode ¶
type ErrorCode int
ErrorCode is a code for a kind of error.
const ( // OK indicates the lack of an error. OK ErrorCode = iota // ErrAmbigContext: "... appears in an ambiguous context within a URL" // Example: // <a href=" // {{if .C}} // /path/ // {{else}} // /search?q= // {{end}} // {{.X}} // "> // Discussion: // {{.X}} is in an ambiguous URL context since, depending on {{.C}}, // it may be either a URL suffix or a query parameter. // Moving {{.X}} into the condition removes the ambiguity: // <a href="{{if .C}}/path/{{.X}}{{else}}/search?q={{.X}}"> ErrAmbigContext // ErrBadHTML: "expected space, attr name, or end of tag, but got ...", // "... in unquoted attr", "... in attribute name" // Example: // <a href = /search?q=foo> // <href=foo> // <form na<e=...> // <option selected< // Discussion: // This is often due to a typo in an HTML element, but some runes // are banned in tag names, attribute names, and unquoted attribute // values because they can tickle parser ambiguities. // Quoting all attributes is the best policy. ErrBadHTML // ErrBranchEnd: "{{if}} branches end in different contexts" // Examples: // {{if .C}}<a href="{{end}}{{.X}} // <script {{with .T}}type="{{.}}"{{end}}> // Discussion: // Package html/template statically examines each path through an // {{if}}, {{range}}, or {{with}} to escape any following pipelines. // The first example is ambiguous since {{.X}} might be an HTML text node, // or a URL prefix in an HTML attribute. The context of {{.X}} is // used to figure out how to escape it, but that context depends on // the run-time value of {{.C}} which is not statically known. // The second example is ambiguous as the script type attribute // can change the type of escaping needed for the script contents. // // The problem is usually something like missing quotes or angle // brackets, or can be avoided by refactoring to put the two contexts // into different branches of an if, range or with. If the problem // is in a {{range}} over a collection that should never be empty, // adding a dummy {{else}} can help. ErrBranchEnd // ErrEndContext: "... ends in a non-text context: ..." // Examples: // <div // <div title="no close quote> // <script>f() // Discussion: // Executed templates should produce a DocumentFragment of HTML. // Templates that end without closing tags will trigger this error. // Templates that should not be used in an HTML context or that // produce incomplete Fragments should not be executed directly. // // {{define "main"}} <script>{{template "helper"}}</script> {{end}} // {{define "helper"}} document.write(' <div title=" ') {{end}} // // "helper" does not produce a valid document fragment, so should // not be Executed directly. ErrEndContext // ErrNoSuchTemplate: "no such template ..." // Examples: // {{define "main"}}<div {{template "attrs"}}>{{end}} // {{define "attrs"}}href="{{.URL}}"{{end}} // Discussion: // Package html/template looks through template calls to compute the // context. // Here the {{.URL}} in "attrs" must be treated as a URL when called // from "main", but you will get this error if "attrs" is not defined // when "main" is parsed. ErrNoSuchTemplate // ErrOutputContext: "cannot compute output context for template ..." // Examples: // {{define "t"}}{{if .T}}{{template "t" .T}}{{end}}{{.H}}",{{end}} // Discussion: // A recursive template does not end in the same context in which it // starts, and a reliable output context cannot be computed. // Look for typos in the named template. // If the template should not be called in the named start context, // look for calls to that template in unexpected contexts. // Maybe refactor recursive templates to not be recursive. ErrOutputContext // ErrPartialCharset: "unfinished JS regexp charset in ..." // Example: // <script>var pattern = /foo[{{.Chars}}]/</script> // Discussion: // Package html/template does not support interpolation into regular // expression literal character sets. ErrPartialCharset // ErrPartialEscape: "unfinished escape sequence in ..." // Example: // <script>alert("\{{.X}}")</script> // Discussion: // Package html/template does not support actions following a // backslash. // This is usually an error and there are better solutions; for // example // <script>alert("{{.X}}")</script> // should work, and if {{.X}} is a partial escape sequence such as