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

fix: Django autoescape should be enable by default #326

Merged
merged 7 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
14 changes: 12 additions & 2 deletions django/django.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ func (e *Engine) Load() error {
pongoset := pongo2.NewSet("default", pongoloader)
// Set template settings
pongoset.Globals.Update(e.Funcmap)
pongo2.SetAutoescape(false)
// Enable autoescaping
pongo2.SetAutoescape(true)

// Loop trough each Directory and register template files
walkFn := func(path string, info os.FileInfo, err error) error {
Expand Down Expand Up @@ -231,7 +232,16 @@ func (e *Engine) Render(out io.Writer, name string, binding interface{}, layout
if bind == nil {
bind = make(map[string]interface{}, 1)
}
bind[e.LayoutName] = parsed

// Workaround for custom {{embed}} tag
// Mark the `embed` variable as safe
// it has already been escaped above
// e.LayoutName will be 'embed'
safeEmbed := pongo2.AsSafeValue(parsed)

// Add the safe value to the binding map
bind[e.LayoutName] = safeEmbed

lay := e.Templates[layout[0]]
if lay == nil {
return fmt.Errorf("LayoutName %s does not exist", layout[0])
Expand Down
15 changes: 15 additions & 0 deletions django/django_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,21 @@ func Test_Invalid_Layout(t *testing.T) {
require.Error(t, err)
}

func Test_XSS(t *testing.T) {
engine := New("./views", ".django")
require.NoError(t, engine.Load())

var buf bytes.Buffer
err := engine.Render(&buf, "index", map[string]interface{}{
"Title": "<script>alert('XSS')</script>",
}, "layouts/main")
require.NoError(t, err)

expect := `<!DOCTYPE html><html><head><title>Main</title></head><body><h2>Header</h2><h1>&lt;script&gt;alert(&#39;XSS&#39;)&lt;/script&gt;</h1><h2>Footer</h2></body></html>`
result := trim(buf.String())
require.Equal(t, expect, result)
}

func Benchmark_Django(b *testing.B) {
expectSimple := `<h1>Hello, World!</h1>`
expectExtended := `<!DOCTYPE html><html><head><title>Main</title></head><body><h2>Header</h2><h1>Hello, Admin!</h1><h2>Footer</h2></body></html>`
Expand Down
Loading