From 87b925bad107ef75039fb61bcf4df66544796599 Mon Sep 17 00:00:00 2001 From: Mohith26 <109003762+Mohith26@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:34:11 -0500 Subject: [PATCH 1/2] Fix two data races in the websocket exec path wsCmd.Close called SetWriteDeadline on the connection while the adapter's write loop could still be inside WriteMessage. gorilla's WriteControl takes its own deadline and is safe to call alongside another writer, so the SetWriteDeadline call is dropped. The TTY resize goroutine read the os.Stdin global 10ms after start, after Start had already returned. It now captures os.Stdin before Start returns and exits early if the command finishes first. Both are covered by tests that fail under -race without the change. Fixes #48 --- websocket.go | 16 ++++-- websocket_race_test.go | 115 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 4 deletions(-) create mode 100644 websocket_race_test.go diff --git a/websocket.go b/websocket.go index d3bce14..91f3300 100644 --- a/websocket.go +++ b/websocket.go @@ -267,10 +267,17 @@ func (c *wsCmd) start() { // Send initial resize message for TTY mode if c.Tty { + // Read os.Stdin here, before Start returns, so a caller that swaps + // it afterwards does not race with this goroutine. + stdin := os.Stdin go func() { - time.Sleep(10 * time.Millisecond) - if term.IsTerminal(int(os.Stdin.Fd())) { - if width, height, err := term.GetSize(int(os.Stdin.Fd())); err == nil { + select { + case <-time.After(10 * time.Millisecond): + case <-c.doneChan: + return + } + if term.IsTerminal(int(stdin.Fd())) { + if width, height, err := term.GetSize(int(stdin.Fd())); err == nil { c.Resize(uint16(width), uint16(height)) } } @@ -686,8 +693,9 @@ func (c *wsCmd) IsDone() bool { // Close gracefully closes the WebSocket connection func (c *wsCmd) Close() error { if c.conn != nil { + // WriteControl takes its own deadline and is safe to call while the + // adapter's write loop is writing; SetWriteDeadline is not. deadline := time.Now().Add(time.Second) - c.conn.SetWriteDeadline(deadline) c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), deadline) diff --git a/websocket_race_test.go b/websocket_race_test.go new file mode 100644 index 0000000..39b2832 --- /dev/null +++ b/websocket_race_test.go @@ -0,0 +1,115 @@ +package sprites + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +// endlessReader returns data forever so the write loop stays busy. +type endlessReader struct{} + +func (endlessReader) Read(p []byte) (int, error) { + for i := range p { + p[i] = 'x' + } + + return len(p), nil +} + +func newExitingServer(t *testing.T, exitFrame func(*websocket.Conn) error) *httptest.Server { + t.Helper() + + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + go func() { + for { + if _, _, err := conn.ReadMessage(); err != nil { + return + } + } + }() + _ = exitFrame(conn) + time.Sleep(50 * time.Millisecond) + })) +} + +func wsURL(server *httptest.Server) string { + return "ws" + strings.TrimPrefix(server.URL, "http") +} + +// Close used to call SetWriteDeadline on the connection while the adapter's +// write loop could still be inside WriteMessage. Run with -race. +func TestCloseDoesNotRaceWriteLoop(t *testing.T) { + server := newExitingServer(t, func(conn *websocket.Conn) error { + time.Sleep(5 * time.Millisecond) + return conn.WriteMessage(websocket.BinaryMessage, []byte{byte(StreamExit), 0}) + }) + defer server.Close() + + for i := 0; i < 20; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, wsURL(server), nil) + if err != nil { + cancel() + t.Fatalf("NewRequestWithContext() error = %v", err) + } + wsCmd := newWSCmdContext(ctx, req, "cat") + wsCmd.Stdin = endlessReader{} + if err := wsCmd.Start(); err != nil { + cancel() + t.Fatalf("Start() error = %v", err) + } + _ = wsCmd.Wait() + cancel() + } +} + +// The TTY resize goroutine used to read the os.Stdin global 10ms after +// start, so a caller that swapped os.Stdin and restored it once the command +// finished raced with it. Run with -race. +func TestTTYResizeDoesNotReadStdinAfterCommandReturns(t *testing.T) { + server := newExitingServer(t, func(conn *websocket.Conn) error { + return conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"exit","exit_code":0}`)) + }) + defer server.Close() + + stdinReader, stdinWriter, err := os.Pipe() + if err != nil { + t.Fatalf("os.Pipe() error = %v", err) + } + defer stdinReader.Close() + defer stdinWriter.Close() + + original := os.Stdin + os.Stdin = stdinReader + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, wsURL(server), nil) + if err != nil { + os.Stdin = original + t.Fatalf("NewRequestWithContext() error = %v", err) + } + wsCmd := newWSCmdContext(ctx, req, "sh") + wsCmd.Tty = true + if err := wsCmd.Start(); err != nil { + os.Stdin = original + t.Fatalf("Start() error = %v", err) + } + _ = wsCmd.Wait() + + os.Stdin = original + // Give a detached resize goroutine time to run if one is still pending. + time.Sleep(30 * time.Millisecond) +} From 81018e35cd451cfbd00e882eca61337a905135d9 Mon Sep 17 00:00:00 2001 From: Mohith Gajjela <109003762+Mohith26@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:50:59 -0500 Subject: [PATCH 2/2] Fix the same Close race in proxyConn and tighten the TTY test proxyConn.Close called SetWriteDeadline outside writeMu, racing with a concurrent Write inside WriteMessage, the same pattern as wsCmd.Close. net.Conn allows Close while Write is in progress, so drop the call and rely on the deadline WriteControl already takes. The TTY resize test's server exited before the goroutine's 10ms delay, so it only covered the early return, not the stdin capture. Delay the exit frame so the goroutine reads stdin while the command runs. That also showed the goroutine calling Fd() on an *os.File the caller may close afterwards, so capture the descriptor before Start returns. Restore os.Stdin with t.Cleanup. Each new or changed test fails under -race with its fix reverted. --- proxy.go | 5 +++-- websocket.go | 10 +++++----- websocket_race_test.go | 41 +++++++++++++++++++++++++++++++++++++++-- 3 files changed, 47 insertions(+), 9 deletions(-) diff --git a/proxy.go b/proxy.go index 2ec9608..cb98319 100644 --- a/proxy.go +++ b/proxy.go @@ -96,9 +96,10 @@ func (conn *proxyConn) Write(p []byte) (n int, err error) { func (conn *proxyConn) Close() error { var closeErr error conn.closeOnce.Do(func() { - // send close message with deadline + // send close message with deadline. WriteControl takes its own + // deadline and is safe to call while Write is in progress; + // SetWriteDeadline is not. deadline := time.Now().Add(proxyCloseDeadline) - conn.conn.SetWriteDeadline(deadline) conn.conn.WriteControl( websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), diff --git a/websocket.go b/websocket.go index 91f3300..116f044 100644 --- a/websocket.go +++ b/websocket.go @@ -267,17 +267,17 @@ func (c *wsCmd) start() { // Send initial resize message for TTY mode if c.Tty { - // Read os.Stdin here, before Start returns, so a caller that swaps - // it afterwards does not race with this goroutine. - stdin := os.Stdin + // Read os.Stdin's descriptor here, before Start returns, so a caller + // that swaps or closes it afterwards does not race with this goroutine. + stdinFd := int(os.Stdin.Fd()) go func() { select { case <-time.After(10 * time.Millisecond): case <-c.doneChan: return } - if term.IsTerminal(int(stdin.Fd())) { - if width, height, err := term.GetSize(int(stdin.Fd())); err == nil { + if term.IsTerminal(stdinFd) { + if width, height, err := term.GetSize(stdinFd); err == nil { c.Resize(uint16(width), uint16(height)) } } diff --git a/websocket_race_test.go b/websocket_race_test.go index 39b2832..56d21f8 100644 --- a/websocket_race_test.go +++ b/websocket_race_test.go @@ -80,6 +80,9 @@ func TestCloseDoesNotRaceWriteLoop(t *testing.T) { // finished raced with it. Run with -race. func TestTTYResizeDoesNotReadStdinAfterCommandReturns(t *testing.T) { server := newExitingServer(t, func(conn *websocket.Conn) error { + // Exit after the resize goroutine's 10ms delay, so it gets past the + // select and reads stdin while the command is still running. + time.Sleep(50 * time.Millisecond) return conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"exit","exit_code":0}`)) }) defer server.Close() @@ -93,18 +96,17 @@ func TestTTYResizeDoesNotReadStdinAfterCommandReturns(t *testing.T) { original := os.Stdin os.Stdin = stdinReader + t.Cleanup(func() { os.Stdin = original }) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, wsURL(server), nil) if err != nil { - os.Stdin = original t.Fatalf("NewRequestWithContext() error = %v", err) } wsCmd := newWSCmdContext(ctx, req, "sh") wsCmd.Tty = true if err := wsCmd.Start(); err != nil { - os.Stdin = original t.Fatalf("Start() error = %v", err) } _ = wsCmd.Wait() @@ -113,3 +115,38 @@ func TestTTYResizeDoesNotReadStdinAfterCommandReturns(t *testing.T) { // Give a detached resize goroutine time to run if one is still pending. time.Sleep(30 * time.Millisecond) } + +// proxyConn.Close used to call SetWriteDeadline on the connection outside +// writeMu, racing with a concurrent Write inside WriteMessage. net.Conn +// allows Close to be called while Write is in progress. Run with -race. +func TestProxyConnCloseDoesNotRaceWrite(t *testing.T) { + server := newExitingServer(t, func(*websocket.Conn) error { + return nil + }) + defer server.Close() + + for i := 0; i < 20; i++ { + ws, resp, err := websocket.DefaultDialer.Dial(wsURL(server), nil) + if err != nil { + t.Fatalf("Dial() error = %v", err) + } + resp.Body.Close() + conn := &proxyConn{conn: ws} + + done := make(chan struct{}) + go func() { + defer close(done) + buf := make([]byte, 1024) + for { + if _, err := conn.Write(buf); err != nil { + return + } + } + }() + time.Sleep(2 * time.Millisecond) + if err := conn.Close(); err != nil { + t.Fatalf("Close() error = %v", err) + } + <-done + } +}