Skip to content

Commit

Permalink
fix: eventsource escapes as done in sockjs-node (#102)
Browse files Browse the repository at this point in the history
The EventSource frame writer does no escaping of its messages.  This has caused a problem when updating from sockjs-client-0.3.4 to a more modern sockjs-1.5.x

Changes:
* eventsource escapes as done in sockjs-node
* unit test of eventSourceFrameWriter to confirm escaping
  • Loading branch information
aronatkins committed Oct 1, 2021
1 parent db9cf16 commit ad26384
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
11 changes: 10 additions & 1 deletion v3/sockjs/eventsource.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
)

func (h *Handler) eventSource(rw http.ResponseWriter, req *http.Request) {
Expand Down Expand Up @@ -34,6 +36,13 @@ func (h *Handler) eventSource(rw http.ResponseWriter, req *http.Request) {

type eventSourceFrameWriter struct{}

var escaper *strings.Replacer = strings.NewReplacer(
"%", url.QueryEscape("%"),
"\n", url.QueryEscape("\n"),
"\r", url.QueryEscape("\r"),
"\x00", url.QueryEscape("\x00"),
)

func (*eventSourceFrameWriter) write(w io.Writer, frame string) (int, error) {
return fmt.Fprintf(w, "data: %s\r\n\r\n", frame)
return fmt.Fprintf(w, "data: %s\r\n\r\n", escaper.Replace(frame))
}
16 changes: 16 additions & 0 deletions v3/sockjs/eventsource_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package sockjs

import (
"bytes"
"context"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -91,3 +92,18 @@ func TestHandler_EventSourceConnectionInterrupted(t *testing.T) {
t.Errorf("session should be closed")
}
}

func TestEventSourceFrameWriter(t *testing.T) {
writer := new(eventSourceFrameWriter)
out := new(bytes.Buffer)

// Confirm that "important" characters are escaped, but others pass
// through unmodified.
_, err := writer.write(out, "escaped: %\r\n;unescaped: +&#")
if err != nil {
t.Errorf("unexpected write error: %s", err)
}
if out.String() != "data: escaped: %25%0D%0A;unescaped: +&#\r\n\r\n" {
t.Errorf("wrong, got '%v'", out.String())
}
}

0 comments on commit ad26384

Please sign in to comment.