Skip to content

Commit

Permalink
fix(gnodev/pkg/emitter): use html/template not text/template for HTML…
Browse files Browse the repository at this point in the history
… generation (#3545)

This change uses html/template instead of text/template for HTML
generation and also locks in tests to detect such subtle regressions and
thus help prevent future cross-side scripting (XSS) attacks if later the
scripts evolve and take in user input.

Fixes #3544
  • Loading branch information
odeke-em authored Jan 20, 2025
1 parent 7a397a2 commit 4135ffe
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
2 changes: 1 addition & 1 deletion contribs/gnodev/pkg/emitter/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import (
_ "embed"
"encoding/json"
"fmt"
"html/template"
"net/http"
"strings"
"sync"
"text/template"

"github.com/gnolang/gno/contribs/gnodev/pkg/events"
)
Expand Down
43 changes: 43 additions & 0 deletions contribs/gnodev/pkg/emitter/middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package emitter

import (
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"testing"

"github.com/stretchr/testify/require"
)

func TestMiddlewareUsesHTMLTemplate(t *testing.T) {
tests := []struct {
name string
remote string
want string
}{
{"normal remote", "localhost:9999", "const ws = new WebSocket('ws://localhost:9999');"},
{"xss'd remote", `localhost:9999');alert('pwned`, "const ws = new WebSocket('ws://localhost:9999');alert('pwned');"},
}

// As the code revolves, add more search patterns here.
reWebsocket := regexp.MustCompile("const ws = new WebSocket[^\n]+")

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
mdw := NewMiddleware(tt.remote, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "text/html")
fmt.Fprintf(rw, "<body></body>")
}))
rec.Header().Set("Content-Type", "text/html")
req := httptest.NewRequest("GET", "https://gno.land/example", nil)
mdw.ServeHTTP(rec, req)

targets := reWebsocket.FindAllString(rec.Body.String(), -1)
require.True(t, len(targets) > 0)
body := targets[0]
require.Equal(t, body, tt.want)
})
}
}
4 changes: 3 additions & 1 deletion contribs/gnodev/pkg/emitter/static/hotreload.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
(function() {
// Define the events that will trigger a page reload
const eventsReload = {{ .ReloadEvents | json }};
const eventsReload = [
{{range .ReloadEvents}}'{{.}}',{{end}}
];

// Establish the WebSocket connection to the event server
const ws = new WebSocket('ws://{{- .Remote -}}');
Expand Down

0 comments on commit 4135ffe

Please sign in to comment.