Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented auto-escape functionality and provided a default escape replacer for HTML. #70

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,11 @@ func (e *Engine) ParseTemplateAndCache(source []byte, path string, line int) (*T
e.cfg.Cache[path] = source
return t, err
}

// SetAutoEscapeReplacer enables auto-escape functionality where the output of expression blocks ({{ ... }}) is
// passed though a render.Replacer during rendering, unless it's been marked as safe by applying the 'safe' filter.
// This filter is automatically registered when this method is called. The filter must be applied last.
// A replacer is provided for escaping HTML (see render.HtmlEscaper).
func (e *Engine) SetAutoEscapeReplacer(replacer render.Replacer) {
e.cfg.SetAutoEscapeReplacer(replacer)
}
24 changes: 21 additions & 3 deletions expressions/filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ func (e FilterError) Error() string {

type valueFn func(Context) values.Value

func (c *Config) ensureMapIsCreated() {
if c.filters == nil {
c.filters = make(map[string]interface{})
}
}

// AddFilter adds a filter to the filter dictionary.
func (c *Config) AddFilter(name string, fn interface{}) {
rf := reflect.ValueOf(fn)
Expand All @@ -46,12 +52,24 @@ func (c *Config) AddFilter(name string, fn interface{}) {
// case rf.Type().Out(1).Implements(…):
// panic(typeError("a filter's second output must be type error"))
}
if len(c.filters) == 0 {
c.filters = make(map[string]interface{})
}
c.ensureMapIsCreated()
c.filters[name] = fn
}

func (c *Config) AddSafeFilter() {
if c.filters["safe"] == nil {
c.ensureMapIsCreated()
c.filters["safe"] = func(in interface{}) interface{} {
if in, alreadySafe := in.(values.SafeValue); alreadySafe {
return in
}
return values.SafeValue{
Value: in,
}
}
}
}

var closureType = reflect.TypeOf(closure{})
var interfaceType = reflect.TypeOf([]interface{}{}).Elem()

Expand Down
21 changes: 21 additions & 0 deletions render/autoescape.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package render

import (
"io"
"strings"
)

// HtmlEscaper is a Replacer that escapes HTML markup characters. Copied from Go standard library because it's
// not exposed.
var HtmlEscaper = strings.NewReplacer(
`&`, "&",
`'`, "'", // "'" is shorter than "'" and apos was not in HTML until HTML5.
`<`, "&lt;",
`>`, "&gt;",
`"`, "&#34;", // "&#34;" is shorter than "&quot;".
)

// Replacer interface is used for auto-escape.
type Replacer interface {
WriteString(io.Writer, string) (int, error)
}
74 changes: 74 additions & 0 deletions render/autoescape_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package render

import (
"bytes"
"testing"

"github.com/osteele/liquid/parser"
"github.com/stretchr/testify/require"
)

func TestRenderEscapeFilter(t *testing.T) {
cfg := NewConfig()
cfg.SetAutoEscapeReplacer(HtmlEscaper)
buf := new(bytes.Buffer)

f := func(t *testing.T, tmpl string, bindings map[string]interface{}, out string) {
buf.Reset()
root, err := cfg.Compile(tmpl, parser.SourceLoc{})
require.NoErrorf(t, err, "")
err = Render(root, buf, bindings, cfg)
require.NoErrorf(t, err, "")
require.Equalf(t, out, buf.String(), "")
}

t.Run("unsafe", func(t *testing.T) {
f(t,
`{{ input }}`,
map[string]interface{}{
"input": "<script>doEvilStuff()</script>",
},
"&lt;script&gt;doEvilStuff()&lt;/script&gt;",
)
})

t.Run("safe", func(t *testing.T) {
f(t,
`{{ input|safe }}`,
map[string]interface{}{
"input": "<script>doGoodStuff()</script>",
},
"<script>doGoodStuff()</script>",
)
})

t.Run("double safe", func(t *testing.T) {
f(t,
`{{ input|safe|safe }}`,
map[string]interface{}{
"input": "<script>doGoodStuff()</script>",
},
"<script>doGoodStuff()</script>",
)
})

t.Run("unsafe slice result", func(t *testing.T) {
f(t,
`{{ input }}`,
map[string]interface{}{
"input": []interface{}{"<a>", "<b>"},
},
"&lt;a&gt;&lt;b&gt;",
)
})

t.Run("safe slice result", func(t *testing.T) {
f(t,
`{{ input|safe }}`,
map[string]interface{}{
"input": []interface{}{"<a>", "<b>"},
},
"<a><b>",
)
})
}
7 changes: 7 additions & 0 deletions render/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ type Config struct {
parser.Config
grammar
Cache map[string][]byte

escapeReplacer Replacer
}

type grammar struct {
Expand All @@ -24,3 +26,8 @@ func NewConfig() Config {
}
return Config{Config: parser.NewConfig(g), grammar: g, Cache: map[string][]byte{}}
}

func (c *Config) SetAutoEscapeReplacer(replacer Replacer) {
c.escapeReplacer = replacer
c.AddSafeFilter()
}
31 changes: 29 additions & 2 deletions render/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,22 @@ func (n *ObjectNode) render(w *trimWriter, ctx nodeContext) Error {
if err != nil {
return wrapRenderError(err, n)
}
if err := wrapRenderError(writeObject(w, value), n); err != nil {
return err
if sv, isSafe := value.(values.SafeValue); isSafe {
err = writeObject(w, sv.Value)
} else {
var fw io.Writer
if replacer := ctx.config.escapeReplacer; replacer != nil {
fw = &replacerWriter{
replacer: replacer,
w: w,
}
} else {
fw = w
}
err = writeObject(fw, value)
}
if err != nil {
return wrapRenderError(err, n)
}
w.TrimRight(n.TrimRight)
return nil
Expand Down Expand Up @@ -129,3 +143,16 @@ func writeObject(w io.Writer, value interface{}) error {
return err
}
}

type replacerWriter struct {
replacer Replacer
w io.Writer
}

func (h *replacerWriter) Write(p []byte) (n int, err error) {
return h.WriteString(string(p))
}

func (h *replacerWriter) WriteString(s string) (n int, err error) {
return h.replacer.WriteString(h.w, s)
}
6 changes: 6 additions & 0 deletions values/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,9 @@ func (sv stringValue) PropertyValue(iv Value) Value {
}
return nilValue
}

// SafeValue is a wrapped interface{} to mark it as being safe so that auto-escape is not applied.
// It is used by the 'safe' filter which is added when (*Engine).SetAutoEscapeReplacer() is called.
type SafeValue struct {
Value interface{}
}