From 683309857c62b01de1f4ad4824ad903077bfdd01 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:00:37 -0600 Subject: [PATCH 01/17] fix(streaming): close connection send queues on disconnect handleWebSocket and handleSSE wrap each transport in NewConnection, which starts a dedicated send queue writer goroutine. Neither handler ever closed that connection, and manager.Unregister does not close it either, so every disconnect left the writer parked on its notify channel forever. 2000 connect/disconnect cycles left 2000 goroutines, about 19 KB each. Both handlers now close the enhanced connection on every exit path, including a hook rejection or a failed registration. The writer also watches the transport's context and exits when it ends, so a caller that builds a connection by hand and forgets Close no longer leaks it either. --- extensions/streaming/connection.go | 7 + extensions/streaming/connection_leak_test.go | 197 +++++++++++++++++++ extensions/streaming/extension.go | 13 ++ extensions/streaming/sendqueue.go | 21 +- 4 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 extensions/streaming/connection_leak_test.go diff --git a/extensions/streaming/connection.go b/extensions/streaming/connection.go index 5f28eeea6..2c9018965 100644 --- a/extensions/streaming/connection.go +++ b/extensions/streaming/connection.go @@ -134,6 +134,13 @@ func NewConnectionWithTransport(conn forge.Connection, transport string, opts .. func() { _ = c.closeUnderlying() }, c.onWriterExit, ) + + // Tie the writer to the transport's lifetime, so it cannot outlive the + // connection even when the owner never calls Close. + if ctx := conn.Context(); ctx != nil { + c.queue.stopOn(ctx.Done()) + } + c.queue.start() return c diff --git a/extensions/streaming/connection_leak_test.go b/extensions/streaming/connection_leak_test.go new file mode 100644 index 000000000..c3c626f36 --- /dev/null +++ b/extensions/streaming/connection_leak_test.go @@ -0,0 +1,197 @@ +package streaming + +import ( + "bufio" + "context" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "testing" + "time" + + "github.com/gobwas/ws" + "github.com/xraph/forge" +) + +// newLeakTestServer serves the extension's real WebSocket and SSE handlers +// through a real router, so the tests below exercise the production +// connect/disconnect path rather than a stand-in for it. +func newLeakTestServer(t *testing.T) (*Extension, *httptest.Server) { + t.Helper() + + app := forge.NewApp(forge.AppConfig{Name: "leak"}) + ext := NewExtension(WithLocalBackend()) + + if err := ext.Register(app); err != nil { + t.Fatal(err) + } + + if err := ext.RegisterRoutes(app.Router(), "/ws", "/sse"); err != nil { + t.Fatal(err) + } + + srv := httptest.NewServer(app.Router().(http.Handler)) + t.Cleanup(srv.Close) + + return ext, srv +} + +// settleGoroutines waits for every connection to be unregistered and for the +// goroutine count to fall back to base, then returns the count it settled at. +func settleGoroutines(t *testing.T, ext *Extension, base int) int { + t.Helper() + + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) && ext.Manager().ConnectionCount() > 0 { + time.Sleep(10 * time.Millisecond) + } + + runtime.GC() + + return waitForGoroutineCount(base) +} + +func sendQueueWriters() int { + buf := make([]byte, 4<<20) + + return strings.Count(string(buf[:runtime.Stack(buf, true)]), "(*sendQueue).run") +} + +// Every WebSocket connection starts a send queue writer goroutine. The handler +// unregistered the connection on disconnect but never closed it, so each +// disconnect left that goroutine, and its stack, behind for good. +func TestHandleWebSocket_DisconnectReleasesWriterGoroutine(t *testing.T) { + ext, srv := newLeakTestServer(t) + url := "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws" + + dial := func() { + c, _, _, err := ws.Dial(context.Background(), url) + if err != nil { + t.Fatal(err) + } + + time.Sleep(time.Millisecond) + + _ = c.Close() + } + + // Warm up so lazily started background goroutines are part of the base. + dial() + settleGoroutines(t, ext, 0) + + base := runtime.NumGoroutine() + baseWriters := sendQueueWriters() + + const cycles = 300 + for range cycles { + dial() + } + + after := settleGoroutines(t, ext, base) + + // Relative to the start: other tests in the package may leave their own + // connections open. + if writers := sendQueueWriters() - baseWriters; writers > 0 || after-base > cycles/10 { + t.Fatalf("after %d connect/disconnect cycles: %d goroutines over base, %d send queue writers still running", + cycles, after-base, writers) + } +} + +// The SSE handler had the same leak as the WebSocket one. +func TestHandleSSE_DisconnectReleasesWriterGoroutine(t *testing.T) { + ext, srv := newLeakTestServer(t) + + connect := func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/sse", nil) + if err != nil { + t.Fatal(err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + + // Wait for the "connected" event, which proves registration happened. + sc := bufio.NewScanner(resp.Body) + for sc.Scan() { + if strings.HasPrefix(sc.Text(), "event: connected") { + break + } + } + } + + connect() + settleGoroutines(t, ext, 0) + + base := runtime.NumGoroutine() + baseWriters := sendQueueWriters() + + const cycles = 150 + for range cycles { + connect() + } + + http.DefaultClient.CloseIdleConnections() + + after := settleGoroutines(t, ext, base) + + // Relative to the start: other tests in the package may leave their own + // connections open. + if writers := sendQueueWriters() - baseWriters; writers > 0 || after-base > cycles/10 { + t.Fatalf("after %d connect/disconnect cycles: %d goroutines over base, %d send queue writers still running", + cycles, after-base, writers) + } +} + +// ctxConn is a recording transport whose context the test controls. +type ctxConn struct { + recordingConn + + ctx context.Context //nolint:containedctx // stands in for a transport's connection context +} + +func (c *ctxConn) Context() context.Context { return c.ctx } + +// The writer must not depend on its owner remembering to call Close: once the +// transport's context ends, it stops by itself and the connection reports +// closed. +func TestEnhancedConn_WriterStopsWhenTransportContextEnds(t *testing.T) { + base := runtime.NumGoroutine() + + ctx, cancel := context.WithCancel(context.Background()) + tc := &ctxConn{recordingConn: recordingConn{id: "c1"}, ctx: ctx} + conn := NewConnection(tc) + + if err := conn.WriteJSON(&Message{ID: "m1", Type: MessageTypeMessage}); err != nil { + t.Fatal(err) + } + + cancel() + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) && !conn.IsClosed() { + time.Sleep(time.Millisecond) + } + + if !conn.IsClosed() { + t.Fatal("connection still open after its transport context ended") + } + + if n := waitForGoroutineCount(base); n > base { + t.Fatalf("writer goroutine still running: %d goroutines, base %d", n, base) + } + + tc.mu.Lock() + closed := tc.closed + tc.mu.Unlock() + + if !closed { + t.Fatal("underlying transport was not closed") + } +} diff --git a/extensions/streaming/extension.go b/extensions/streaming/extension.go index 4b476ee59..3a75dfd37 100644 --- a/extensions/streaming/extension.go +++ b/extensions/streaming/extension.go @@ -417,6 +417,14 @@ func (e *Extension) handleWebSocket(ctx forge.Context, conn forge.Connection) er // Create enhanced connection enhanced := NewConnection(conn) + + // Close stops the connection's send queue writer. Registered first so it + // runs last, after unregistration and the disconnect hooks, and on every + // early return too: a rejected or unregistrable connection already has a + // writer goroutine running. Unregister does not close the connection, so + // without this each disconnect left the writer and its stack behind. + defer func() { _ = enhanced.Close() }() + enhanced.SetUserID(userID) enhanced.SetSessionID(sessionID) @@ -785,6 +793,11 @@ func (e *Extension) handleSSE(ctx forge.Context, stream forge.Stream) error { // Wrap in enhanced connection with SSE transport type enhanced := NewConnectionWithTransport(sseConn, TransportSSE) + + // See handleWebSocket: the send queue writer has to be stopped on every + // exit path, and Unregister does not do it. + defer func() { _ = enhanced.Close() }() + enhanced.SetUserID(userID) enhanced.SetSessionID(sessionID) diff --git a/extensions/streaming/sendqueue.go b/extensions/streaming/sendqueue.go index 729e19c7f..ebd22d5af 100644 --- a/extensions/streaming/sendqueue.go +++ b/extensions/streaming/sendqueue.go @@ -185,6 +185,13 @@ type sendQueue struct { notify chan struct{} // capacity 1; a pending token means "look again" done chan struct{} // closed once the writer goroutine has returned + // stop, when set, is the transport's own done channel. An idle writer + // parks waiting for work, and nothing else would wake it once the peer + // has gone: a handler that forgot to call Close left one goroutine and + // its stack behind per disconnected client. Watching the transport's + // context makes the writer exit on its own when the connection ends. + stop <-chan struct{} + enqueued atomic.Uint64 written atomic.Uint64 dropped atomic.Uint64 @@ -224,6 +231,12 @@ func newSendQueue(capacity int, flushTimeout, exitTimeout time.Duration, return q } +// stopOn makes the writer exit once ch is closed, typically the transport +// context's Done channel. Must be called before start. +func (q *sendQueue) stopOn(ch <-chan struct{}) { + q.stop = ch +} + // start launches the dedicated writer goroutine. func (q *sendQueue) start() { go q.run() @@ -467,7 +480,13 @@ func (q *sendQueue) loop() error { } if len(frames) == 0 { - <-q.notify + // A nil stop channel blocks forever, so a transport without a + // context behaves exactly as before. + select { + case <-q.notify: + case <-q.stop: + return nil + } } } } From 6cc3cddcaeecaac047c33a9c7a669f0699c181ed Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:03:08 -0600 Subject: [PATCH 02/17] fix(router): answer WebSocket pings under the write lock wsutil.ReadClientData answers ping and close frames by writing straight to the socket from the reading goroutine. It took neither the connection's write mutex nor a write deadline, while write() put a frame header and its payload on the wire in two separate writes. A pong could land between the two and the client saw a corrupt stream. It happened in 3 of 3 runs of a ping flood against a busy writer. Read now drives wsutil.Reader itself and answers control frames through writeControl, which builds the reply in memory and writes it as one frame under the mutex and the write deadline. A peer that stops reading can no longer block the reader on a pong either. Data frames now go out as one writev of header and payload instead of two writes. --- internal/router/streaming_websocket.go | 118 ++++++++- .../streaming_websocket_control_test.go | 230 ++++++++++++++++++ 2 files changed, 340 insertions(+), 8 deletions(-) create mode 100644 internal/router/streaming_websocket_control_test.go diff --git a/internal/router/streaming_websocket.go b/internal/router/streaming_websocket.go index 440bda35a..25464ad8c 100644 --- a/internal/router/streaming_websocket.go +++ b/internal/router/streaming_websocket.go @@ -1,9 +1,11 @@ package router import ( + "bytes" "context" "encoding/json" "errors" + "io" "net" "net/http" "sync" @@ -161,7 +163,7 @@ func (c *wsConnection) Read() ([]byte, error) { } // Bound the read rather than trusting the advertised frame length. - data, _, err := wsutil.ReadClientData(newLimitedConn(c.conn, limit)) + data, err := c.readClientData(newLimitedConn(c.conn, limit)) if err != nil { return nil, err } @@ -179,6 +181,100 @@ func (c *wsConnection) Read() ([]byte, error) { return data, nil } +// readClientData reads the next text or binary message from src, answering +// control frames along the way. +// +// It mirrors wsutil.ReadClientData with one difference that matters: the +// library writes ping and close replies straight to the socket from the +// reading goroutine, without c.mu and without a write deadline. A pong could +// then land in the middle of a data frame another goroutine was writing, +// corrupting the stream for the client, and a peer that stopped reading +// could block the reader on its reply forever. Replies here go through +// writeControl instead. +func (c *wsConnection) readClientData(src io.Reader) ([]byte, error) { + rd := wsutil.Reader{ + Source: src, + State: ws.StateServerSide, + CheckUTF8: true, + OnIntermediate: c.handleControlFrame, + } + + for { + hdr, err := rd.NextFrame() + if err != nil { + return nil, err + } + + if hdr.OpCode.IsControl() { + if err := c.handleControlFrame(hdr, &rd); err != nil { + return nil, err + } + + continue + } + + if hdr.OpCode&(ws.OpText|ws.OpBinary) == 0 { + if err := rd.Discard(); err != nil { + return nil, err + } + + continue + } + + return io.ReadAll(&rd) + } +} + +// handleControlFrame answers a ping or close frame. The reply is built in +// memory first and written as a single frame under the write lock, so it can +// never interleave with an application write. +func (c *wsConnection) handleControlFrame(h ws.Header, r io.Reader) error { + var reply bytes.Buffer + + err := wsutil.ControlHandler{ + Src: r, + Dst: &reply, + State: ws.StateServerSide, + DisableSrcCiphering: true, + }.Handle(h) + + if reply.Len() > 0 { + if werr := c.writeControl(reply.Bytes()); werr != nil && err == nil { + err = werr + } + } + + return err +} + +// writeControl writes an already framed control reply under the write lock +// and the write deadline. Control frames are not messages, so the stream +// handle does not count them. +func (c *wsConnection) writeControl(frame []byte) error { + c.mu.Lock() + defer c.mu.Unlock() + + if c.closed { + return errors.New("connection closed") + } + + _ = c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeoutLocked())) + + defer func() { _ = c.conn.SetWriteDeadline(time.Time{}) }() + + _, err := c.conn.Write(frame) + + return err +} + +func (c *wsConnection) writeTimeoutLocked() time.Duration { + if c.writeTimeout <= 0 { + return DefaultWebSocketWriteTimeout + } + + return c.writeTimeout +} + // ReadJSON reads JSON from the WebSocket. func (c *wsConnection) ReadJSON(v any) error { data, err := c.Read() @@ -202,19 +298,25 @@ func (c *wsConnection) write(op ws.OpCode, data []byte) error { return errors.New("connection closed") } - timeout := c.writeTimeout - if timeout <= 0 { - timeout = DefaultWebSocketWriteTimeout - } - // Deadline errors are ignored rather than failing the write: not every // net.Conn honours deadlines, and refusing to write to one that does not is // worse than writing without the bound. - _ = c.conn.SetWriteDeadline(time.Now().Add(timeout)) + _ = c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeoutLocked())) defer func() { _ = c.conn.SetWriteDeadline(time.Time{}) }() - if err := wsutil.WriteServerMessage(c.conn, op, data); err != nil { + // Header and payload go out together. net.Buffers uses writev where the + // connection supports it, so this is one syscall and no payload copy, + // where WriteServerMessage made two writes. + var hdr [ws.MaxHeaderSize]byte + + hb := bytes.NewBuffer(hdr[:0]) + if err := ws.WriteHeader(hb, ws.Header{Fin: true, OpCode: op, Length: int64(len(data))}); err != nil { + return err + } + + frame := net.Buffers{hb.Bytes(), data} + if _, err := frame.WriteTo(c.conn); err != nil { return err } diff --git a/internal/router/streaming_websocket_control_test.go b/internal/router/streaming_websocket_control_test.go new file mode 100644 index 000000000..c56bb3117 --- /dev/null +++ b/internal/router/streaming_websocket_control_test.go @@ -0,0 +1,230 @@ +package router + +import ( + "bytes" + "context" + "errors" + "io" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsutil" +) + +// wsPair returns a server-side wsConnection and the raw client socket talking +// to it over loopback TCP. +func wsPair(t *testing.T) (*wsConnection, net.Conn) { + t.Helper() + + ln, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = ln.Close() }) + + ready := make(chan *wsConnection, 1) + + go func() { + c, err := ln.Accept() + if err != nil { + close(ready) + + return + } + + if _, err := ws.Upgrade(c); err != nil { + close(ready) + + return + } + + ready <- newWSConnection("x", c, context.Background()) + }() + + cli, _, _, err := ws.Dial(context.Background(), "ws://"+ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = cli.Close() }) + + srv, ok := <-ready + if !ok { + t.Fatal("server side of the WebSocket never came up") + } + + t.Cleanup(func() { _ = srv.Close() }) + + return srv, cli +} + +// Pong replies used to be written by wsutil.ReadClientData on the reading +// goroutine, straight to the socket and without the write lock, while Write +// put a frame header and its payload on the wire in two separate writes. A +// pong could land between them and the client saw a corrupt stream. +func TestWSConnection_PongDoesNotInterleaveWithDataFrames(t *testing.T) { + srv, cli := wsPair(t) + + payload := bytes.Repeat([]byte("x"), 32*1024) + ping := bytes.Repeat([]byte("p"), 100) + + stop := make(chan struct{}) + + time.AfterFunc(1500*time.Millisecond, func() { close(stop) }) + + // Server reader: answers pings. + go func() { + for { + if _, err := srv.Read(); err != nil { + return + } + } + }() + + // Server writer: application traffic. + go func() { + for { + select { + case <-stop: + return + default: + } + + if err := srv.Write(payload); err != nil { + return + } + } + }() + + // Client pinger. + go func() { + for { + select { + case <-stop: + return + default: + } + + if err := wsutil.WriteClientMessage(cli, ws.OpPing, ping); err != nil { + return + } + } + }() + + var dataFrames, pongs atomic.Int64 + + _ = cli.SetReadDeadline(time.Now().Add(2500 * time.Millisecond)) + + for { + h, err := ws.ReadHeader(cli) + if err != nil { + break + } + + if h.Length > 1<<20 { + t.Fatalf("corrupt frame header: length %d", h.Length) + } + + buf := make([]byte, h.Length) + if _, err := io.ReadFull(cli, buf); err != nil { + break + } + + switch h.OpCode { + case ws.OpText: + if !bytes.Equal(buf, payload) { + t.Fatal("data frame corrupted: a control frame landed inside it") + } + + dataFrames.Add(1) + case ws.OpPong: + if !bytes.Equal(buf, ping) { + t.Fatal("pong frame corrupted") + } + + pongs.Add(1) + default: + t.Fatalf("unexpected opcode %v: stream is out of frame sync", h.OpCode) + } + } + + if dataFrames.Load() == 0 || pongs.Load() == 0 { + t.Fatalf("test did not exercise the race: data frames=%d pongs=%d", dataFrames.Load(), pongs.Load()) + } +} + +// The control frame handling was rewritten to route replies through the write +// lock. A close from the client must still be echoed and end the read loop. +func TestWSConnection_CloseFrameIsEchoed(t *testing.T) { + srv, cli := wsPair(t) + + body := ws.NewCloseFrameBody(ws.StatusNormalClosure, "bye") + if err := wsutil.WriteClientMessage(cli, ws.OpClose, body); err != nil { + t.Fatal(err) + } + + _, err := srv.Read() + + var closed wsutil.ClosedError + if !errors.As(err, &closed) || closed.Code != ws.StatusNormalClosure { + t.Fatalf("Read error = %v, want ClosedError with code 1000", err) + } + + _ = cli.SetReadDeadline(time.Now().Add(2 * time.Second)) + + h, err := ws.ReadHeader(cli) + if err != nil { + t.Fatalf("no close reply: %v", err) + } + + if h.OpCode != ws.OpClose { + t.Fatalf("reply opcode = %v, want close", h.OpCode) + } +} + +// Pings interleaved with a fragmented message are answered mid-message and do +// not disturb the message itself. +func TestWSConnection_PingBetweenFragmentsIsAnswered(t *testing.T) { + srv, cli := wsPair(t) + + frames := []ws.Frame{ + ws.MaskFrame(ws.NewFrame(ws.OpText, false, []byte("hel"))), + ws.MaskFrame(ws.NewPingFrame([]byte("p1"))), + ws.MaskFrame(ws.NewFrame(ws.OpContinuation, true, []byte("lo"))), + } + + for _, f := range frames { + if err := ws.WriteFrame(cli, f); err != nil { + t.Fatal(err) + } + } + + data, err := srv.Read() + if err != nil { + t.Fatal(err) + } + + if string(data) != "hello" { + t.Fatalf("message = %q, want %q", data, "hello") + } + + _ = cli.SetReadDeadline(time.Now().Add(2 * time.Second)) + + h, err := ws.ReadHeader(cli) + if err != nil { + t.Fatalf("no pong: %v", err) + } + + pong := make([]byte, h.Length) + if _, err := io.ReadFull(cli, pong); err != nil { + t.Fatal(err) + } + + if h.OpCode != ws.OpPong || string(pong) != "p1" { + t.Fatalf("reply = %v %q, want pong %q", h.OpCode, pong, "p1") + } +} From bf9406b6d98ff2960005dbb0fdc9a2c4b5b284be Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:04:26 -0600 Subject: [PATCH 03/17] fix(router): cap the size of one WebTransport JSON value streamReader.ReadJSON decoded straight from the QUIC stream with no limit. json.Decoder buffers a whole value before it returns, and the client picks how long that value is, so one stream could make the server allocate as much as it cared to send. A 200 MiB string cost 1.2 GiB. The decoder now reads through a byte budget that ReadJSON refills for every value. The cap defaults to DefaultMaxWebSocketMessageSize (1 MiB), is set per route with WebTransportConfig.MaxJSONValueSize, and per stream with SetReadLimit. A negative value turns it off. An oversized value fails with ErrWebTransportMessageTooLarge. Raw Read calls are not limited. --- internal/router/router_webtransport.go | 2 + internal/router/webtransport.go | 104 ++++++++++++++-- .../router/webtransport_json_limit_test.go | 113 ++++++++++++++++++ streaming.go | 5 + 4 files changed, 215 insertions(+), 9 deletions(-) create mode 100644 internal/router/webtransport_json_limit_test.go diff --git a/internal/router/router_webtransport.go b/internal/router/router_webtransport.go index 6479ae89a..e756c4295 100644 --- a/internal/router/router_webtransport.go +++ b/internal/router/router_webtransport.go @@ -64,11 +64,13 @@ func (r *router) WebTransport(path string, handler WebTransportHandler, opts ... r.mu.RLock() maxDatagramSize := r.webTransportConfig.MaxDatagramFrameSize + maxJSONValueSize := r.webTransportConfig.MaxJSONValueSize r.mu.RUnlock() wtSession := newWebTransportSession(sessionID, session, req.Context()) wtSession.handle = handle wtSession.maxDatagramSize = maxDatagramSize + wtSession.maxJSONValueSize = maxJSONValueSize defer wtSession.Close() diff --git a/internal/router/webtransport.go b/internal/router/webtransport.go index aa4b1bf71..c6d7d9ea1 100644 --- a/internal/router/webtransport.go +++ b/internal/router/webtransport.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io" + "math" "sync" "github.com/quic-go/quic-go" @@ -96,6 +97,10 @@ type webTransportSession struct { // maxDatagramSize is WebTransportConfig.MaxDatagramFrameSize. Zero or // less means no limit beyond QUIC's own. Set by the router. maxDatagramSize int64 + + // maxJSONValueSize is WebTransportConfig.MaxJSONValueSize, handed to every + // stream the session opens or accepts. Set by the router. + maxJSONValueSize int64 } // newWebTransportSession creates a new WebTransport session wrapper. @@ -121,7 +126,7 @@ func (s *webTransportSession) OpenStream() (WebTransportStream, error) { return nil, fmt.Errorf("failed to open stream: %w", err) } - return newWebTransportStream(stream), nil + return newWebTransportStream(stream, s.maxJSONValueSize), nil } func (s *webTransportSession) OpenUniStream() (WebTransportStream, error) { @@ -139,7 +144,7 @@ func (s *webTransportSession) AcceptStream(ctx context.Context) (WebTransportStr return nil, fmt.Errorf("failed to accept stream: %w", err) } - return newWebTransportStream(stream), nil + return newWebTransportStream(stream, s.maxJSONValueSize), nil } func (s *webTransportSession) AcceptUniStream(ctx context.Context) (WebTransportStream, error) { @@ -148,7 +153,7 @@ func (s *webTransportSession) AcceptUniStream(ctx context.Context) (WebTransport return nil, fmt.Errorf("failed to accept uni stream: %w", err) } - return newWebTransportReceiveStream(stream), nil + return newWebTransportReceiveStream(stream, s.maxJSONValueSize), nil } // ReceiveDatagram returns the next datagram within the size limit. A larger @@ -245,9 +250,23 @@ func (s *webTransportSession) LocalAddr() string { // read-ahead back to Read when the caller switches. // // Like the stream underneath, it supports one reader at a time. +// +// ReadJSON caps each value at maxJSON bytes. The decoder buffers a whole +// value before it returns, and the peer chooses how long that value is, so +// without a cap one client could make the server allocate as much memory as +// it cared to send: a 200 MiB string cost 1.2 GiB. type streamReader struct { r io.Reader + // maxJSON caps the bytes ReadJSON may pull from the stream for one value. + // Zero means DefaultMaxWebSocketMessageSize and a negative value turns + // the cap off. + maxJSON int64 + + // budget sits between the decoder and the stream and enforces maxJSON. + // ReadJSON refills it for every value. + budget budgetReader + // dec is the decoder ReadJSON uses, nil after a raw Read. dec *json.Decoder @@ -285,12 +304,54 @@ func (s *streamReader) ReadJSON(v any) error { src = io.MultiReader(s.pending, s.r) } - s.dec = json.NewDecoder(src) + s.budget = budgetReader{r: src} + s.dec = json.NewDecoder(&s.budget) } + // The budget is per value. Bytes the decoder read ahead for this value + // were paid for by the previous one, so a value can exceed the limit by + // at most one read-ahead, which is itself bounded by the limit. + s.budget.remaining = s.limit() + return s.dec.Decode(v) } +func (s *streamReader) limit() int64 { + switch { + case s.maxJSON < 0: + return math.MaxInt64 + case s.maxJSON == 0: + return DefaultMaxWebSocketMessageSize + default: + return s.maxJSON + } +} + +// ErrWebTransportMessageTooLarge is returned by ReadJSON when one JSON value +// on a WebTransport stream is larger than the read limit. +var ErrWebTransportMessageTooLarge = errors.New("webtransport JSON value exceeds read limit") + +// budgetReader reads from r until remaining runs out, then fails. +type budgetReader struct { + r io.Reader + remaining int64 +} + +func (b *budgetReader) Read(p []byte) (int, error) { + if b.remaining <= 0 { + return 0, ErrWebTransportMessageTooLarge + } + + if int64(len(p)) > b.remaining { + p = p[:b.remaining] + } + + n, err := b.r.Read(p) + b.remaining -= int64(n) + + return n, err +} + // writeJSONLine writes v and a newline in one Write. The newline keeps values // apart: two numbers back to back would otherwise read as one, and a client // that splits the stream on newlines, as the generated TypeScript client's @@ -316,14 +377,23 @@ type webTransportStream struct { mu sync.RWMutex } -// newWebTransportStream creates a new WebTransport stream wrapper. -func newWebTransportStream(stream *webtransport.Stream) *webTransportStream { +// newWebTransportStream creates a new WebTransport stream wrapper. maxJSON +// caps one ReadJSON value; see streamReader. +func newWebTransportStream(stream *webtransport.Stream, maxJSON int64) *webTransportStream { return &webTransportStream{ stream: stream, - reader: streamReader{r: stream}, + reader: streamReader{r: stream, maxJSON: maxJSON}, } } +// SetReadLimit overrides the largest JSON value ReadJSON accepts on this +// stream. Zero restores DefaultMaxWebSocketMessageSize and a negative value +// removes the cap. Raw Read calls are not limited. Call it from the goroutine +// that reads the stream. +func (s *webTransportStream) SetReadLimit(limit int64) { + s.reader.maxJSON = limit +} + func (s *webTransportStream) Read(p []byte) (n int, err error) { return s.reader.Read(p) } @@ -399,8 +469,14 @@ type webTransportReceiveStream struct { reader streamReader } -func newWebTransportReceiveStream(stream *webtransport.ReceiveStream) *webTransportReceiveStream { - return &webTransportReceiveStream{stream: stream, reader: streamReader{r: stream}} +func newWebTransportReceiveStream(stream *webtransport.ReceiveStream, maxJSON int64) *webTransportReceiveStream { + return &webTransportReceiveStream{stream: stream, reader: streamReader{r: stream, maxJSON: maxJSON}} +} + +// SetReadLimit overrides the largest JSON value ReadJSON accepts on this +// stream. See webTransportStream.SetReadLimit. +func (s *webTransportReceiveStream) SetReadLimit(limit int64) { + s.reader.maxJSON = limit } func (s *webTransportReceiveStream) Read(p []byte) (n int, err error) { @@ -465,6 +541,15 @@ type WebTransportConfig struct { // AllowedOrigins is the list of allowed origins for WebTransport connections. // If empty, only same-origin requests are allowed. "*" allows any origin. AllowedOrigins []string + + // MaxJSONValueSize caps, in bytes, one JSON value read with ReadJSON on a + // stream. The decoder buffers a whole value before returning it and the + // client picks its length, so the cap is what keeps one stream from + // asking for unbounded memory. Zero means DefaultMaxWebSocketMessageSize + // (1 MiB) and a negative value removes the cap. A larger value fails + // ReadJSON with ErrWebTransportMessageTooLarge. Individual streams can + // override it with SetReadLimit. + MaxJSONValueSize int64 } // DefaultWebTransportConfig returns default WebTransport configuration. @@ -478,5 +563,6 @@ func DefaultWebTransportConfig() WebTransportConfig { ConnectionReceiveWindow: 15 * 1024 * 1024, // 15MB KeepAliveInterval: 30000, // 30 seconds MaxIdleTimeout: 60000, // 60 seconds + MaxJSONValueSize: DefaultMaxWebSocketMessageSize, } } diff --git a/internal/router/webtransport_json_limit_test.go b/internal/router/webtransport_json_limit_test.go new file mode 100644 index 000000000..f342b9040 --- /dev/null +++ b/internal/router/webtransport_json_limit_test.go @@ -0,0 +1,113 @@ +package router + +import ( + "errors" + "io" + "runtime" + "strings" + "testing" +) + +// repeatReader yields n copies of b and then EOF, without holding them all. +type repeatReader struct { + b byte + left int +} + +func (r *repeatReader) Read(p []byte) (int, error) { + if r.left <= 0 { + return 0, io.EOF + } + + n := min(len(p), r.left) + for i := range n { + p[i] = r.b + } + + r.left -= n + + return n, nil +} + +// jsonString streams one JSON string of n 'a' characters. +func jsonString(n int) io.Reader { + return io.MultiReader(strings.NewReader(`"`), &repeatReader{b: 'a', left: n}, strings.NewReader(`"`)) +} + +// ReadJSON had no size cap: the decoder buffered whatever one value the peer +// sent, and a 200 MiB string cost 1.2 GiB of allocations. With the default cap +// it now fails after about 1 MiB. +func TestStreamReader_ReadJSONDefaultCapBoundsMemory(t *testing.T) { + sr := streamReader{r: jsonString(200 << 20)} + + var before, after runtime.MemStats + + runtime.ReadMemStats(&before) + + var v any + + err := sr.ReadJSON(&v) + + runtime.ReadMemStats(&after) + + if !errors.Is(err, ErrWebTransportMessageTooLarge) { + t.Fatalf("ReadJSON error = %v, want ErrWebTransportMessageTooLarge", err) + } + + if allocated := after.TotalAlloc - before.TotalAlloc; allocated > 16<<20 { + t.Fatalf("ReadJSON allocated %d MiB before refusing the value", allocated>>20) + } +} + +func TestStreamReader_ReadJSONCustomCap(t *testing.T) { + sr := streamReader{r: jsonString(4096), maxJSON: 1024} + + var v string + if err := sr.ReadJSON(&v); !errors.Is(err, ErrWebTransportMessageTooLarge) { + t.Fatalf("ReadJSON error = %v, want ErrWebTransportMessageTooLarge", err) + } +} + +// The cap is per value, not per stream: a long run of small values must keep +// decoding long after their total has passed the limit. +func TestStreamReader_ReadJSONCapIsPerValue(t *testing.T) { + const values = 200 + + sr := streamReader{r: strings.NewReader(strings.Repeat(`{"pad":"0123456789012345678901234567890123456789"}`+"\n", values)), maxJSON: 128} + + for i := range values { + var v struct{ Pad string } + if err := sr.ReadJSON(&v); err != nil { + t.Fatalf("value %d: %v", i, err) + } + } +} + +func TestStreamReader_NegativeCapDisablesLimit(t *testing.T) { + sr := streamReader{r: jsonString(2 << 20), maxJSON: -1} + + var v string + if err := sr.ReadJSON(&v); err != nil { + t.Fatalf("ReadJSON with the cap off: %v", err) + } + + if len(v) != 2<<20 { + t.Fatalf("decoded %d bytes, want %d", len(v), 2<<20) + } +} + +func TestWebTransportStream_SetReadLimit(t *testing.T) { + s := &webTransportStream{reader: streamReader{r: jsonString(4096)}} + s.SetReadLimit(1024) + + var v string + if err := s.ReadJSON(&v); !errors.Is(err, ErrWebTransportMessageTooLarge) { + t.Fatalf("ReadJSON error = %v, want ErrWebTransportMessageTooLarge", err) + } +} + +func TestDefaultWebTransportConfig_CapsJSONValues(t *testing.T) { + if got := DefaultWebTransportConfig().MaxJSONValueSize; got != DefaultMaxWebSocketMessageSize { + t.Fatalf("MaxJSONValueSize = %d, want %d", got, DefaultMaxWebSocketMessageSize) + } +} diff --git a/streaming.go b/streaming.go index 08fdd7141..750e74372 100644 --- a/streaming.go +++ b/streaming.go @@ -79,6 +79,11 @@ type WebTransportHandler = router.WebTransportHandler // WebTransportConfig configures WebTransport behavior. type WebTransportConfig = router.WebTransportConfig +// ErrWebTransportMessageTooLarge is returned by a WebTransport stream's +// ReadJSON when one JSON value is larger than +// WebTransportConfig.MaxJSONValueSize. +var ErrWebTransportMessageTooLarge = router.ErrWebTransportMessageTooLarge + // StreamConfig configures streaming behavior. type StreamConfig = router.StreamConfig From 2bd8f2ff61c9a45844f8926db592bb57ad0d4f8d Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:09:51 -0600 Subject: [PATCH 04/17] fix(streaming): authorize channel subscriptions Subscribe checked nothing. handleSSE calls it for every id in ?channels=, and handleSSESubscribe and session resumption call it too, so any client, anonymous ones included, could subscribe to any channel it could name. ChannelOptions.Private was stored nowhere and enforced nowhere. An anonymous GET /sse?channels=user-42-notifications received user 42's password reset link. Subscribe now refuses anonymous connections unless Config.AllowAnonymousSubscriptions is set, then asks a ChannelAuthorizer, the same way JoinRoom asks the room authorizer. The default authorizer admits public channels and refuses private ones, because a channel has no member list the store could check. Applications supply their own policy with Extension.SetChannelAuthorizer or WithChannelAuthorizer, and streamauth.ChannelAuthorizerFunc makes that a closure. NewManager installs the default when no authorizer is given, so a hand-built manager is not left open either. The local and Redis channel stores now keep the private flag. Redis channels stored before this read back public, as they behaved before. --- extensions/streaming/auth/channel_auth.go | 59 +++++ .../streaming/auth/channel_auth_test.go | 46 ++++ extensions/streaming/auth/interfaces.go | 12 + .../backends/local/channel_private_test.go | 42 ++++ .../streaming/backends/local/channel_store.go | 19 ++ .../streaming/backends/redis/channel_store.go | 13 ++ .../backends/redis/channel_store_test.go | 41 ++++ extensions/streaming/channel_auth_test.go | 211 ++++++++++++++++++ extensions/streaming/configs.go | 6 + extensions/streaming/extension.go | 34 +++ extensions/streaming/internal/config.go | 15 ++ extensions/streaming/manager.go | 69 ++++++ 12 files changed, 567 insertions(+) create mode 100644 extensions/streaming/auth/channel_auth.go create mode 100644 extensions/streaming/auth/channel_auth_test.go create mode 100644 extensions/streaming/backends/local/channel_private_test.go create mode 100644 extensions/streaming/backends/redis/channel_store_test.go create mode 100644 extensions/streaming/channel_auth_test.go diff --git a/extensions/streaming/auth/channel_auth.go b/extensions/streaming/auth/channel_auth.go new file mode 100644 index 000000000..61b2cf033 --- /dev/null +++ b/extensions/streaming/auth/channel_auth.go @@ -0,0 +1,59 @@ +package auth + +import ( + "context" + + "github.com/xraph/forge/errors" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// ChannelAuthorizerFunc adapts a function to ChannelAuthorizer. +type ChannelAuthorizerFunc func(ctx context.Context, userID, channelID string) (bool, error) + +// CanSubscribe calls f. +func (f ChannelAuthorizerFunc) CanSubscribe(ctx context.Context, userID, channelID string) (bool, error) { + return f(ctx, userID, channelID) +} + +// channelAuthorizer is the default ChannelAuthorizer. +type channelAuthorizer struct { + channelStore streaming.ChannelStore +} + +// NewChannelAuthorizer returns the default channel policy: anyone the manager +// lets through may subscribe to a public channel, and nobody may subscribe to +// a private one. +// +// A channel has no member list the store could check, so the default policy +// cannot tell who belongs to a private channel and refuses everyone. An +// application that uses private channels supplies its own ChannelAuthorizer, +// which knows its users, for example with ChannelAuthorizerFunc. +// +// A channel the store does not know is left to the store to refuse, as before: +// it has no private flag to leak through. +func NewChannelAuthorizer(channelStore streaming.ChannelStore) ChannelAuthorizer { + return &channelAuthorizer{channelStore: channelStore} +} + +// CanSubscribe implements ChannelAuthorizer. +func (ca *channelAuthorizer) CanSubscribe(ctx context.Context, userID, channelID string) (bool, error) { + channel, err := ca.channelStore.Get(ctx, channelID) + if errors.Is(err, streaming.ErrChannelNotFound) { + return true, nil + } + + if err != nil { + return false, err + } + + return !IsPrivateChannel(channel), nil +} + +// IsPrivateChannel reports whether a channel was created with +// ChannelOptions.Private. The Channel interface predates the flag, so it is +// read through an optional IsPrivate method; a channel without one is public. +func IsPrivateChannel(channel streaming.Channel) bool { + p, ok := channel.(interface{ IsPrivate() bool }) + + return ok && p.IsPrivate() +} diff --git a/extensions/streaming/auth/channel_auth_test.go b/extensions/streaming/auth/channel_auth_test.go new file mode 100644 index 000000000..246b4da03 --- /dev/null +++ b/extensions/streaming/auth/channel_auth_test.go @@ -0,0 +1,46 @@ +package auth + +import ( + "context" + "testing" + + "github.com/xraph/forge/extensions/streaming/backends/local" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +func TestChannelAuthorizer_DefaultPolicy(t *testing.T) { + ctx := context.Background() + store := local.NewChannelStore() + + for _, opts := range []streaming.ChannelOptions{ + {ID: "news", Name: "news"}, + {ID: "secret", Name: "secret", Private: true}, + } { + if err := store.Create(ctx, local.NewLocalChannel(opts)); err != nil { + t.Fatal(err) + } + } + + ca := NewChannelAuthorizer(store) + + cases := []struct { + channel string + want bool + }{ + {"news", true}, + {"secret", false}, + // Unknown channels are left to the store, which refuses them itself. + {"missing", true}, + } + + for _, tc := range cases { + got, err := ca.CanSubscribe(ctx, "alice", tc.channel) + if err != nil { + t.Fatalf("%s: %v", tc.channel, err) + } + + if got != tc.want { + t.Errorf("%s: CanSubscribe = %v, want %v", tc.channel, got, tc.want) + } + } +} diff --git a/extensions/streaming/auth/interfaces.go b/extensions/streaming/auth/interfaces.go index 61fd2d247..178d6279b 100644 --- a/extensions/streaming/auth/interfaces.go +++ b/extensions/streaming/auth/interfaces.go @@ -37,6 +37,18 @@ type RoomAuthorizer interface { GetUserRole(ctx context.Context, userID, roomID string) (string, error) } +// ChannelAuthorizer decides who may subscribe to a channel. +// +// The manager consults it on every Subscribe, whether the request came from a +// client (an SSE ?channels= parameter, the subscribe endpoint, a resumed +// session) or from server code. userID is empty for an anonymous connection, +// which reaches the authorizer only when the manager is configured to admit +// anonymous subscribers at all. +type ChannelAuthorizer interface { + // CanSubscribe reports whether userID may subscribe to channelID. + CanSubscribe(ctx context.Context, userID, channelID string) (bool, error) +} + // MessageAuthorizer checks message-level permissions. type MessageAuthorizer interface { // CanSend checks if user can send message to room/channel diff --git a/extensions/streaming/backends/local/channel_private_test.go b/extensions/streaming/backends/local/channel_private_test.go new file mode 100644 index 000000000..662539a58 --- /dev/null +++ b/extensions/streaming/backends/local/channel_private_test.go @@ -0,0 +1,42 @@ +package local + +import ( + "context" + "testing" + + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// opaqueChannel is a Channel that is not a *LocalChannel, so Create has to +// copy it. +type opaqueChannel struct { + *LocalChannel +} + +// The private flag decides channel authorization, so it has to survive both a +// direct Create and the copy Create makes of a foreign Channel. +func TestChannelStore_KeepsPrivateFlag(t *testing.T) { + ctx := context.Background() + s := NewChannelStore() + + direct := NewLocalChannel(streaming.ChannelOptions{ID: "a", Name: "a", Private: true}) + copied := opaqueChannel{NewLocalChannel(streaming.ChannelOptions{ID: "b", Name: "b", Private: true})} + public := NewLocalChannel(streaming.ChannelOptions{ID: "c", Name: "c"}) + + for _, ch := range []streaming.Channel{direct, copied, public} { + if err := s.Create(ctx, ch); err != nil { + t.Fatal(err) + } + } + + for id, want := range map[string]bool{"a": true, "b": true, "c": false} { + ch, err := s.Get(ctx, id) + if err != nil { + t.Fatal(err) + } + + if got := ch.(*LocalChannel).IsPrivate(); got != want { + t.Errorf("channel %s: IsPrivate = %v, want %v", id, got, want) + } + } +} diff --git a/extensions/streaming/backends/local/channel_store.go b/extensions/streaming/backends/local/channel_store.go index e3a2c6801..169f75c1c 100644 --- a/extensions/streaming/backends/local/channel_store.go +++ b/extensions/streaming/backends/local/channel_store.go @@ -43,6 +43,12 @@ func (s *ChannelStore) Create(ctx context.Context, channel streaming.Channel) er created: channel.GetCreated(), messageCount: channel.GetMessageCount(), } + + // Keep the private flag across the copy. Dropping it would quietly + // turn a private channel into a public one. + if p, ok := channel.(interface{ IsPrivate() bool }); ok { + localChannel.private = p.IsPrivate() + } } s.channels[localChannel.id] = localChannel @@ -260,6 +266,7 @@ type LocalChannel struct { name string created time.Time messageCount int64 + private bool } func NewLocalChannel(opts streaming.ChannelOptions) *LocalChannel { @@ -268,9 +275,21 @@ func NewLocalChannel(opts streaming.ChannelOptions) *LocalChannel { name: opts.Name, created: time.Now(), messageCount: 0, + private: opts.Private, } } +// IsPrivate reports whether the channel was created with +// ChannelOptions.Private. The manager's default channel authorizer refuses +// every subscriber to a private channel unless the application supplies an +// authorizer that knows who belongs. +func (c *LocalChannel) IsPrivate() bool { + c.mu.RLock() + defer c.mu.RUnlock() + + return c.private +} + func (c *LocalChannel) GetID() string { c.mu.RLock() defer c.mu.RUnlock() diff --git a/extensions/streaming/backends/redis/channel_store.go b/extensions/streaming/backends/redis/channel_store.go index b6cfa3788..f41c5efbd 100644 --- a/extensions/streaming/backends/redis/channel_store.go +++ b/extensions/streaming/backends/redis/channel_store.go @@ -41,6 +41,10 @@ func (s *ChannelStore) Create(ctx context.Context, channel streaming.Channel) er "message_count": channel.GetMessageCount(), } + if p, ok := channel.(interface{ IsPrivate() bool }); ok && p.IsPrivate() { + data["private"] = true + } + dataJSON, err := json.Marshal(data) if err != nil { return err @@ -82,12 +86,16 @@ func (s *ChannelStore) Get(ctx context.Context, channelID string) (streaming.Cha return nil, err } + // Absent on channels stored before the flag existed, which were public. + private, _ := channelData["private"].(bool) + return &redisChannel{ store: s, id: channelData["id"].(string), name: channelData["name"].(string), created: time.Unix(int64(channelData["created"].(float64)), 0), messageCount: int64(channelData["message_count"].(float64)), + private: private, }, nil } @@ -316,8 +324,13 @@ type redisChannel struct { name string created time.Time messageCount int64 + private bool } +// IsPrivate reports whether the channel was created with +// ChannelOptions.Private. +func (c *redisChannel) IsPrivate() bool { return c.private } + func (c *redisChannel) GetID() string { return c.id } func (c *redisChannel) GetName() string { return c.name } func (c *redisChannel) GetCreated() time.Time { return c.created } diff --git a/extensions/streaming/backends/redis/channel_store_test.go b/extensions/streaming/backends/redis/channel_store_test.go new file mode 100644 index 000000000..c2cf1c987 --- /dev/null +++ b/extensions/streaming/backends/redis/channel_store_test.go @@ -0,0 +1,41 @@ +package redis + +import ( + "context" + "testing" + + "github.com/xraph/forge/extensions/streaming/backends/local" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// The private flag decides channel authorization, so it has to round-trip +// through Redis. Channels stored before the flag existed read back public. +func TestChannelStore_KeepsPrivateFlag(t *testing.T) { + ctx := context.Background() + s := NewChannelStore(newTestClient(t), "test:channels") + + for _, opts := range []streaming.ChannelOptions{ + {ID: "secret", Name: "secret", Private: true}, + {ID: "news", Name: "news"}, + } { + if err := s.Create(ctx, local.NewLocalChannel(opts)); err != nil { + t.Fatal(err) + } + } + + for id, want := range map[string]bool{"secret": true, "news": false} { + ch, err := s.Get(ctx, id) + if err != nil { + t.Fatal(err) + } + + p, ok := ch.(interface{ IsPrivate() bool }) + if !ok { + t.Fatalf("redis channel has no IsPrivate method") + } + + if p.IsPrivate() != want { + t.Errorf("channel %s: IsPrivate = %v, want %v", id, p.IsPrivate(), want) + } + } +} diff --git a/extensions/streaming/channel_auth_test.go b/extensions/streaming/channel_auth_test.go new file mode 100644 index 000000000..dcfd35d03 --- /dev/null +++ b/extensions/streaming/channel_auth_test.go @@ -0,0 +1,211 @@ +package streaming + +import ( + "bufio" + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/xraph/forge" + streamauth "github.com/xraph/forge/extensions/streaming/auth" + "github.com/xraph/forge/extensions/streaming/backends/local" + "github.com/xraph/forge/extensions/streaming/filters" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// realManager wires a manager over the real local backends, the way +// Extension.Register does with the default config. +func realManager(t testing.TB, opts ...ManagerOption) (Manager, streaming.RoomStore, streaming.ChannelStore) { + t.Helper() + + cfg := DefaultConfig() + rooms := local.NewRoomStore() + chans := local.NewChannelStore() + msgs := local.NewMessageStore() + ra := streamauth.NewRoomAuthorizer(rooms) + + base := []ManagerOption{ + WithRoomAuthorizer(ra), + WithMessageAuthorizer(streamauth.NewMessageAuthorizer(ra, newAuthMessageStore(msgs))), + WithChannelAuthorizer(streamauth.NewChannelAuthorizer(chans)), + WithFilterChain(filters.NewFilterChain()), + WithHookRegistry(NewHookRegistry()), + WithCodecRegistry(NewCodecRegistry()), + } + + m := NewManager(cfg, rooms, chans, msgs, newFakePresenceTracker(), newFakeTypingTracker(), nil, nil, nil, + append(base, opts...)...) + + return m, rooms, chans +} + +func createChannel(t *testing.T, chans streaming.ChannelStore, id string, private bool) { + t.Helper() + + ch := local.NewLocalChannel(streaming.ChannelOptions{ID: id, Name: id, Private: private}) + if err := chans.Create(context.Background(), ch); err != nil { + t.Fatal(err) + } +} + +// Subscribe had no authorization, and handleSSE calls it for every id in +// ?channels=, so an unauthenticated EventSource could read any channel it +// could name. A private notifications channel delivered a password reset link +// to an anonymous subscriber. +func TestSubscribe_AnonymousCannotReadPrivateChannel(t *testing.T) { + m, _, chans := realManager(t) + ctx := context.Background() + + createChannel(t, chans, "user-42-notifications", true) + + attacker := newTestConn("attacker", "") + assertNoError(t, m.Register(attacker)) + + err := m.Subscribe(ctx, attacker.ID(), "user-42-notifications", nil) + assertErrorIs(t, err, ErrChannelAccessDenied) + + _ = m.BroadcastToChannel(ctx, "user-42-notifications", + &Message{ID: "secret", Type: MessageTypeMessage, ChannelID: "user-42-notifications", Data: "password reset link"}) + + attacker.waitQuiet(t) + + if n := attacker.rec.totalWrites(); n != 0 { + t.Fatalf("anonymous connection received %d private channel frames", n) + } +} + +func TestSubscribe_AnonymousRefusedByDefault(t *testing.T) { + m, _, chans := realManager(t) + createChannel(t, chans, "news", false) + + anon := newTestConn("anon", "") + assertNoError(t, m.Register(anon)) + + assertErrorIs(t, m.Subscribe(context.Background(), anon.ID(), "news", nil), ErrChannelAccessDenied) +} + +func TestSubscribe_AnonymousAllowedWhenConfigured(t *testing.T) { + cfg := DefaultConfig() + cfg.AllowAnonymousSubscriptions = true + + chans := local.NewChannelStore() + m := NewManager(cfg, local.NewRoomStore(), chans, local.NewMessageStore(), + newFakePresenceTracker(), newFakeTypingTracker(), nil, nil, nil) + + createChannel(t, chans, "news", false) + createChannel(t, chans, "secret", true) + + anon := newTestConn("anon", "") + assertNoError(t, m.Register(anon)) + + assertNoError(t, m.Subscribe(context.Background(), anon.ID(), "news", nil)) + + // Admitting anonymous subscribers does not open private channels: the + // default authorizer, which NewManager installs on its own, still refuses. + assertErrorIs(t, m.Subscribe(context.Background(), anon.ID(), "secret", nil), ErrChannelAccessDenied) +} + +func TestSubscribe_PrivateChannelNeedsAuthorizer(t *testing.T) { + m, _, chans := realManager(t) + ctx := context.Background() + + createChannel(t, chans, "user-42-notifications", true) + + owner := newTestConn("owner", "user-42") + other := newTestConn("other", "user-7") + + for _, c := range []*testConn{owner, other} { + assertNoError(t, m.Register(c)) + } + + // The default policy cannot tell who belongs, so it refuses everyone. + assertErrorIs(t, m.Subscribe(ctx, owner.ID(), "user-42-notifications", nil), ErrChannelAccessDenied) + + // An application policy that knows its users decides instead. + m.(*manager).setChannelAuthorizer(streamauth.ChannelAuthorizerFunc( + func(_ context.Context, userID, channelID string) (bool, error) { + return channelID == "user-"+strings.TrimPrefix(userID, "user-")+"-notifications", nil + })) + + assertNoError(t, m.Subscribe(ctx, owner.ID(), "user-42-notifications", nil)) + assertErrorIs(t, m.Subscribe(ctx, other.ID(), "user-42-notifications", nil), ErrChannelAccessDenied) +} + +func TestSubscribe_AuthenticatedPublicChannelStillWorks(t *testing.T) { + m, _, chans := realManager(t) + createChannel(t, chans, "news", false) + + c := newTestConn("c1", "alice") + assertNoError(t, m.Register(c)) + + assertNoError(t, m.Subscribe(context.Background(), c.ID(), "news", nil)) + + if !c.IsSubscribed("news") { + t.Fatal("connection not subscribed after an allowed Subscribe") + } +} + +// End to end: the exact request from the finding, an anonymous +// GET /sse?channels=user-42-notifications, must not end up subscribed. +func TestHandleSSE_AnonymousChannelsParamIsRefused(t *testing.T) { + app := forge.NewApp(forge.AppConfig{Name: "sse-auth"}) + ext := NewExtension(WithLocalBackend()) + + if err := ext.Register(app); err != nil { + t.Fatal(err) + } + + if err := ext.RegisterRoutes(app.Router(), "/ws", "/sse"); err != nil { + t.Fatal(err) + } + + srv := httptest.NewServer(app.Router().(http.Handler)) + defer srv.Close() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + if err := ext.Manager().CreateChannel(ctx, local.NewLocalChannel(streaming.ChannelOptions{ + ID: "user-42-notifications", Name: "n", Private: true, + })); err != nil { + t.Fatal(err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/sse?channels=user-42-notifications", nil) + if err != nil { + t.Fatal(err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + + sc := bufio.NewScanner(resp.Body) + for sc.Scan() { + if strings.HasPrefix(sc.Text(), "event: connected") { + break + } + } + + conns := ext.Manager().GetAllConnections() + if len(conns) != 1 { + t.Fatalf("expected one registered SSE connection, got %d", len(conns)) + } + + // The handler subscribes from the query string just after it writes the + // connected event. Watch for a while rather than checking once, so the + // check cannot pass merely by running before the handler got there. + deadline := time.Now().Add(300 * time.Millisecond) + for time.Now().Before(deadline) { + if subs := conns[0].GetSubscriptions(); len(subs) != 0 { + t.Fatalf("anonymous SSE connection subscribed to %v", subs) + } + + time.Sleep(5 * time.Millisecond) + } +} diff --git a/extensions/streaming/configs.go b/extensions/streaming/configs.go index 7ccaf21c3..806bacfde 100644 --- a/extensions/streaming/configs.go +++ b/extensions/streaming/configs.go @@ -92,6 +92,12 @@ func WithSessionResumption(ttl time.Duration) ConfigOption { return internal.WithSessionResumption(ttl) } +// WithAnonymousSubscriptions sets whether connections with no authenticated +// user may subscribe to channels. Off by default. +func WithAnonymousSubscriptions(allow bool) ConfigOption { + return internal.WithAnonymousSubscriptions(allow) +} + func WithLoadBalancer(strategy string) ConfigOption { return internal.WithLoadBalancer(strategy) } diff --git a/extensions/streaming/extension.go b/extensions/streaming/extension.go index 3a75dfd37..bfffdcb04 100644 --- a/extensions/streaming/extension.go +++ b/extensions/streaming/extension.go @@ -35,6 +35,10 @@ type Extension struct { manager Manager hooks *HookRegistry codecs *CodecRegistry + + // channelAuth, when set by SetChannelAuthorizer, replaces the default + // channel policy. + channelAuth streamauth.ChannelAuthorizer } // NewExtension creates a new streaming extension with functional options. @@ -191,6 +195,17 @@ func (e *Extension) Register(app forge.App) error { managerOpts = append(managerOpts, WithMessageAuthorizer(streamauth.NewMessageAuthorizer(roomAuthorizer, newAuthMessageStore(messageStore)))) + // Channel subscriptions get the same treatment. The default admits public + // channels and refuses private ones, since the store has no record of who + // belongs to a private channel; SetChannelAuthorizer supplies a policy + // that does. + channelAuthorizer := e.channelAuth + if channelAuthorizer == nil { + channelAuthorizer = streamauth.NewChannelAuthorizer(channelStore) + } + + managerOpts = append(managerOpts, WithChannelAuthorizer(channelAuthorizer)) + // Create rate limiter using config values rlConfig := ratelimit.DefaultRateLimitConfig() rlConfig.MessagesPerSecond = e.config.MaxMessagesPerSecond @@ -353,6 +368,25 @@ func (e *Extension) Health(ctx context.Context) error { return nil } +// SetChannelAuthorizer replaces the policy that decides who may subscribe to +// which channel. Call it before Register, or after it to swap the policy on a +// running manager. Passing nil restores the default, which admits public +// channels and refuses private ones. +func (e *Extension) SetChannelAuthorizer(ca streamauth.ChannelAuthorizer) { + e.channelAuth = ca + + m, ok := e.manager.(*manager) + if !ok { + return + } + + if ca == nil { + ca = streamauth.NewChannelAuthorizer(m.channelStore) + } + + m.setChannelAuthorizer(ca) +} + // Manager returns the streaming manager (for advanced usage). func (e *Extension) Manager() Manager { return e.manager diff --git a/extensions/streaming/internal/config.go b/extensions/streaming/internal/config.go index 857abd082..089273f62 100644 --- a/extensions/streaming/internal/config.go +++ b/extensions/streaming/internal/config.go @@ -34,6 +34,13 @@ type Config struct { // runs out of descriptors. 0 disables the cap. MaxAnonymousConnections int `json:"max_anonymous_connections" yaml:"max_anonymous_connections"` + // AllowAnonymousSubscriptions lets connections with no authenticated user + // subscribe to channels. Off by default: a channel is how per-user data + // such as notifications reaches a client, and an unauthenticated + // EventSource could otherwise subscribe to any channel it could name. Even + // when on, the ChannelAuthorizer still decides each subscription. + AllowAnonymousSubscriptions bool `json:"allow_anonymous_subscriptions" yaml:"allow_anonymous_subscriptions"` + // MaxTotalConnections caps sockets on this node regardless of identity. A // per-user limit does not bound the total: enough distinct users exceed any // per-user number. 0 disables the cap. @@ -201,6 +208,14 @@ func WithConfig(config Config) ConfigOption { } } +// WithAnonymousSubscriptions sets whether connections with no authenticated +// user may subscribe to channels. See Config.AllowAnonymousSubscriptions. +func WithAnonymousSubscriptions(allow bool) ConfigOption { + return func(c *Config) { + c.AllowAnonymousSubscriptions = allow + } +} + // WithBackend sets the backend type. func WithBackend(backend string) ConfigOption { return func(c *Config) { diff --git a/extensions/streaming/manager.go b/extensions/streaming/manager.go index ea143a2de..abf7c8d22 100644 --- a/extensions/streaming/manager.go +++ b/extensions/streaming/manager.go @@ -54,6 +54,12 @@ type manager struct { roomAuth streamauth.RoomAuthorizer messageAuth streamauth.MessageAuthorizer + // channelAuth decides channel subscriptions. Unlike the two above it is + // never left nil: NewManager falls back to the default policy, because a + // Subscribe with no check at all handed any channel, private ones + // included, to whoever named it. + channelAuth streamauth.ChannelAuthorizer + // Load balancer (optional, distributed mode) loadBalancer lb.LoadBalancer healthChecker lb.HealthChecker @@ -154,6 +160,13 @@ func WithMessageAuthorizer(ma streamauth.MessageAuthorizer) ManagerOption { return func(m *manager) { m.messageAuth = ma } } +// WithChannelAuthorizer sets the channel authorizer consulted on every +// Subscribe. Without it the manager uses streamauth.NewChannelAuthorizer, +// which admits public channels and refuses private ones. +func WithChannelAuthorizer(ca streamauth.ChannelAuthorizer) ManagerOption { + return func(m *manager) { m.channelAuth = ca } +} + // WithManagerNodeID sets the node ID for distributed mode. func WithManagerNodeID(id string) ManagerOption { return func(m *manager) { m.nodeID = id } @@ -202,9 +215,29 @@ func NewManager( opt(m) } + if m.channelAuth == nil && channelStore != nil { + m.channelAuth = streamauth.NewChannelAuthorizer(channelStore) + } + return m } +// setChannelAuthorizer replaces the channel authorizer after construction. +// Used by Extension.SetChannelAuthorizer. +func (m *manager) setChannelAuthorizer(ca streamauth.ChannelAuthorizer) { + m.mu.Lock() + defer m.mu.Unlock() + + m.channelAuth = ca +} + +func (m *manager) channelAuthorizer() streamauth.ChannelAuthorizer { + m.mu.RLock() + defer m.mu.RUnlock() + + return m.channelAuth +} + // Connection management func (m *manager) Register(conn Connection) error { @@ -800,6 +833,18 @@ func (m *manager) Subscribe(ctx context.Context, connID, channelID string, filte userID := conn.GetUserID() + // Authorization first, before the limit check or the store write, the + // same order JoinRoom uses. Subscribe used to check nothing, so an + // anonymous EventSource asking for ?channels=user-42-notifications got + // user 42's private notifications. + if err := m.authorizeSubscribe(ctx, userID, channelID); err != nil { + if m.metrics != nil { + m.metrics.Counter("streaming.channels.subscribes_denied").Inc() + } + + return err + } + // Check channel limit userChannels, _ := m.channelStore.GetUserChannels(ctx, userID) if m.config.MaxChannelsPerUser > 0 && len(userChannels) >= m.config.MaxChannelsPerUser { @@ -830,6 +875,30 @@ func (m *manager) Subscribe(ctx context.Context, connID, channelID string, filte return nil } +// authorizeSubscribe applies the anonymous-subscriber policy and then the +// channel authorizer. +func (m *manager) authorizeSubscribe(ctx context.Context, userID, channelID string) error { + if userID == "" && !m.config.AllowAnonymousSubscriptions { + return fmt.Errorf("%w: anonymous connections cannot subscribe to channels", ErrChannelAccessDenied) + } + + ca := m.channelAuthorizer() + if ca == nil { + return nil + } + + allowed, err := ca.CanSubscribe(ctx, userID, channelID) + if err != nil { + return fmt.Errorf("channel subscribe authorization failed: %w", err) + } + + if !allowed { + return ErrChannelAccessDenied + } + + return nil +} + func (m *manager) Unsubscribe(ctx context.Context, connID, channelID string) error { conn, err := m.GetConnection(connID) if err != nil { From 22032c8562fd1ebd50f0f0e6d0e9de0bbd4de7da Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:10:14 -0600 Subject: [PATCH 05/17] fix(streaming): let WebSocket clients join rooms ProcessInbound runs every client frame through authorizeSend, which required the connection to be in msg.RoomID already, whatever the message type. A join frame is by definition from a connection that is not in the room yet, so every one was rejected with send_denied and never reached JoinRoom. No WebSocket client could join a room. Leave frames hit the same check for no reason. Join frames now skip the membership check and get a join check instead: the room authorizer's CanJoin, a refusal for anonymous connections, and a refusal for users banned from the room in the store. JoinRoom still runs CanJoin itself, since server code calls it directly. Leave frames need no permission. Sends still require membership. The new end-to-end test drives a real WebSocket through the read loop, ProcessInbound and handleMessage rather than calling handleMessage. --- extensions/streaming/inbound_join_test.go | 183 ++++++++++++++++++++++ extensions/streaming/manager.go | 53 +++++++ 2 files changed, 236 insertions(+) create mode 100644 extensions/streaming/inbound_join_test.go diff --git a/extensions/streaming/inbound_join_test.go b/extensions/streaming/inbound_join_test.go new file mode 100644 index 000000000..4812f790b --- /dev/null +++ b/extensions/streaming/inbound_join_test.go @@ -0,0 +1,183 @@ +package streaming + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsutil" + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/streaming/backends/local" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// A client "join" frame used to be rejected by ProcessInbound, because the +// gate demanded the connection already be in msg.RoomID for every message +// type. No WebSocket client could ever join a room. +func TestProcessInbound_JoinFrameReachesJoinRoom(t *testing.T) { + m, rooms, _ := realManager(t) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "public", Name: "public", Owner: "o"}))) + + c := newTestConn("c1", "alice") + assertNoError(t, m.Register(c)) + + if _, err := m.ProcessInbound(ctx, &Message{Type: MessageTypeJoin, RoomID: "public"}, c); err != nil { + t.Fatalf("join frame rejected by the inbound gate: %v", err) + } +} + +// Exempting joins from the membership check must not exempt them from join +// authorization. +func TestProcessInbound_JoinFrameStillAuthorized(t *testing.T) { + m, rooms, _ := realManager(t) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "secret", Name: "secret", Owner: "o", Private: true}))) + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "public", Name: "public", Owner: "o"}))) + assertNoError(t, rooms.BanMember(ctx, "public", "mallory", streaming.RoomBan{UserID: "mallory"})) + + alice := newTestConn("c1", "alice") + mallory := newTestConn("c2", "mallory") + anon := newTestConn("c3", "") + + for _, c := range []*testConn{alice, mallory, anon} { + assertNoError(t, m.Register(c)) + } + + cases := []struct { + name string + conn *testConn + room string + want error + }{ + {"private room", alice, "secret", ErrRoomAccessDenied}, + {"banned user", mallory, "public", ErrUserBanned}, + {"anonymous", anon, "public", ErrRoomAccessDenied}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, err := m.ProcessInbound(ctx, &Message{Type: MessageTypeJoin, RoomID: tc.room}, tc.conn) + assertErrorIs(t, err, tc.want) + }) + } +} + +func TestProcessInbound_LeaveFrameNeedsNoMembership(t *testing.T) { + m, _, _ := realManager(t) + + c := newTestConn("c1", "alice") + assertNoError(t, m.Register(c)) + + if _, err := m.ProcessInbound(context.Background(), &Message{Type: MessageTypeLeave, RoomID: "elsewhere"}, c); err != nil { + t.Fatalf("leave frame rejected: %v", err) + } +} + +// Sends still need membership: the join exemption must not leak into them. +func TestProcessInbound_SendStillNeedsMembership(t *testing.T) { + m, rooms, _ := realManager(t) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "public", Name: "public", Owner: "o"}))) + + c := newTestConn("c1", "alice") + assertNoError(t, m.Register(c)) + + _, err := m.ProcessInbound(ctx, &Message{Type: MessageTypeMessage, RoomID: "public", Data: "hi"}, c) + assertErrorIs(t, err, ErrSendDenied) +} + +// End to end through the real socket read loop, ProcessInbound and +// handleMessage: a client joins a room with a join frame and then receives +// the message it sends to that room. +func TestWebSocket_ClientJoinsRoomThroughInboundPath(t *testing.T) { + app := forge.NewApp(forge.AppConfig{Name: "join"}) + ext := NewExtension(WithLocalBackend()) + + if err := ext.Register(app); err != nil { + t.Fatal(err) + } + + // Stand-in for an auth middleware. + app.Router().Use(func(next forge.Handler) forge.Handler { + return func(ctx forge.Context) error { + if uid := ctx.Request().URL.Query().Get("uid"); uid != "" { + ctx.Set("user_id", uid) + } + + return next(ctx) + } + }) + + if err := ext.RegisterRoutes(app.Router(), "/ws", "/sse"); err != nil { + t.Fatal(err) + } + + srv := httptest.NewServer(app.Router().(http.Handler)) + defer srv.Close() + + ctx := context.Background() + if err := ext.Manager().CreateRoom(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"})); err != nil { + t.Fatal(err) + } + + cli, _, _, err := ws.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/ws?uid=alice") + if err != nil { + t.Fatal(err) + } + defer cli.Close() + + send := func(m map[string]any) { + t.Helper() + + data, err := json.Marshal(m) + if err != nil { + t.Fatal(err) + } + + if err := wsutil.WriteClientText(cli, data); err != nil { + t.Fatal(err) + } + } + + send(map[string]any{"type": MessageTypeJoin, "room_id": "lobby"}) + send(map[string]any{"type": MessageTypeMessage, "room_id": "lobby", "data": "hello"}) + + _ = cli.SetReadDeadline(time.Now().Add(3 * time.Second)) + + for { + data, err := wsutil.ReadServerText(cli) + if err != nil { + t.Fatalf("never received the room message: %v", err) + } + + var msg Message + if err := json.Unmarshal(data, &msg); err != nil { + t.Fatalf("undecodable frame %s: %v", data, err) + } + + if msg.Type == MessageTypeError { + t.Fatalf("server rejected a frame: %s", data) + } + + if msg.Type == MessageTypeMessage && msg.RoomID == "lobby" { + if msg.Data != "hello" || msg.UserID != "alice" { + t.Fatalf("unexpected room message: %s", data) + } + + break + } + } + + if conns := ext.Manager().GetUserConnections("alice"); len(conns) != 1 || !conns[0].IsInRoom("lobby") { + t.Fatal("connection is not in the room after the join frame") + } +} diff --git a/extensions/streaming/manager.go b/extensions/streaming/manager.go index abf7c8d22..08fe3a057 100644 --- a/extensions/streaming/manager.go +++ b/extensions/streaming/manager.go @@ -1164,6 +1164,19 @@ func (m *manager) authorizeSend(ctx context.Context, message *Message, sender Co return nil // Server-originated message; not subject to client authorization. } + // Membership control frames are not sends. Requiring the sender to be in + // the room already made a join frame impossible to pass: every client + // "join" was rejected here and never reached JoinRoom, so a WebSocket + // client had no way into a room at all. + switch message.Type { + case streaming.MessageTypeJoin: + return m.authorizeJoinFrame(ctx, message, userID) + case streaming.MessageTypeLeave: + // Leaving a room the connection is not in is a no-op in LeaveRoom, and + // leaving one it is in needs no permission. + return nil + } + switch { case message.RoomID != "": // Membership is the baseline check and does not depend on an authorizer @@ -1229,6 +1242,46 @@ func (m *manager) authorizeSend(ctx context.Context, message *Message, sender Co return nil } +// authorizeJoinFrame checks a client's request to join a room before it +// reaches JoinRoom. +// +// JoinRoom applies the room authorizer itself, since it is also called from +// server code. The gate asks the same question first so a refused join is +// reported as a rejection like any other refused frame, and it also refuses a +// user banned from the room, which CanJoin does not consider. +func (m *manager) authorizeJoinFrame(ctx context.Context, message *Message, userID string) error { + if message.RoomID == "" { + return nil // handleMessage ignores a join with no room. + } + + if userID == "" { + return fmt.Errorf("%w: anonymous connections cannot join rooms", ErrRoomAccessDenied) + } + + if m.roomAuth != nil { + allowed, err := m.roomAuth.CanJoin(ctx, userID, message.RoomID) + if err != nil { + return fmt.Errorf("room join authorization failed: %w", err) + } + + if !allowed { + if m.metrics != nil { + m.metrics.Counter("streaming.rooms.joins_denied").Inc() + } + + return ErrRoomAccessDenied + } + } + + // Asked of the store rather than the room object: the local backend keeps + // bans in the store, and its room's IsBanned only reports an error. + if banned, err := m.roomStore.IsBanned(ctx, message.RoomID, userID); err == nil && banned { + return ErrUserBanned + } + + return nil +} + // approximateMessageSize estimates the wire size of a message without paying // for a full encode. // From ea051790296a0497f483851727a8e7c6eb75f87c Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:15:56 -0600 Subject: [PATCH 06/17] fix(streaming): emit SSE event ids for messages sent through the queue sseConnection.WriteJSON only tags an event with a resume id when it is handed a *Message. In production nothing hands it one: the enhanced connection's send queue encodes on the caller's goroutine and the writer replays the bytes as a json.RawMessage, so the type check never matched, no SSE event ever carried an id, and Last-Event-ID resume could not work. Queued frames now carry the room id and sequence of the message they were encoded from, and the writer passes them to the SSE transport, which builds the cursor id from them as before. A test reconnects a real EventSource style client with the id it last saw and gets the message it missed. --- extensions/streaming/connection.go | 35 ++- extensions/streaming/sendqueue.go | 7 + extensions/streaming/sse_connection.go | 27 ++- extensions/streaming/sse_queue_id_test.go | 257 ++++++++++++++++++++++ 4 files changed, 319 insertions(+), 7 deletions(-) create mode 100644 extensions/streaming/sse_queue_id_test.go diff --git a/extensions/streaming/connection.go b/extensions/streaming/connection.go index 2c9018965..efad35d07 100644 --- a/extensions/streaming/connection.go +++ b/extensions/streaming/connection.go @@ -167,11 +167,16 @@ func (c *enhancedConn) WriteJSON(v any) error { return err } - return c.queue.enqueue(sendFrame{ - msgType: messageTypeOf(v), - payload: data, - kind: frameJSON, - }) + frame := sendFrame{payload: data, kind: frameJSON} + describeFrame(&frame, v) + + return c.queue.enqueue(frame) +} + +// sequencedJSONWriter is implemented by transports that tag a JSON frame with +// the room sequence it carries. sseConnection does, to emit event ids. +type sequencedJSONWriter interface { + writeSequencedJSON(data []byte, roomID string, seq int64) error } // WriteBinary queues a binary frame for the socket. @@ -256,6 +261,10 @@ func (c *enhancedConn) SendQueueStats() SendQueueStats { func (c *enhancedConn) writeFrame(f sendFrame) error { switch f.kind { case frameJSON: + if sw, ok := c.Connection.(sequencedJSONWriter); ok { + return sw.writeSequencedJSON(f.payload, f.roomID, f.seq) + } + return c.Connection.WriteJSON(json.RawMessage(f.payload)) case frameBinary: @@ -295,6 +304,22 @@ func (c *enhancedConn) closeUnderlying() error { return c.closeErr } +// describeFrame copies what the queue and the transport need to know about a +// payload onto its frame: the message type for the overflow policy, and the +// room and sequence for transports that emit resume ids. +func describeFrame(f *sendFrame, v any) { + f.msgType = messageTypeOf(v) + + switch msg := v.(type) { + case *internal.Message: + if msg != nil { + f.roomID, f.seq = msg.RoomID, msg.Sequence + } + case internal.Message: + f.roomID, f.seq = msg.RoomID, msg.Sequence + } +} + // messageTypeOf extracts the streaming message type from an outbound payload. // An unrecognised payload reports no type, which selects the conservative // disconnect overflow policy. diff --git a/extensions/streaming/sendqueue.go b/extensions/streaming/sendqueue.go index ebd22d5af..7c623c5e9 100644 --- a/extensions/streaming/sendqueue.go +++ b/extensions/streaming/sendqueue.go @@ -93,6 +93,13 @@ type sendFrame struct { payload []byte kind frameKind + // roomID and seq carry a room message's sequence past the encode, for + // transports that tag frames with a resume position. SSE writes them into + // the event id; without them the writer saw only bytes and every event + // went out with no id at all. + roomID string + seq int64 + // done belongs to frameBarrier frames and is closed once the writer has // reached this point in the queue. done chan struct{} diff --git a/extensions/streaming/sse_connection.go b/extensions/streaming/sse_connection.go index 3b2be55d5..980cf2637 100644 --- a/extensions/streaming/sse_connection.go +++ b/extensions/streaming/sse_connection.go @@ -3,6 +3,7 @@ package streaming import ( "context" "encoding/base64" + "encoding/json" "errors" "maps" "sync" @@ -88,14 +89,36 @@ func (c *sseConnection) WriteBinary(data []byte) error { // never receive its backlog at all. func (c *sseConnection) WriteJSON(v any) error { msg, ok := v.(*streaming.Message) - if !ok || msg.RoomID == "" || msg.Sequence <= 0 { + if !ok || msg == nil { + return c.send(v, "", 0) + } + + return c.send(v, msg.RoomID, msg.Sequence) +} + +// writeSequencedJSON sends a message that has already been encoded, with the +// room and sequence it was encoded from. +// +// This is the path every message takes in production: the enhanced +// connection's send queue encodes on the caller's goroutine and hands the +// writer bytes, not a *Message. WriteJSON's type check therefore never +// matched, and no event ever carried an id, so Last-Event-ID resume could not +// work. The sequence now travels with the frame instead. +func (c *sseConnection) writeSequencedJSON(data []byte, roomID string, seq int64) error { + return c.send(json.RawMessage(data), roomID, seq) +} + +// send writes v as a "message" event, with a resume id when it carries a room +// sequence. +func (c *sseConnection) send(v any, roomID string, seq int64) error { + if roomID == "" || seq <= 0 { // Unsequenced: presence, typing, system frames. These are not part of // any room's ordered history, and inventing an id for them would move // the client's resume point to a place it was never actually at. return c.stream.SendJSON("message", v) } - id := c.advanceCursor(msg.RoomID, msg.Sequence) + id := c.advanceCursor(roomID, seq) // Fall back cleanly on a transport with no id support, so an SSE stream // predating event ids still delivers — just without resumability. diff --git a/extensions/streaming/sse_queue_id_test.go b/extensions/streaming/sse_queue_id_test.go new file mode 100644 index 000000000..75a1eec78 --- /dev/null +++ b/extensions/streaming/sse_queue_id_test.go @@ -0,0 +1,257 @@ +package streaming + +import ( + "bufio" + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/streaming/backends/local" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// flushConn waits for everything queued on an enhanced connection to reach +// its transport. +func flushConn(t *testing.T, conn Connection) { + t.Helper() + + f, ok := conn.(interface { + Flush(ctx context.Context) error + }) + if !ok { + t.Fatal("connection has no Flush") + } + + if err := f.Flush(context.Background()); err != nil { + t.Fatal(err) + } +} + +// Every production write goes through the send queue, which encodes on the +// caller's goroutine and gives the writer bytes. sseConnection.WriteJSON only +// emitted an id for a *Message, so through the queue no event ever had one and +// Last-Event-ID resume could not work. +func TestSSE_SequencedMessageThroughQueueCarriesID(t *testing.T) { + stream := &fakeStream{} + conn := NewConnectionWithTransport(NewSSEConnection(stream, "", ""), TransportSSE) + + assertNoError(t, conn.WriteJSON(&Message{ID: "a", Type: MessageTypeMessage, RoomID: "room-1", Sequence: 3})) + assertNoError(t, conn.WriteJSON(&Message{ID: "b", Type: MessageTypeMessage, RoomID: "room-2", Sequence: 9})) + assertNoError(t, conn.WriteJSON(&Message{ID: "c", Type: MessageTypePresence})) + flushConn(t, conn) + + events := stream.snapshot() + if len(events) != 3 { + t.Fatalf("got %d events, want 3", len(events)) + } + + cursor, err := decodeReplayCursor(events[1].id) + if err != nil { + t.Fatalf("second event id %q is not a cursor: %v", events[1].id, err) + } + + if cursor["room-1"] != 3 || cursor["room-2"] != 9 { + t.Fatalf("cursor = %v, want room-1:3 room-2:9", cursor) + } + + if events[2].id != "" { + t.Fatalf("unsequenced presence event got id %q", events[2].id) + } +} + +// The same holds when a broadcast fans one shared encoding out to many SSE +// connections. +func TestSSE_RoomBroadcastCarriesID(t *testing.T) { + m, rooms, _ := realManager(t) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + const n = 12 // above the serial fan-out threshold, so the worker pool runs + + streams := make([]*fakeStream, n) + conns := make([]Connection, n) + + for i := range n { + streams[i] = &fakeStream{} + conns[i] = NewConnectionWithTransport(NewSSEConnection(streams[i], "", ""), TransportSSE) + } + + for i, c := range conns { + c.SetUserID(fmt.Sprintf("user-%d", i)) + assertNoError(t, m.Register(c)) + assertNoError(t, m.JoinRoom(ctx, c.ID(), "lobby")) + } + + assertNoError(t, m.BroadcastToRoom(ctx, "lobby", &Message{ID: "m", Type: MessageTypeMessage, RoomID: "lobby", Sequence: 4, Data: "hi"})) + + for i, c := range conns { + flushConn(t, c) + + events := streams[i].snapshot() + if len(events) != 1 { + t.Fatalf("conn %d: got %d events, want 1", i, len(events)) + } + + cursor, err := decodeReplayCursor(events[0].id) + if err != nil || cursor["lobby"] != 4 { + t.Fatalf("conn %d: event id %q, want a cursor at lobby:4 (err %v)", i, events[0].id, err) + } + } +} + +// End to end over HTTP: a client that reconnects with the id it last saw gets +// the message it missed while away. +func TestHandleSSE_LastEventIDResumesMissedMessages(t *testing.T) { + app := forge.NewApp(forge.AppConfig{Name: "sse-resume"}) + ext := NewExtension(WithLocalBackend()) + + if err := ext.Register(app); err != nil { + t.Fatal(err) + } + + app.Router().Use(func(next forge.Handler) forge.Handler { + return func(ctx forge.Context) error { + if uid := ctx.Request().URL.Query().Get("uid"); uid != "" { + ctx.Set("user_id", uid) + } + + return next(ctx) + } + }) + + if err := ext.RegisterRoutes(app.Router(), "/ws", "/sse"); err != nil { + t.Fatal(err) + } + + srv := httptest.NewServer(app.Router().(http.Handler)) + defer srv.Close() + + ctx := context.Background() + mgr := ext.Manager() + + if err := mgr.CreateRoom(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"})); err != nil { + t.Fatal(err) + } + + publish := func(data string) { + t.Helper() + + msg := &Message{ID: data, Type: MessageTypeMessage, RoomID: "lobby", Data: data, Timestamp: time.Now()} + assertNoError(t, mgr.SaveMessage(ctx, msg)) + assertNoError(t, mgr.BroadcastToRoom(ctx, "lobby", msg)) + } + + // open connects and returns a function yielding the next event's id and + // data lines. + open := func(lastEventID string) (func() (string, string), func()) { + t.Helper() + + // Bounded, so a missing event fails the test instead of hanging it. + reqCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + + req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, srv.URL+"/sse?rooms=lobby&uid=alice", nil) + if err != nil { + t.Fatal(err) + } + + if lastEventID != "" { + req.Header.Set("Last-Event-ID", lastEventID) + } + + resp, err := http.DefaultClient.Do(req) //nolint:bodyclose // closed by the returned stop function + if err != nil { + t.Fatal(err) + } + + sc := bufio.NewScanner(resp.Body) + + next := func() (string, string) { + var id, data string + + for sc.Scan() { + line := sc.Text() + + switch { + case strings.HasPrefix(line, "id: "): + id = strings.TrimPrefix(line, "id: ") + case strings.HasPrefix(line, "data: "): + data += strings.TrimPrefix(line, "data: ") + case line == "": + if data != "" { + return id, data + } + } + } + + t.Fatalf("stream ended: %v", sc.Err()) + + return "", "" + } + + return next, func() { cancel(); _ = resp.Body.Close() } + } + + waitFor := func(next func() (string, string), text string) string { + t.Helper() + + for { + id, data := next() + if strings.Contains(data, `"data":"`+text+`"`) { + return id + } + } + } + + next, closeFirst := open("") + defer closeFirst() + + next() // the connected event; rooms are joined right after it + + // The join from ?rooms= runs after the connected event is written. + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if conns := mgr.GetUserConnections("alice"); len(conns) == 1 && conns[0].IsInRoom("lobby") { + break + } + + time.Sleep(5 * time.Millisecond) + } + + publish("one") + + id := waitFor(next, "one") + if id == "" { + t.Fatal("room message arrived with no SSE id; the client has nothing to resume from") + } + + closeFirst() + + for time.Now().Before(deadline.Add(2*time.Second)) && mgr.ConnectionCount() > 0 { + time.Sleep(5 * time.Millisecond) + } + + publish("two") // missed: nobody is connected + + next2, closeSecond := open(id) + defer closeSecond() + + done := make(chan struct{}) + + go func() { + defer close(done) + + waitFor(next2, "two") + }() + + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("reconnecting with Last-Event-ID did not replay the missed message") + } +} From 94515c4f4625c9d689847a5bde74bd46a7a9c9b4 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:18:23 -0600 Subject: [PATCH 07/17] perf(streaming): encode a broadcast once instead of per recipient Fan-out called WriteJSON on every recipient, and each one marshalled the same *Message on its own. The send queue writer then handed the result to the router as a json.RawMessage, and the router's WriteJSON marshalled it a second time. A 1000-member room cost two encodes per member per message. fanOut now keeps one encoding per content type for the message it was given and enqueues those shared bytes on every recipient whose filters left the message alone. A filter that substitutes a message still gets that message encoded separately. The router's wsConnection writes a json.RawMessage as is rather than marshalling it again. BenchmarkBroadcastToRoom_1000, 1000 members, against main: before: ~1.40 ms/op, 1.47 MB/op, 8,220 allocs/op after: ~0.88 ms/op, 0.13 MB/op, 2,143 allocs/op --- extensions/streaming/connection.go | 19 +++ extensions/streaming/fanout_bench_test.go | 106 ++++++++++++++ .../streaming/fanout_shared_encoding_test.go | 134 ++++++++++++++++++ extensions/streaming/manager.go | 87 +++++++++++- internal/router/streaming_websocket.go | 9 ++ .../streaming_websocket_control_test.go | 28 ++++ 6 files changed, 380 insertions(+), 3 deletions(-) create mode 100644 extensions/streaming/fanout_bench_test.go create mode 100644 extensions/streaming/fanout_shared_encoding_test.go diff --git a/extensions/streaming/connection.go b/extensions/streaming/connection.go index efad35d07..df37b4795 100644 --- a/extensions/streaming/connection.go +++ b/extensions/streaming/connection.go @@ -173,6 +173,25 @@ func (c *enhancedConn) WriteJSON(v any) error { return c.queue.enqueue(frame) } +// writeEncodedJSON queues msg already encoded as JSON in data. +// +// A broadcast encodes its message once and hands every recipient the same +// bytes through here, instead of each WriteJSON marshalling the same *Message +// again. The queue only reads data, so sharing it is safe; callers must not +// modify it afterwards. +func (c *enhancedConn) writeEncodedJSON(data []byte, msg *internal.Message) error { + frame := sendFrame{payload: data, kind: frameJSON} + describeFrame(&frame, msg) + + return c.queue.enqueue(frame) +} + +// encodedJSONWriter is implemented by connections that can queue pre-encoded +// JSON for a message, so a fan-out can share one encoding. +type encodedJSONWriter interface { + writeEncodedJSON(data []byte, msg *internal.Message) error +} + // sequencedJSONWriter is implemented by transports that tag a JSON frame with // the room sequence it carries. sseConnection does, to emit event ids. type sequencedJSONWriter interface { diff --git a/extensions/streaming/fanout_bench_test.go b/extensions/streaming/fanout_bench_test.go new file mode 100644 index 000000000..add1ead9e --- /dev/null +++ b/extensions/streaming/fanout_bench_test.go @@ -0,0 +1,106 @@ +package streaming + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + streamauth "github.com/xraph/forge/extensions/streaming/auth" + "github.com/xraph/forge/extensions/streaming/backends/local" + "github.com/xraph/forge/extensions/streaming/filters" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// routerLikeConn costs what the router's wsConnection costs to hand a frame +// to, minus the socket: WriteJSON marshals what it is given, except a +// json.RawMessage, which it writes as is. +type routerLikeConn struct { + recordingConn +} + +func (c *routerLikeConn) WriteJSON(v any) error { + if _, ok := v.(json.RawMessage); ok { + return nil + } + + _, err := json.Marshal(v) + + return err +} + +func (c *routerLikeConn) Write([]byte) error { return nil } + +func benchManager(b *testing.B) (Manager, streaming.RoomStore) { + b.Helper() + + rooms := local.NewRoomStore() + msgs := local.NewMessageStore() + ra := streamauth.NewRoomAuthorizer(rooms) + + m := NewManager(DefaultConfig(), rooms, local.NewChannelStore(), msgs, + newFakePresenceTracker(), newFakeTypingTracker(), nil, nil, nil, + WithRoomAuthorizer(ra), + WithMessageAuthorizer(streamauth.NewMessageAuthorizer(ra, newAuthMessageStore(msgs))), + WithFilterChain(filters.NewFilterChain()), + WithHookRegistry(NewHookRegistry()), + WithCodecRegistry(NewCodecRegistry()), + ) + + return m, rooms +} + +func benchMessage() *Message { + return &Message{ + ID: "m", Type: MessageTypeMessage, RoomID: "room", UserID: "u1", + Data: map[string]any{"text": strings.Repeat("hello world ", 40), "n": 1, "tags": []string{"a", "b", "c"}}, + Timestamp: time.Now(), + } +} + +// BenchmarkBroadcastToRoom_1000 measures one message to a 1000-member room. +// Each member used to marshal the message itself and the router marshalled +// the result again; now the fan-out encodes once and the bytes pass through. +func BenchmarkBroadcastToRoom_1000(b *testing.B) { + m, rooms := benchManager(b) + ctx := context.Background() + + if err := rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "room", Name: "room", Owner: "o"})); err != nil { + b.Fatal(err) + } + + conns := make([]Connection, 0, 1000) + + for i := range 1000 { + ec := NewConnection(&routerLikeConn{recordingConn: recordingConn{id: fmt.Sprintf("c%d", i)}}, + WithSendQueueCapacity(1<<20)) + ec.SetUserID(fmt.Sprintf("u%d", i)) + + if err := m.Register(ec); err != nil { + b.Fatal(err) + } + + if err := m.JoinRoom(ctx, ec.ID(), "room"); err != nil { + b.Fatal(err) + } + + conns = append(conns, ec) + } + + b.Cleanup(func() { + for _, c := range conns { + _ = c.Close() + } + }) + + msg := benchMessage() + + b.ReportAllocs() + b.ResetTimer() + + for b.Loop() { + _ = m.BroadcastToRoom(ctx, "room", msg) + } +} diff --git a/extensions/streaming/fanout_shared_encoding_test.go b/extensions/streaming/fanout_shared_encoding_test.go new file mode 100644 index 000000000..aa952ac68 --- /dev/null +++ b/extensions/streaming/fanout_shared_encoding_test.go @@ -0,0 +1,134 @@ +package streaming + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "sync/atomic" + "testing" + + "github.com/xraph/forge/extensions/streaming/backends/local" + "github.com/xraph/forge/extensions/streaming/filters" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// countingCodec counts encodes so a test can see how often a fan-out encoded. +type countingCodec struct { + encodes atomic.Int64 +} + +func (c *countingCodec) ContentType() string { return "application/x-count" } + +func (c *countingCodec) Encode(msg *Message) ([]byte, error) { + c.encodes.Add(1) + + return json.Marshal(msg) +} + +func (c *countingCodec) Decode(data []byte, msg *Message) error { return json.Unmarshal(data, msg) } + +// A broadcast encodes its message once and every recipient gets the same +// bytes, except one whose filter swapped the message out: that recipient gets +// its own message, encoded on its own. +func TestFanOut_EncodesOncePerContentType(t *testing.T) { + codec := &countingCodec{} + codecs := NewCodecRegistry() + codecs.Register(codec) + + chain := filters.NewFilterChain() + chain.Add(filters.NewSimpleFilter("redact-for-u3", 0, + func(_ context.Context, msg *streaming.Message, recipient streaming.EnhancedConnection) (*streaming.Message, error) { + if recipient.GetUserID() != "u3" { + return msg, nil + } + + cp := *msg + cp.Data = "redacted" + + return &cp, nil + })) + + m, rooms, _ := realManager(t, WithFilterChain(chain), WithCodecRegistry(codecs)) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + const n = 20 + + recs := make([]*recordingConn, n) + + for i := range n { + recs[i] = &recordingConn{id: fmt.Sprintf("c%d", i)} + conn := NewConnection(recs[i]) + conn.SetUserID(fmt.Sprintf("u%d", i)) + + // Half the room prefers the counting codec, so both the JSON path and + // the codec path are shared. + if i%2 == 0 { + conn.SetContentType(codec.ContentType()) + } + + assertNoError(t, m.Register(conn)) + assertNoError(t, m.JoinRoom(ctx, conn.ID(), "lobby")) + t.Cleanup(func() { _ = conn.Close() }) + } + + assertNoError(t, m.BroadcastToRoom(ctx, "lobby", &Message{ID: "m", Type: MessageTypeMessage, RoomID: "lobby", Data: "secret"})) + + for _, c := range m.GetAllConnections() { + flushConn(t, c) + } + + // Ten codec recipients, one encode. u3 prefers JSON, so its filter does + // not add a codec encode. + if got := codec.encodes.Load(); got != 1 { + t.Errorf("codec encoded %d times for one broadcast, want 1", got) + } + + var shared []byte + + for i, rec := range recs { + var data []byte + + if i%2 == 0 { + data = rec.lastRaw(t) + } else { + raw, ok := func() (json.RawMessage, bool) { + rec.mu.Lock() + defer rec.mu.Unlock() + + r, ok := rec.jsonWrites[len(rec.jsonWrites)-1].(json.RawMessage) + + return r, ok + }() + if !ok { + t.Fatalf("conn %d: JSON frame did not reach the transport as encoded bytes", i) + } + + data = raw + } + + var got Message + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("conn %d: %v", i, err) + } + + want := "secret" + if i == 3 { + want = "redacted" + } + + if got.Data != want { + t.Errorf("conn %d: data = %v, want %q", i, got.Data, want) + } + + if i%2 == 1 && i != 3 { + if shared == nil { + shared = data + } else if !bytes.Equal(shared, data) || &shared[0] != &data[0] { + t.Errorf("conn %d: JSON recipients did not share one encoding", i) + } + } + } +} diff --git a/extensions/streaming/manager.go b/extensions/streaming/manager.go index 08fe3a057..25a6b1f99 100644 --- a/extensions/streaming/manager.go +++ b/extensions/streaming/manager.go @@ -1302,8 +1302,58 @@ func approximateMessageSize(msg *Message) int { return len(data) } +// sharedEncoding holds one message's encodings for the duration of a fan-out, +// one per content type, so a broadcast encodes its message once rather than +// once per recipient. Safe for the fan-out's concurrent workers. +// +// It only covers the message the broadcast started with. A filter that hands +// a recipient a different message gets that message encoded on its own. +type sharedEncoding struct { + msg *Message + + mu sync.Mutex + byType map[string]sharedFrame +} + +type sharedFrame struct { + data []byte + err error +} + +func newSharedEncoding(msg *Message) *sharedEncoding { + return &sharedEncoding{msg: msg} +} + +// get returns the encoding for contentType, running encode the first time. +// The lock is held across encode on purpose: workers asking for the same +// content type wait for one encode instead of all doing it. +func (e *sharedEncoding) get(contentType string, encode func() ([]byte, error)) ([]byte, error) { + e.mu.Lock() + defer e.mu.Unlock() + + if f, ok := e.byType[contentType]; ok { + return f.data, f.err + } + + data, err := encode() + + if e.byType == nil { + e.byType = make(map[string]sharedFrame, 1) + } + + e.byType[contentType] = sharedFrame{data: data, err: err} + + return data, err +} + // deliverToConnection delivers a message to a single connection, applying per-recipient filters. func (m *manager) deliverToConnection(ctx context.Context, conn Connection, message *Message) error { + return m.deliverShared(ctx, conn, message, nil) +} + +// deliverShared is deliverToConnection with an optional encoding shared +// across a fan-out. enc may be nil. +func (m *manager) deliverShared(ctx context.Context, conn Connection, message *Message, enc *sharedEncoding) error { msg := message if m.filterChain != nil { filtered, err := m.filterChain.Apply(ctx, msg, conn) @@ -1329,8 +1379,23 @@ func (m *manager) deliverToConnection(ctx context.Context, conn Connection, mess contentType = conn.GetContentType() } + // The shared encoding applies only when the filters left the message as + // the broadcast sent it. + if enc != nil && msg != enc.msg { + enc = nil + } + // Use WriteJSON for default JSON or empty content type (backward compatible) if contentType == "" || contentType == streaming.ContentTypeJSON { + if w, ok := conn.(encodedJSONWriter); ok && enc != nil { + data, err := enc.get(streaming.ContentTypeJSON, func() ([]byte, error) { return json.Marshal(msg) }) + if err != nil { + return err + } + + return w.writeEncodedJSON(data, msg) + } + return conn.WriteJSON(msg) } @@ -1342,7 +1407,19 @@ func (m *manager) deliverToConnection(ctx context.Context, conn Connection, mess // The per-connection preference set via SetContentType therefore never // reached a codec at all. if m.codecs != nil { - data, err := m.codecs.EncodeWithType(contentType, msg) + encode := func() ([]byte, error) { return m.codecs.EncodeWithType(contentType, msg) } + + var ( + data []byte + err error + ) + + if enc != nil { + data, err = enc.get(contentType, encode) + } else { + data, err = encode() + } + if err != nil { return err } @@ -1483,6 +1560,10 @@ func (m *manager) fanOut( return 0 } + // Encode once for the whole fan-out. Every recipient used to marshal the + // same *Message itself: a 1000-member room cost 1000 encodes per message. + enc := newSharedEncoding(message) + logFailure := func(c Connection, err error) { if m.logger != nil { m.logger.Error("failed to deliver message", @@ -1499,7 +1580,7 @@ func (m *manager) fanOut( var count int64 for _, conn := range conns { - if err := m.deliverToConnection(ctx, conn, message); err != nil { + if err := m.deliverShared(ctx, conn, message, enc); err != nil { logFailure(conn, err) } else { count++ @@ -1523,7 +1604,7 @@ func (m *manager) fanOut( for range workers { wg.Go(func() { for conn := range work { - if err := m.deliverToConnection(ctx, conn, message); err != nil { + if err := m.deliverShared(ctx, conn, message, enc); err != nil { logFailure(conn, err) } else { count.Add(1) diff --git a/internal/router/streaming_websocket.go b/internal/router/streaming_websocket.go index 25464ad8c..2b9a36d4d 100644 --- a/internal/router/streaming_websocket.go +++ b/internal/router/streaming_websocket.go @@ -342,7 +342,16 @@ func (c *wsConnection) WriteBinary(data []byte) error { } // WriteJSON sends JSON to the WebSocket. +// +// A json.RawMessage is written as is. Callers that encode once and fan the +// same bytes out to many connections, such as the streaming extension's send +// queue, hand over RawMessage, and marshalling it again would only copy and +// re-validate bytes that are already JSON. The caller vouches for them. func (c *wsConnection) WriteJSON(v any) error { + if raw, ok := v.(json.RawMessage); ok && raw != nil { + return c.Write(raw) + } + data, err := json.Marshal(v) if err != nil { return err diff --git a/internal/router/streaming_websocket_control_test.go b/internal/router/streaming_websocket_control_test.go index c56bb3117..f3968e17e 100644 --- a/internal/router/streaming_websocket_control_test.go +++ b/internal/router/streaming_websocket_control_test.go @@ -3,6 +3,7 @@ package router import ( "bytes" "context" + "encoding/json" "errors" "io" "net" @@ -228,3 +229,30 @@ func TestWSConnection_PingBetweenFragmentsIsAnswered(t *testing.T) { t.Fatalf("reply = %v %q, want pong %q", h.OpCode, pong, "p1") } } + +// WriteJSON passes a json.RawMessage through untouched instead of marshalling +// it a second time, and still encodes a nil one as null. +func TestWSConnection_WriteJSONRawMessage(t *testing.T) { + srv, cli := wsPair(t) + + if err := srv.WriteJSON(json.RawMessage(`{"a":1}`)); err != nil { + t.Fatal(err) + } + + if err := srv.WriteJSON(json.RawMessage(nil)); err != nil { + t.Fatal(err) + } + + _ = cli.SetReadDeadline(time.Now().Add(2 * time.Second)) + + for _, want := range []string{`{"a":1}`, `null`} { + got, _, err := wsutil.ReadServerData(cli) + if err != nil { + t.Fatal(err) + } + + if string(got) != want { + t.Fatalf("frame = %q, want %q", got, want) + } + } +} From 1ddf9345c36f6484838c439a700ffc47181eda85 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:20:09 -0600 Subject: [PATCH 08/17] perf(streaming): deliver relayed room messages through the room index A room message arriving from another node was delivered by walking every connection on this node and testing IsInRoom, one at a time and with no worker pool. On a node with 20k sockets that cost about 10 ms per relayed message regardless of the room's size, while local broadcasts already used the room index. Its payload also went through encoding/json as a map, which the handler marshalled back to JSON and unmarshalled into a Message. Relayed room, user and global messages now go through roomRecipients, GetUserConnections and fanOut, the same path as local broadcasts, which also gives them the shared encoding. The Redis and NATS coordinators decode with the new coordinator.DecodeMessage, which unmarshals a broadcast payload straight into a *streaming.Message. Other message types keep the generic decode. The handler also accepts a json.RawMessage payload. BenchmarkRemoteRoomBroadcast_20k, wire bytes to delivery, 20k connections, 10 in the room, against main: before: ~9.2 ms/op, 349 KB/op, 184 allocs/op after: ~24 us/op, 6.5 KB/op, 86 allocs/op --- .../streaming/coordinator/coordinator.go | 50 ++++++++++++ .../streaming/coordinator/decode_test.go | 60 ++++++++++++++ extensions/streaming/coordinator/nats.go | 6 +- extensions/streaming/coordinator/redis.go | 6 +- .../streaming/coordinator_delivery_test.go | 80 +++++++++++++++++++ extensions/streaming/fanout_bench_test.go | 65 +++++++++++++++ extensions/streaming/manager.go | 39 +++++---- 7 files changed, 280 insertions(+), 26 deletions(-) create mode 100644 extensions/streaming/coordinator/decode_test.go create mode 100644 extensions/streaming/coordinator_delivery_test.go diff --git a/extensions/streaming/coordinator/coordinator.go b/extensions/streaming/coordinator/coordinator.go index f68c768e8..53c40d0dd 100644 --- a/extensions/streaming/coordinator/coordinator.go +++ b/extensions/streaming/coordinator/coordinator.go @@ -2,6 +2,7 @@ package coordinator import ( "context" + "encoding/json" "time" streaming "github.com/xraph/forge/extensions/streaming/internal" @@ -82,3 +83,52 @@ const ( MessageTypeNodeRegister = "node.register" MessageTypeNodeUnregister = "node.unregister" ) + +// rawCoordinatorMessage is CoordinatorMessage with the payload left encoded. +// The outer Payload field shadows the embedded one for encoding/json. +type rawCoordinatorMessage struct { + CoordinatorMessage + + Payload json.RawMessage `json:"payload"` +} + +// DecodeMessage decodes a coordinator message off the wire. +// +// A broadcast's payload is decoded straight into a *streaming.Message. Left to +// encoding/json it became a map[string]any, which the receiving node then +// marshalled back to JSON and unmarshalled again into a Message: two extra +// passes and a map of interface values per relayed message. Other message +// types keep the generic decode, since their payloads have no single shape. +func DecodeMessage(data []byte) (*CoordinatorMessage, error) { + var raw rawCoordinatorMessage + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + msg := raw.CoordinatorMessage + msg.Payload = nil + + if len(raw.Payload) == 0 || string(raw.Payload) == "null" { + return &msg, nil + } + + if msg.Type == MessageTypeBroadcast { + var sm streaming.Message + if err := json.Unmarshal(raw.Payload, &sm); err != nil { + return nil, err + } + + msg.Payload = &sm + + return &msg, nil + } + + var payload any + if err := json.Unmarshal(raw.Payload, &payload); err != nil { + return nil, err + } + + msg.Payload = payload + + return &msg, nil +} diff --git a/extensions/streaming/coordinator/decode_test.go b/extensions/streaming/coordinator/decode_test.go new file mode 100644 index 000000000..35ef5dfc0 --- /dev/null +++ b/extensions/streaming/coordinator/decode_test.go @@ -0,0 +1,60 @@ +package coordinator + +import ( + "encoding/json" + "testing" + + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +func TestDecodeMessage_BroadcastPayloadIsAMessage(t *testing.T) { + wire, err := json.Marshal(CoordinatorMessage{ + Type: MessageTypeBroadcast, + NodeID: "n1", + RoomID: "lobby", + Payload: &streaming.Message{ID: "m1", Type: streaming.MessageTypeMessage, RoomID: "lobby", Sequence: 5, Data: "hi"}, + }) + if err != nil { + t.Fatal(err) + } + + got, err := DecodeMessage(wire) + if err != nil { + t.Fatal(err) + } + + if got.Type != MessageTypeBroadcast || got.NodeID != "n1" || got.RoomID != "lobby" { + t.Fatalf("envelope = %+v", got) + } + + msg, ok := got.Payload.(*streaming.Message) + if !ok { + t.Fatalf("payload is %T, want *streaming.Message", got.Payload) + } + + if msg.ID != "m1" || msg.Sequence != 5 || msg.Data != "hi" { + t.Fatalf("payload = %+v", msg) + } +} + +// Payloads of other message types keep the generic decode they always had. +func TestDecodeMessage_OtherPayloadsStayGeneric(t *testing.T) { + got, err := DecodeMessage([]byte(`{"type":"node.register","nodeId":"n2","payload":{"address":"10.0.0.2"}}`)) + if err != nil { + t.Fatal(err) + } + + meta, ok := got.Payload.(map[string]any) + if !ok || meta["address"] != "10.0.0.2" { + t.Fatalf("payload = %#v, want a map", got.Payload) + } + + got, err = DecodeMessage([]byte(`{"type":"broadcast","payload":null}`)) + if err != nil { + t.Fatal(err) + } + + if got.Payload != nil { + t.Fatalf("null payload decoded to %#v", got.Payload) + } +} diff --git a/extensions/streaming/coordinator/nats.go b/extensions/streaming/coordinator/nats.go index 01800ec22..a52690b23 100644 --- a/extensions/streaming/coordinator/nats.go +++ b/extensions/streaming/coordinator/nats.go @@ -437,8 +437,8 @@ func (nc *natsCoordinator) messageHandler(msg *nats.Msg) { return } - var coordMsg CoordinatorMessage - if err := json.Unmarshal(msg.Data, &coordMsg); err != nil { + coordMsg, err := DecodeMessage(msg.Data) + if err != nil { _ = msg.Nak() return @@ -453,7 +453,7 @@ func (nc *natsCoordinator) messageHandler(msg *nats.Msg) { // Call handler ctx := context.Background() - if err := nc.handler(ctx, &coordMsg); err != nil { + if err := nc.handler(ctx, coordMsg); err != nil { _ = msg.Nak() return diff --git a/extensions/streaming/coordinator/redis.go b/extensions/streaming/coordinator/redis.go index 835e4974d..11c482f18 100644 --- a/extensions/streaming/coordinator/redis.go +++ b/extensions/streaming/coordinator/redis.go @@ -311,8 +311,8 @@ func (rc *redisCoordinator) handleMessage(ctx context.Context, payload string) { return } - var coordMsg CoordinatorMessage - if err := json.Unmarshal([]byte(payload), &coordMsg); err != nil { + coordMsg, err := DecodeMessage([]byte(payload)) + if err != nil { return } @@ -322,7 +322,7 @@ func (rc *redisCoordinator) handleMessage(ctx context.Context, payload string) { } // Call handler - _ = rc.handler(ctx, &coordMsg) + _ = rc.handler(ctx, coordMsg) } // TrackUserNode tracks user connection to node. diff --git a/extensions/streaming/coordinator_delivery_test.go b/extensions/streaming/coordinator_delivery_test.go new file mode 100644 index 000000000..ed815a6fd --- /dev/null +++ b/extensions/streaming/coordinator_delivery_test.go @@ -0,0 +1,80 @@ +package streaming + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/xraph/forge/extensions/streaming/backends/local" + "github.com/xraph/forge/extensions/streaming/coordinator" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// A room message relayed from another node reaches the local members of that +// room and nobody else, whichever payload shape the coordinator produced. +func TestHandleCoordinatorMessage_RoomDeliveryUsesMembership(t *testing.T) { + m, rooms, _ := realManager(t) + mgr := m.(*manager) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + conns := make([]*testConn, 12) + for i := range conns { + conns[i] = newTestConn(fmt.Sprintf("c%d", i), fmt.Sprintf("u%d", i)) + assertNoError(t, m.Register(conns[i])) + + if i%2 == 0 { + assertNoError(t, m.JoinRoom(ctx, conns[i].ID(), "lobby")) + } + } + + msg := &Message{ID: "remote-1", Type: MessageTypeMessage, RoomID: "lobby", Data: "hi", + Metadata: map[string]any{"_origin_node": "other"}} + + raw, err := json.Marshal(msg) + if err != nil { + t.Fatal(err) + } + + wire, err := json.Marshal(coordinator.CoordinatorMessage{ + Type: coordinator.MessageTypeBroadcast, NodeID: "other", RoomID: "lobby", Payload: msg, + }) + if err != nil { + t.Fatal(err) + } + + decoded, err := coordinator.DecodeMessage(wire) + if err != nil { + t.Fatal(err) + } + + payloads := []any{decoded.Payload, json.RawMessage(raw)} + + for i, p := range payloads { + cm := &coordinator.CoordinatorMessage{Type: coordinator.MessageTypeBroadcast, NodeID: "other", RoomID: "lobby", Payload: p} + + // Distinct ids, so dedup does not swallow the second delivery. + if pm, ok := p.(*streaming.Message); ok { + pm.ID = fmt.Sprintf("remote-%d", i) + } else { + cm.Payload = json.RawMessage(fmt.Appendf(nil, `{"id":"remote-%d","type":"message","room_id":"lobby","data":"hi"}`, i)) + } + + assertNoError(t, mgr.handleCoordinatorMessage(ctx, cm)) + } + + for i, c := range conns { + c.waitQuiet(t) + + want := 0 + if i%2 == 0 { + want = len(payloads) + } + + if got := c.rec.totalWrites(); got != want { + t.Errorf("conn %d: %d frames, want %d", i, got, want) + } + } +} diff --git a/extensions/streaming/fanout_bench_test.go b/extensions/streaming/fanout_bench_test.go index add1ead9e..60918d5b5 100644 --- a/extensions/streaming/fanout_bench_test.go +++ b/extensions/streaming/fanout_bench_test.go @@ -10,6 +10,7 @@ import ( streamauth "github.com/xraph/forge/extensions/streaming/auth" "github.com/xraph/forge/extensions/streaming/backends/local" + "github.com/xraph/forge/extensions/streaming/coordinator" "github.com/xraph/forge/extensions/streaming/filters" streaming "github.com/xraph/forge/extensions/streaming/internal" ) @@ -104,3 +105,67 @@ func BenchmarkBroadcastToRoom_1000(b *testing.B) { _ = m.BroadcastToRoom(ctx, "room", msg) } } + +// BenchmarkRemoteRoomBroadcast_20k measures a room message relayed from +// another node, from wire bytes to delivery, on a node holding 20k +// connections of which 10 are in the room. Delivery used to scan all 20k +// connections, and the payload went JSON -> map -> JSON -> Message. +func BenchmarkRemoteRoomBroadcast_20k(b *testing.B) { + mi, rooms := benchManager(b) + m := mi.(*manager) + ctx := context.Background() + + if err := rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "room", Name: "room", Owner: "o"})); err != nil { + b.Fatal(err) + } + + conns := make([]Connection, 0, 20000) + + for i := range 20000 { + ec := NewConnection(&routerLikeConn{recordingConn: recordingConn{id: fmt.Sprintf("c%d", i)}}, + WithSendQueueCapacity(1<<20)) + ec.SetUserID(fmt.Sprintf("u%d", i)) + + if err := m.Register(ec); err != nil { + b.Fatal(err) + } + + if i < 10 { + if err := m.JoinRoom(ctx, ec.ID(), "room"); err != nil { + b.Fatal(err) + } + } + + conns = append(conns, ec) + } + + b.Cleanup(func() { + for _, c := range conns { + _ = c.Close() + } + }) + + msg := benchMessage() + msg.Metadata = map[string]any{"_origin_node": "other"} + + wire, err := json.Marshal(coordinator.CoordinatorMessage{ + Type: coordinator.MessageTypeBroadcast, NodeID: "other", RoomID: "room", Payload: msg, + }) + if err != nil { + b.Fatal(err) + } + + b.ReportAllocs() + b.ResetTimer() + + for b.Loop() { + cm, err := coordinator.DecodeMessage(wire) + if err != nil { + b.Fatal(err) + } + + if err := m.handleCoordinatorMessage(ctx, cm); err != nil { + b.Fatal(err) + } + } +} diff --git a/extensions/streaming/manager.go b/extensions/streaming/manager.go index 25a6b1f99..4bd831e90 100644 --- a/extensions/streaming/manager.go +++ b/extensions/streaming/manager.go @@ -3318,14 +3318,21 @@ func (m *manager) handleCoordinatorMessage(ctx context.Context, msg *coordinator return nil } - // Extract the streaming message from payload + // Extract the streaming message from payload. The bundled coordinators + // decode a broadcast straight into a *Message (coordinator.DecodeMessage); + // the other shapes are kept for coordinators that hand over raw JSON or a + // generic map. var streamMsg *streaming.Message switch payload := msg.Payload.(type) { case *streaming.Message: streamMsg = payload + case json.RawMessage: + streamMsg = &streaming.Message{} + if err := json.Unmarshal(payload, streamMsg); err != nil { + return err + } case map[string]any: - // Coordinator deserializes JSON into map — re-marshal and unmarshal data, err := json.Marshal(payload) if err != nil { return err @@ -3353,29 +3360,21 @@ func (m *manager) handleCoordinatorMessage(ctx context.Context, msg *coordinator } } - // Deliver to local connections based on message type + // Deliver to local connections based on message type. + // + // Room delivery uses the room index, as a local broadcast does. It used to + // walk every connection on the node testing IsInRoom, one at a time: with + // 20k sockets that was about 10 ms per relayed message whatever the room's + // size. fanOut also shares one encoding across the recipients and spreads + // slow sockets over its worker pool. if msg.Type == coordinator.MessageTypeBroadcast { switch { case msg.RoomID != "": - // Room broadcast — deliver to local room members only - conns := m.GetAllConnections() - for _, conn := range conns { - if conn.IsInRoom(msg.RoomID) { - _ = m.deliverToConnection(ctx, conn, streamMsg) - } - } + m.fanOut(ctx, m.roomRecipients(msg.RoomID), streamMsg, "room", msg.RoomID) case msg.UserID != "": - // User-targeted — deliver to local connections for this user - conns := m.GetUserConnections(msg.UserID) - for _, conn := range conns { - _ = m.deliverToConnection(ctx, conn, streamMsg) - } + m.fanOut(ctx, m.GetUserConnections(msg.UserID), streamMsg, "user", msg.UserID) default: - // Global broadcast — deliver to all local connections - conns := m.GetAllConnections() - for _, conn := range conns { - _ = m.deliverToConnection(ctx, conn, streamMsg) - } + m.fanOut(ctx, m.GetAllConnections(), streamMsg, "broadcast", "global") } } From 7caed41ffc142599932de752a521831dab8eeed7 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:21:49 -0600 Subject: [PATCH 09/17] fix(streaming): keep Redis calls out of the manager lock on connect and disconnect Register and Unregister held the manager's global write lock across the coordinator's TrackUserNode and UntrackUserNode (Redis SADD and SREM) and across the session store's Save, all with context.Background(). Every connect, disconnect, lookup and broadcast on the node waited behind each of those round trips, and a hung Redis stalled the node for good. The registry update still happens under the lock. The session snapshot is taken there too, and saved after the lock is released. Coordinator tracking also runs after unlocking, through syncUserNode, which re-reads the registry under a per-user striped lock and tracks or untracks to match it. Re-reading rather than acting on what the caller saw keeps a disconnect racing a reconnect from leaving a connected user untracked. Every call now has a 2 second timeout. Both calls still finish before Register or Unregister returns. --- .../streaming/coordinator_tracking_test.go | 162 ++++++++++++++++ extensions/streaming/manager.go | 177 ++++++++++++++---- 2 files changed, 300 insertions(+), 39 deletions(-) create mode 100644 extensions/streaming/coordinator_tracking_test.go diff --git a/extensions/streaming/coordinator_tracking_test.go b/extensions/streaming/coordinator_tracking_test.go new file mode 100644 index 000000000..be672b0b1 --- /dev/null +++ b/extensions/streaming/coordinator_tracking_test.go @@ -0,0 +1,162 @@ +package streaming + +import ( + "context" + "fmt" + "sync" + "testing" + "time" + + "github.com/xraph/forge/extensions/streaming/coordinator" +) + +// blockingTracker is a coordinator whose user tracking calls block until +// released, standing in for a slow Redis. +type blockingTracker struct { + coordinator.StreamCoordinator + + release chan struct{} + entered chan string + + mu sync.Mutex + tracked map[string]bool + sawCtx []bool // whether each call's context had a deadline +} + +func newBlockingTracker() *blockingTracker { + return &blockingTracker{ + release: make(chan struct{}), + entered: make(chan string, 16), + tracked: make(map[string]bool), + } +} + +func (b *blockingTracker) record(ctx context.Context, userID string, on bool) error { + b.entered <- userID + + <-b.release + + _, hasDeadline := ctx.Deadline() + + b.mu.Lock() + defer b.mu.Unlock() + + b.tracked[userID] = on + b.sawCtx = append(b.sawCtx, hasDeadline) + + return nil +} + +func (b *blockingTracker) BroadcastToRoom(context.Context, string, *Message) error { return nil } + +func (b *blockingTracker) TrackUserNode(ctx context.Context, userID, _ string) error { + return b.record(ctx, userID, true) +} + +func (b *blockingTracker) UntrackUserNode(ctx context.Context, userID, _ string) error { + return b.record(ctx, userID, false) +} + +// Register and Unregister held the manager's write lock across the +// coordinator's Redis SADD/SREM, with context.Background(). One slow round +// trip stalled every connect, disconnect and broadcast on the node. +func TestRegister_CoordinatorCallDoesNotHoldManagerLock(t *testing.T) { + tracker := newBlockingTracker() + m, _, _ := realManager(t, WithCoordinator(tracker), WithManagerNodeID("node-1")) + + slow := newTestConn("slow", "alice") + + registered := make(chan error, 1) + + go func() { registered <- m.Register(slow) }() + + select { + case <-tracker.entered: + case <-time.After(2 * time.Second): + t.Fatal("Register never reached the coordinator") + } + + // Alice's Register is now parked in the coordinator call. The rest of the + // node must carry on. + done := make(chan struct{}) + + go func() { + defer close(done) + + _ = m.ConnectionCount() + _ = m.GetAllConnections() + _ = m.BroadcastToRoom(context.Background(), "any", &Message{Type: MessageTypeMessage, RoomID: "any"}) + + if err := m.Register(newTestConn("anon", "")); err != nil { + t.Error(err) + } + }() + + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("manager blocked behind a pending coordinator call") + } + + close(tracker.release) + + if err := <-registered; err != nil { + t.Fatal(err) + } + + assertNoError(t, m.Unregister(slow.ID())) + + tracker.mu.Lock() + defer tracker.mu.Unlock() + + if tracker.tracked["alice"] { + t.Fatal("alice still tracked on this node after her last connection left") + } + + for i, hasDeadline := range tracker.sawCtx { + if !hasDeadline { + t.Errorf("coordinator call %d ran with no deadline", i) + } + } +} + +// With the calls outside the lock, connects and disconnects of one user race +// to the coordinator. Whatever the interleaving, the final record must match +// the registry. +func TestRegister_CoordinatorTrackingConvergesUnderRace(t *testing.T) { + tracker := newBlockingTracker() + close(tracker.release) + + m, _, _ := realManager(t, WithCoordinator(tracker), WithManagerNodeID("node-1")) + + go func() { + for range tracker.entered { + } + }() + + var wg sync.WaitGroup + + for i := range 50 { + wg.Go(func() { + c := newTestConn(fmt.Sprintf("c%d", i), "bob") + if err := m.Register(c); err != nil { + return // per-user limit; fine + } + + if i%3 != 0 { + _ = m.Unregister(c.ID()) + } + }) + } + + wg.Wait() + + connected := len(m.GetUserConnections("bob")) > 0 + + tracker.mu.Lock() + defer tracker.mu.Unlock() + + if tracker.tracked["bob"] != connected { + t.Fatalf("coordinator says tracked=%v, registry says connected=%v", tracker.tracked["bob"], connected) + } +} diff --git a/extensions/streaming/manager.go b/extensions/streaming/manager.go index 4bd831e90..4853b0a98 100644 --- a/extensions/streaming/manager.go +++ b/extensions/streaming/manager.go @@ -98,6 +98,14 @@ type manager struct { // the manager lock per message would serialise all delivery behind it. messagesSent atomic.Int64 + // userNodeLocks serialise the coordinator's per-user node tracking. The + // Redis calls run outside mu, so without these an Unregister that saw a + // user's last connection go could SREM after a concurrent Register had + // already SADDed for a new one, leaving a connected user untracked. + // Striped by user so unrelated users do not wait on each other's Redis + // round trips. + userNodeLocks [userNodeLockStripes]sync.Mutex + // Configuration config Config nodeID string @@ -240,7 +248,88 @@ func (m *manager) channelAuthorizer() streamauth.ChannelAuthorizer { // Connection management +// userNodeLockStripes is the number of locks userNodeLocks is striped over. +const userNodeLockStripes = 64 + +// coordinatorCallTimeout bounds one coordinator or session store call made on +// the connect and disconnect path. These used to run with +// context.Background() while holding the manager's write lock, so one slow +// Redis round trip stalled every connect, disconnect and broadcast on the +// node, and a hung one stalled them forever. +const coordinatorCallTimeout = 2 * time.Second + func (m *manager) Register(conn Connection) error { + if err := m.registerLocked(conn); err != nil { + return err + } + + // Outside the lock: a network round trip. + if userID := conn.GetUserID(); userID != "" { + m.syncUserNode(userID) + } + + return nil +} + +// syncUserNode brings the coordinator's record of whether userID is on this +// node in line with the registry, as it stands when the call runs. Reading +// the registry under the user's stripe lock, rather than passing in what the +// caller saw, is what keeps concurrent connects and disconnects of one user +// from leaving a stale answer behind. +func (m *manager) syncUserNode(userID string) { + if m.coordinator == nil || userID == "" || m.nodeID == "" { + return + } + + type userNodeTracker interface { + TrackUserNode(ctx context.Context, userID, nodeID string) error + UntrackUserNode(ctx context.Context, userID, nodeID string) error + } + + tracker, ok := m.coordinator.(userNodeTracker) + if !ok { + return + } + + lock := &m.userNodeLocks[stripeOf(userID)] + lock.Lock() + defer lock.Unlock() + + m.mu.RLock() + _, connected := m.userConns[userID] + m.mu.RUnlock() + + ctx, cancel := context.WithTimeout(context.Background(), coordinatorCallTimeout) + defer cancel() + + var err error + if connected { + err = tracker.TrackUserNode(ctx, userID, m.nodeID) + } else { + err = tracker.UntrackUserNode(ctx, userID, m.nodeID) + } + + if err != nil && m.logger != nil { + m.logger.Warn("coordinator user tracking failed", + forge.F("user_id", userID), + forge.F("connected", connected), + forge.F("error", err), + ) + } +} + +// stripeOf maps a user id to one of the userNodeLocks (FNV-1a). +func stripeOf(userID string) int { + h := uint32(2166136261) + for i := range len(userID) { + h ^= uint32(userID[i]) + h *= 16777619 + } + + return int(h % userNodeLockStripes) +} + +func (m *manager) registerLocked(conn Connection) error { m.mu.Lock() defer m.mu.Unlock() @@ -319,15 +408,6 @@ func (m *manager) Register(conn Connection) error { } } - // Track user on this node for coordinator - if m.coordinator != nil && userID != "" && m.nodeID != "" { - if tracker, ok := m.coordinator.(interface { - TrackUserNode(ctx context.Context, userID, nodeID string) error - }); ok { - _ = tracker.TrackUserNode(context.Background(), userID, m.nodeID) - } - } - // Track metrics if m.metrics != nil { m.metrics.Gauge("streaming.connections.active").Inc() @@ -345,40 +425,70 @@ func (m *manager) Register(conn Connection) error { } func (m *manager) Unregister(connID string) error { + userID, snapshot, err := m.unregisterLocked(connID) + if err != nil { + return err + } + + // Both of these can be network calls, so they run after the lock is + // released, each with a bounded context. They still complete before + // Unregister returns, so a reconnect that follows can resume the session. + if snapshot != nil { + m.saveSessionSnapshot(snapshot) + } + + if userID != "" { + m.syncUserNode(userID) + } + + return nil +} + +func (m *manager) saveSessionSnapshot(snapshot *SessionSnapshot) { + ctx, cancel := context.WithTimeout(context.Background(), coordinatorCallTimeout) + defer cancel() + + if err := m.sessionStore.Save(ctx, snapshot, m.config.SessionResumptionTTL); err != nil { + if m.logger != nil { + m.logger.Error("failed to save session snapshot", + forge.F("session_id", snapshot.SessionID), + forge.F("error", err), + ) + } + } else if m.logger != nil { + m.logger.Debug("session snapshot saved for resumption", + forge.F("session_id", snapshot.SessionID), + forge.F("ttl", m.config.SessionResumptionTTL), + ) + } +} + +// unregisterLocked removes the connection from the registry and indexes. It +// returns the user id and, when resumption is on, the session snapshot to +// save, both taken while the connection's state is still consistent. +func (m *manager) unregisterLocked(connID string) (string, *SessionSnapshot, error) { m.mu.Lock() defer m.mu.Unlock() conn, exists := m.connections[connID] if !exists { - return ErrConnectionNotFound + return "", nil, ErrConnectionNotFound } userID := conn.GetUserID() - // Save session snapshot for resumption before cleanup + // Snapshot for resumption before cleanup. + var snapshot *SessionSnapshot + if m.sessionStore != nil && m.config.EnableSessionResumption { - sessionID := conn.GetSessionID() - if sessionID != "" { - snapshot := &SessionSnapshot{ + if sessionID := conn.GetSessionID(); sessionID != "" { + snapshot = &SessionSnapshot{ SessionID: sessionID, UserID: userID, Rooms: conn.GetJoinedRooms(), Channels: conn.GetSubscriptions(), DisconnectedAt: time.Now(), } - if err := m.sessionStore.Save(context.Background(), snapshot, m.config.SessionResumptionTTL); err != nil { - if m.logger != nil { - m.logger.Error("failed to save session snapshot", - forge.F("session_id", sessionID), - forge.F("error", err), - ) - } - } else if m.logger != nil { - m.logger.Debug("session snapshot saved for resumption", - forge.F("session_id", sessionID), - forge.F("ttl", m.config.SessionResumptionTTL), - ) - } } } @@ -417,17 +527,6 @@ func (m *manager) Unregister(connID string) error { } } - // Untrack user from this node if no more connections - if m.coordinator != nil && userID != "" && m.nodeID != "" { - if _, stillHasConns := m.userConns[userID]; !stillHasConns { - if tracker, ok := m.coordinator.(interface { - UntrackUserNode(ctx context.Context, userID, nodeID string) error - }); ok { - _ = tracker.UntrackUserNode(context.Background(), userID, m.nodeID) - } - } - } - // Track metrics if m.metrics != nil { m.metrics.Gauge("streaming.connections.active").Dec() @@ -440,7 +539,7 @@ func (m *manager) Unregister(connID string) error { ) } - return nil + return userID, snapshot, nil } // ResumeSession restores room and channel state from a previous session. From 6fca864589b6fbee5e47e284f3f442fae051f35d Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:22:31 -0600 Subject: [PATCH 10/17] fix(streaming): rate limit anonymous connections ProcessInbound only consulted the rate limiter when the sender had a user id, so anonymous connections, the cheapest identity to get, were the only ones with no limit at all. Anonymous senders are now limited under a key derived from their connection id. Per connection rather than per remote address, because behind a proxy or a shared NAT every anonymous client has the same address and one noisy client would exhaust the budget for all of them. MaxAnonymousConnections already caps how many such connections exist. The retry guidance in rejection frames reads the same key. --- extensions/streaming/extension.go | 2 +- extensions/streaming/manager.go | 28 +++++++- extensions/streaming/manager_test.go | 4 +- .../streaming/ratelimit_anonymous_test.go | 64 +++++++++++++++++++ 4 files changed, 93 insertions(+), 5 deletions(-) create mode 100644 extensions/streaming/ratelimit_anonymous_test.go diff --git a/extensions/streaming/extension.go b/extensions/streaming/extension.go index bfffdcb04..01cb236ba 100644 --- a/extensions/streaming/extension.go +++ b/extensions/streaming/extension.go @@ -693,7 +693,7 @@ func (e *Extension) sendError(conn Connection, cause *Message, err error) { // Attach retry guidance when the rejection was a rate limit, so the client // backs off by the server's schedule rather than guessing at one. if errors.Is(err, ErrRateLimitExceeded) { - if status, sErr := e.manager.GetRateLimitStatus(context.Background(), conn.GetUserID()); sErr == nil { + if status, sErr := e.manager.GetRateLimitStatus(context.Background(), rateLimitKey(conn)); sErr == nil { if data, ok := frame.Data.(map[string]any); ok { data["retry_after_ms"] = status.RetryAfter.Milliseconds() data["reset_at"] = status.ResetAt diff --git a/extensions/streaming/manager.go b/extensions/streaming/manager.go index 4853b0a98..77dd576d0 100644 --- a/extensions/streaming/manager.go +++ b/extensions/streaming/manager.go @@ -1213,9 +1213,11 @@ func (m *manager) ProcessInbound(ctx context.Context, message *Message, sender C } } - // 2. Rate limiting. - if m.rateLimiter != nil && userID != "" { - allowed, err := m.rateLimiter.Allow(ctx, userID, "message") + // 2. Rate limiting. Anonymous connections are limited too, per + // connection. They used to skip the limiter entirely, which made the + // cheapest identity to obtain the only one with no rate limit. + if key := rateLimitKey(sender); m.rateLimiter != nil && key != "" { + allowed, err := m.rateLimiter.Allow(ctx, key, "message") if err != nil { // A limiter that cannot answer must not become an open door in one // direction or a hard outage in the other. Log and allow: the @@ -1256,6 +1258,26 @@ func (m *manager) ProcessInbound(ctx context.Context, message *Message, sender C return message, nil } +// rateLimitKey is the identity a connection's inbound messages are rate +// limited under: the user for an authenticated connection, so a user's +// sockets share one budget, and the connection itself for an anonymous one. +// +// Per connection rather than per remote address on purpose. Behind a proxy or +// a shared NAT every anonymous client has the same address, and one noisy +// client would use up the budget for all of them. The number of anonymous +// connections is capped separately by MaxAnonymousConnections. +func rateLimitKey(conn Connection) string { + if conn == nil { + return "" + } + + if userID := conn.GetUserID(); userID != "" { + return userID + } + + return "anon:conn:" + conn.ID() +} + // authorizeSend checks that the sender may publish to the target the message // names. func (m *manager) authorizeSend(ctx context.Context, message *Message, sender Connection, userID string) error { diff --git a/extensions/streaming/manager_test.go b/extensions/streaming/manager_test.go index 02edef9fa..defaaa2b6 100644 --- a/extensions/streaming/manager_test.go +++ b/extensions/streaming/manager_test.go @@ -1281,9 +1281,11 @@ func TestManager_ProcessMessage(t *testing.T) { sender: newTestConn("c1", "u1"), }, { - name: "rate limiter is skipped for anonymous senders", + // Anonymous senders used to skip the limiter entirely. + name: "rate limiter applies to anonymous senders", rateLimiter: &stubRateLimiter{allow: false}, sender: newTestConn("c1", ""), + wantErr: true, }, { name: "validator rejects", diff --git a/extensions/streaming/ratelimit_anonymous_test.go b/extensions/streaming/ratelimit_anonymous_test.go new file mode 100644 index 000000000..dd37f33c7 --- /dev/null +++ b/extensions/streaming/ratelimit_anonymous_test.go @@ -0,0 +1,64 @@ +package streaming + +import ( + "context" + "errors" + "testing" + + "github.com/xraph/forge/extensions/streaming/ratelimit" +) + +// sendUntilLimited sends system frames until the limiter refuses one and +// returns how many got through, or -1 if none was refused. +func sendUntilLimited(m Manager, conn Connection, limit int) int { + for i := range limit { + _, err := m.ProcessInbound(context.Background(), &Message{Type: MessageTypeSystem, Data: "x"}, conn) + if errors.Is(err, ErrRateLimitExceeded) { + return i + } + } + + return -1 +} + +// ProcessInbound skipped the rate limiter whenever the sender had no user id, +// so an anonymous socket could send without limit. +func TestProcessInbound_RateLimitsAnonymousConnections(t *testing.T) { + rl := ratelimit.NewTokenBucket(ratelimit.DefaultRateLimitConfig(), nil) + m, _, _ := realManager(t, WithRateLimiter(rl)) + + first := newTestConn("anon-1", "") + second := newTestConn("anon-2", "") + + for _, c := range []*testConn{first, second} { + assertNoError(t, m.Register(c)) + } + + if n := sendUntilLimited(m, first, 1000); n < 0 { + t.Fatal("anonymous connection sent 1000 messages without being rate limited") + } + + // The budget is per connection: one noisy anonymous client does not use + // up another's, as it would if every client behind one proxy shared an + // address-based bucket. + if n := sendUntilLimited(m, second, 1); n == 0 { + t.Fatal("a second anonymous connection inherited the first one's exhausted budget") + } +} + +func TestRateLimitKey(t *testing.T) { + user := newTestConn("c1", "alice") + anon := newTestConn("c2", "") + + if got := rateLimitKey(user); got != "alice" { + t.Errorf("authenticated key = %q, want the user id", got) + } + + if got := rateLimitKey(anon); got != "anon:conn:c2" { + t.Errorf("anonymous key = %q, want one derived from the connection id", got) + } + + if got := rateLimitKey(nil); got != "" { + t.Errorf("nil sender key = %q, want empty", got) + } +} From a82c138304c9a3b0427fa0cc1b4697156fa65ba0 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:23:40 -0600 Subject: [PATCH 11/17] fix(streaming): mark users offline only when their last connection closes handleSSE marked the user offline on every disconnect, so closing one of two tabs showed a user with an open tab as offline. It also wrote with the request context, which is already cancelled by the time the deferred call runs, so a Redis presence store would reject the write. While porting the WebSocket handler's rule to SSE, its version turned out to be broken the other way. Its offline check is deferred after the Unregister call, so it runs first, always counted the closing connection itself and never marked anyone offline. Both handlers now share markOfflineIfLast, which ignores the closing connection explicitly, so it does not depend on defer order, and writes with a context detached from the request and bounded to 5 seconds. --- extensions/streaming/extension.go | 62 +++-- .../streaming/presence_disconnect_test.go | 217 ++++++++++++++++++ 2 files changed, 255 insertions(+), 24 deletions(-) create mode 100644 extensions/streaming/presence_disconnect_test.go diff --git a/extensions/streaming/extension.go b/extensions/streaming/extension.go index 01cb236ba..e52391b36 100644 --- a/extensions/streaming/extension.go +++ b/extensions/streaming/extension.go @@ -528,21 +528,7 @@ func (e *Extension) handleWebSocket(ctx forge.Context, conn forge.Connection) er if userID != "" && e.config.EnablePresence { _ = e.manager.SetPresence(ctx.Request().Context(), userID, StatusOnline) - defer func() { - // Detached from the request context on purpose: by the time this - // runs the request context is cancelled, so a presence write to a - // Redis backend would fail with "context canceled" and the user - // would be stuck online forever. - presenceCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx.Request().Context()), 5*time.Second) - defer cancel() - - // Unregister has already run (deferred later, so it fires first), - // meaning this connection is out of the registry and any remaining - // entries are genuinely other live sockets. - if len(e.manager.GetUserConnections(userID)) == 0 { - _ = e.manager.SetPresence(presenceCtx, userID, StatusOffline) - } - }() + defer e.markOfflineIfLast(ctx.Request().Context(), userID, conn.ID()) } // Heartbeat, scoped to the connection's lifetime. @@ -667,6 +653,36 @@ func (e *Extension) handleWebSocket(ctx forge.Context, conn forge.Connection) er } } +// markOfflineIfLast marks userID offline unless the user still has a live +// connection other than connID. +// +// connID is excluded explicitly rather than relying on Unregister having run +// first. Deferred calls run last-in first-out, and this one is deferred after +// the unregistration, so it runs before it: counting every registered +// connection always found this one and the user never went offline. +// +// The context is detached from the request on purpose. By the time this runs +// the request context is cancelled, so a presence write to a Redis backend +// would fail with "context canceled" and leave the user online forever. It is +// still bounded, so a slow backend cannot hold the handler open. +func (e *Extension) markOfflineIfLast(reqCtx context.Context, userID, connID string) { + for _, c := range e.manager.GetUserConnections(userID) { + if c.ID() != connID && !c.IsClosed() { + return + } + } + + ctx, cancel := context.WithTimeout(context.WithoutCancel(reqCtx), 5*time.Second) + defer cancel() + + if err := e.manager.SetPresence(ctx, userID, StatusOffline); err != nil { + e.Logger().Warn("failed to mark user offline", + forge.F("user_id", userID), + forge.F("error", err), + ) + } +} + // sendError reports a rejected message back to its sender. // // A rejection the client cannot see is a rejection the client cannot respond @@ -933,17 +949,15 @@ func (e *Extension) handleSSE(ctx forge.Context, stream forge.Stream) error { } } - // Set user online + // Set user online, and offline again only when this was the user's last + // connection, the same rule the WebSocket handler follows. The SSE handler + // used to mark the user offline on every disconnect, so closing one tab + // made a user with another tab open appear offline, and it did so with the + // request context, which is already cancelled by then. if userID != "" && e.config.EnablePresence { _ = e.manager.SetPresence(ctx.Request().Context(), userID, StatusOnline) - defer func() { - if err := e.manager.SetPresence(ctx.Request().Context(), userID, StatusOffline); err != nil { - e.Logger().Warn("failed to mark SSE user offline", - forge.F("user_id", userID), - forge.F("error", err), - ) - } - }() + + defer e.markOfflineIfLast(ctx.Request().Context(), userID, sseConn.ID()) } e.Logger().Debug("SSE connection established", diff --git a/extensions/streaming/presence_disconnect_test.go b/extensions/streaming/presence_disconnect_test.go new file mode 100644 index 000000000..cd5aa53cb --- /dev/null +++ b/extensions/streaming/presence_disconnect_test.go @@ -0,0 +1,217 @@ +package streaming + +import ( + "bufio" + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gobwas/ws" + "github.com/xraph/forge" +) + +// newPresenceServer serves the real handlers, with a stand-in auth middleware +// that takes the user id from ?uid=. +func newPresenceServer(t *testing.T) (*Extension, *httptest.Server) { + t.Helper() + + app := forge.NewApp(forge.AppConfig{Name: "presence"}) + ext := NewExtension(WithLocalBackend()) + + if err := ext.Register(app); err != nil { + t.Fatal(err) + } + + app.Router().Use(func(next forge.Handler) forge.Handler { + return func(ctx forge.Context) error { + if uid := ctx.Request().URL.Query().Get("uid"); uid != "" { + ctx.Set("user_id", uid) + } + + return next(ctx) + } + }) + + if err := ext.RegisterRoutes(app.Router(), "/ws", "/sse"); err != nil { + t.Fatal(err) + } + + srv := httptest.NewServer(app.Router().(http.Handler)) + t.Cleanup(srv.Close) + + return ext, srv +} + +func presenceOf(t *testing.T, ext *Extension, userID string) string { + t.Helper() + + p, err := ext.Manager().GetPresence(context.Background(), userID) + if err != nil || p == nil { + return "" + } + + return p.Status +} + +// waitPresence polls until the user's presence is want, or fails. +func waitPresence(t *testing.T, ext *Extension, userID, want string) { + t.Helper() + + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if presenceOf(t, ext, userID) == want { + return + } + + time.Sleep(10 * time.Millisecond) + } + + t.Fatalf("presence of %s = %q, want %q", userID, presenceOf(t, ext, userID), want) +} + +// waitConns polls until the user has n registered connections. +func waitConns(t *testing.T, ext *Extension, userID string, n int) { + t.Helper() + + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if len(ext.Manager().GetUserConnections(userID)) == n { + return + } + + time.Sleep(5 * time.Millisecond) + } + + t.Fatalf("%s has %d connections, want %d", userID, len(ext.Manager().GetUserConnections(userID)), n) +} + +// assertStaysOnline checks presence does not flip to offline for a while. +func assertStaysOnline(t *testing.T, ext *Extension, userID string) { + t.Helper() + + deadline := time.Now().Add(200 * time.Millisecond) + for time.Now().Before(deadline) { + if got := presenceOf(t, ext, userID); got != StatusOnline { + t.Fatalf("presence of %s = %q while another connection is open, want online", userID, got) + } + + time.Sleep(10 * time.Millisecond) + } +} + +// openSSE connects an SSE client and returns a function that disconnects it. +func openSSE(t *testing.T, srv *httptest.Server, uid string) func() { + t.Helper() + + ctx, cancel := context.WithCancel(context.Background()) + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/sse?uid="+uid, nil) + if err != nil { + t.Fatal(err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + + sc := bufio.NewScanner(resp.Body) + for sc.Scan() { + if strings.HasPrefix(sc.Text(), "event: connected") { + break + } + } + + closed := false + + stop := func() { + if !closed { + closed = true + + cancel() + + _ = resp.Body.Close() + } + } + + t.Cleanup(stop) + + return stop +} + +func openWS(t *testing.T, srv *httptest.Server, uid string) func() { + t.Helper() + + c, _, _, err := ws.Dial(context.Background(), "ws"+strings.TrimPrefix(srv.URL, "http")+"/ws?uid="+uid) + if err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = c.Close() }) + + return func() { _ = c.Close() } +} + +// The SSE handler marked the user offline on every disconnect, so closing one +// of two tabs showed the user offline, and it wrote with the request context, +// which is already cancelled at that point. +func TestHandleSSE_PresenceOfflineOnlyAfterLastConnection(t *testing.T) { + ext, srv := newPresenceServer(t) + + closeFirst := openSSE(t, srv, "alice") + closeSecond := openSSE(t, srv, "alice") + + waitConns(t, ext, "alice", 2) + waitPresence(t, ext, "alice", StatusOnline) + + closeFirst() + waitConns(t, ext, "alice", 1) + assertStaysOnline(t, ext, "alice") + + closeSecond() + waitConns(t, ext, "alice", 0) + waitPresence(t, ext, "alice", StatusOffline) +} + +// The WebSocket handler had the opposite bug. Its offline check ran before +// Unregister (deferred calls run last in, first out), so it always counted +// the closing connection itself and never marked anyone offline. +func TestHandleWebSocket_PresenceOfflineOnlyAfterLastConnection(t *testing.T) { + ext, srv := newPresenceServer(t) + + closeFirst := openWS(t, srv, "bob") + closeSecond := openWS(t, srv, "bob") + + waitConns(t, ext, "bob", 2) + waitPresence(t, ext, "bob", StatusOnline) + + closeFirst() + waitConns(t, ext, "bob", 1) + assertStaysOnline(t, ext, "bob") + + closeSecond() + waitConns(t, ext, "bob", 0) + waitPresence(t, ext, "bob", StatusOffline) +} + +// Mixed transports count together: closing the SSE stream must not mark a +// user offline who still has a WebSocket open. +func TestPresence_MixedTransportsCountTogether(t *testing.T) { + ext, srv := newPresenceServer(t) + + closeWS := openWS(t, srv, "carol") + closeSSE := openSSE(t, srv, "carol") + + waitConns(t, ext, "carol", 2) + + closeSSE() + waitConns(t, ext, "carol", 1) + assertStaysOnline(t, ext, "carol") + + closeWS() + waitConns(t, ext, "carol", 0) + waitPresence(t, ext, "carol", StatusOffline) +} From a5d299a6115b045e198b34abb53c57c0eff2926a Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:38:59 -0600 Subject: [PATCH 12/17] fix(streaming): make room bans work on the local backend LocalRoom's BanMember, UnbanMember, IsBanned and GetBannedMembers returned ErrInvalidRoom unconditionally, because bans live in the RoomStore and the room had no way to reach it. Manager.BanUser and UnbanUser call those methods, so nobody could be banned or unbanned on the local backend. The send-path ban check also asked the room, got the error, and read it as "not banned", so it never fired on any backend. The Redis backend had the same room methods, and its store had problems of its own: BanMember recorded the ban but left the user a member, and IsBanned and GetBans ignored ExpiresAt, so a temporary ban never ended. Now: - A LocalRoom keeps a reference to the store it was created in and its ban methods delegate to it. A room that was never stored still returns ErrInvalidRoom. The Redis room delegates to its store the same way. - The Redis store removes the membership in the same transaction as the ban, skips expired bans in GetBans, and treats an expired ban as absent in IsBanned, deleting it on the way past. - BanUser and UnbanUser go through the room store. BanUser removes the membership, takes the user's connections on this node out of the room, and sends each one a "room.banned" system frame. - JoinRoom refuses a banned user on every path, not only client join frames. - The send check reads bans from the store. It therefore also refuses a connection that is still in the room locally because the ban was made on another node. Tests cover both stores, the manager, and a real WebSocket client being banned, refused on send and rejoin, and let back in after an unban. --- .../backends/local/room_bans_test.go | 65 +++++ .../streaming/backends/local/room_store.go | 54 +++- .../backends/redis/room_bans_test.go | 87 ++++++ .../streaming/backends/redis/room_store.go | 65 ++++- extensions/streaming/manager.go | 95 +++++-- extensions/streaming/room_bans_test.go | 247 ++++++++++++++++++ extensions/streaming/testing_test.go | 37 +++ 7 files changed, 622 insertions(+), 28 deletions(-) create mode 100644 extensions/streaming/backends/local/room_bans_test.go create mode 100644 extensions/streaming/backends/redis/room_bans_test.go create mode 100644 extensions/streaming/room_bans_test.go diff --git a/extensions/streaming/backends/local/room_bans_test.go b/extensions/streaming/backends/local/room_bans_test.go new file mode 100644 index 000000000..f9fa66320 --- /dev/null +++ b/extensions/streaming/backends/local/room_bans_test.go @@ -0,0 +1,65 @@ +package local + +import ( + "context" + "errors" + "testing" + "time" + + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// LocalRoom's ban methods returned ErrInvalidRoom unconditionally, so +// Manager.BanUser, which calls them, failed for every local room. +func TestLocalRoom_BanMethodsUseTheStore(t *testing.T) { + ctx := context.Background() + s := NewRoomStore() + room := NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}) + + // Before it is stored a room has nowhere to keep bans. + if err := room.BanMember(ctx, "alice", "", nil); !errors.Is(err, streaming.ErrInvalidRoom) { + t.Fatalf("BanMember on an unstored room = %v, want ErrInvalidRoom", err) + } + + if err := s.Create(ctx, room); err != nil { + t.Fatal(err) + } + + if err := s.AddMember(ctx, "lobby", NewLocalMember(streaming.MemberOptions{UserID: "alice", Role: streaming.RoleMember})); err != nil { + t.Fatal(err) + } + + if err := room.BanMember(ctx, "alice", "spam", nil); err != nil { + t.Fatalf("BanMember: %v", err) + } + + if member, _ := s.IsMember(ctx, "lobby", "alice"); member { + t.Error("alice is still a member after being banned") + } + + if banned, err := room.IsBanned(ctx, "alice"); err != nil || !banned { + t.Errorf("IsBanned = %v, %v; want true", banned, err) + } + + bans, err := room.GetBannedMembers(ctx) + if err != nil || len(bans) != 1 || bans[0].Reason != "spam" { + t.Errorf("GetBannedMembers = %+v, %v", bans, err) + } + + if err := room.UnbanMember(ctx, "alice"); err != nil { + t.Fatal(err) + } + + if banned, _ := room.IsBanned(ctx, "alice"); banned { + t.Error("alice still banned after UnbanMember") + } + + past := time.Now().Add(-time.Second) + if err := room.BanMember(ctx, "bob", "", &past); err != nil { + t.Fatal(err) + } + + if banned, _ := room.IsBanned(ctx, "bob"); banned { + t.Error("expired ban still reported") + } +} diff --git a/extensions/streaming/backends/local/room_store.go b/extensions/streaming/backends/local/room_store.go index 95b4f79dc..24d80d7b0 100644 --- a/extensions/streaming/backends/local/room_store.go +++ b/extensions/streaming/backends/local/room_store.go @@ -64,6 +64,10 @@ func (s *RoomStore) Create(ctx context.Context, room streaming.Room) error { localRoom.isArchived = room.IsArchived() } + localRoom.mu.Lock() + localRoom.store = s + localRoom.mu.Unlock() + s.rooms[localRoom.id] = localRoom s.members[localRoom.id] = make(map[string]*LocalMember) s.bans[localRoom.id] = make(map[string]*streaming.RoomBan) @@ -772,6 +776,11 @@ type LocalRoom struct { category string readMarkers map[string]string // userID -> messageID mutedMembers map[string]time.Time // userID -> unmute time + + // store is the RoomStore this room was created in, set by Create. Bans + // live in the store, so the room's ban methods delegate to it. A room + // that was never stored has none and keeps refusing them. + store *RoomStore } // NewRoom builds a LocalRoom from the given options. @@ -928,20 +937,57 @@ func (r *LocalRoom) TransferOwnership(ctx context.Context, newOwnerID string) er return nil } +// roomStore returns the store this room belongs to, or nil. +func (r *LocalRoom) roomStore() *RoomStore { + r.mu.RLock() + defer r.mu.RUnlock() + + return r.store +} + +// BanMember bans userID through the room's store. These methods used to +// return ErrInvalidRoom unconditionally, so Manager.BanUser, which calls them, +// failed on every local room and nobody could be banned. func (r *LocalRoom) BanMember(ctx context.Context, userID string, reason string, until *time.Time) error { - return streaming.ErrInvalidRoom // Managed by RoomStore + s := r.roomStore() + if s == nil { + return streaming.ErrInvalidRoom + } + + return s.BanMember(ctx, r.GetID(), userID, streaming.RoomBan{ + UserID: userID, + RoomID: r.GetID(), + Reason: reason, + BannedAt: time.Now(), + ExpiresAt: until, + }) } func (r *LocalRoom) UnbanMember(ctx context.Context, userID string) error { - return streaming.ErrInvalidRoom // Managed by RoomStore + s := r.roomStore() + if s == nil { + return streaming.ErrInvalidRoom + } + + return s.UnbanMember(ctx, r.GetID(), userID) } func (r *LocalRoom) IsBanned(ctx context.Context, userID string) (bool, error) { - return false, streaming.ErrInvalidRoom // Managed by RoomStore + s := r.roomStore() + if s == nil { + return false, streaming.ErrInvalidRoom + } + + return s.IsBanned(ctx, r.GetID(), userID) } func (r *LocalRoom) GetBannedMembers(ctx context.Context) ([]streaming.RoomBan, error) { - return nil, streaming.ErrInvalidRoom // Managed by RoomStore + s := r.roomStore() + if s == nil { + return nil, streaming.ErrInvalidRoom + } + + return s.GetBans(ctx, r.GetID()) } func (r *LocalRoom) MuteMember(ctx context.Context, userID string, duration time.Duration) error { diff --git a/extensions/streaming/backends/redis/room_bans_test.go b/extensions/streaming/backends/redis/room_bans_test.go new file mode 100644 index 000000000..6f4d76dcc --- /dev/null +++ b/extensions/streaming/backends/redis/room_bans_test.go @@ -0,0 +1,87 @@ +package redis + +import ( + "context" + "testing" + "time" + + "github.com/xraph/forge/extensions/streaming/backends/local" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// The Redis backend recorded a ban but left the user a member, ignored +// ExpiresAt so a temporary ban never ran out, and its Room's ban methods +// returned ErrInvalidRoom. +func TestRoomStore_Bans(t *testing.T) { + ctx := context.Background() + s := NewRoomStore(newTestClient(t), "test:rooms") + + if err := s.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"})); err != nil { + t.Fatal(err) + } + + for _, uid := range []string{"alice", "bob"} { + if err := s.AddMember(ctx, "lobby", local.NewLocalMember(streaming.MemberOptions{UserID: uid, Role: streaming.RoleMember})); err != nil { + t.Fatal(err) + } + } + + if err := s.BanMember(ctx, "lobby", "alice", streaming.RoomBan{UserID: "alice", RoomID: "lobby", BannedAt: time.Now()}); err != nil { + t.Fatal(err) + } + + if member, _ := s.IsMember(ctx, "lobby", "alice"); member { + t.Error("alice is still a member after being banned") + } + + if banned, err := s.IsBanned(ctx, "lobby", "alice"); err != nil || !banned { + t.Errorf("IsBanned(alice) = %v, %v; want true", banned, err) + } + + // An expired ban is no ban: not reported, not listed. + past := time.Now().Add(-time.Minute) + if err := s.BanMember(ctx, "lobby", "bob", streaming.RoomBan{UserID: "bob", RoomID: "lobby", ExpiresAt: &past}); err != nil { + t.Fatal(err) + } + + if banned, _ := s.IsBanned(ctx, "lobby", "bob"); banned { + t.Error("expired ban on bob still reported") + } + + bans, err := s.GetBans(ctx, "lobby") + if err != nil { + t.Fatal(err) + } + + if len(bans) != 1 || bans[0].UserID != "alice" { + t.Errorf("GetBans = %+v, want only alice", bans) + } + + // The Room object answers through the store. + room, err := s.Get(ctx, "lobby") + if err != nil { + t.Fatal(err) + } + + if banned, err := room.IsBanned(ctx, "alice"); err != nil || !banned { + t.Errorf("room.IsBanned(alice) = %v, %v; want true", banned, err) + } + + until := time.Now().Add(time.Hour) + if err := room.BanMember(ctx, "carol", "spam", &until); err != nil { + t.Fatalf("room.BanMember: %v", err) + } + + if err := room.UnbanMember(ctx, "alice"); err != nil { + t.Fatalf("room.UnbanMember: %v", err) + } + + listed, err := room.GetBannedMembers(ctx) + if err != nil { + t.Fatal(err) + } + + if len(listed) != 1 || listed[0].UserID != "carol" || listed[0].Reason != "spam" { + t.Errorf("GetBannedMembers = %+v, want only carol", listed) + } +} diff --git a/extensions/streaming/backends/redis/room_store.go b/extensions/streaming/backends/redis/room_store.go index 85657ff81..4c2f46ee7 100644 --- a/extensions/streaming/backends/redis/room_store.go +++ b/extensions/streaming/backends/redis/room_store.go @@ -530,16 +530,24 @@ func (s *RoomStore) GetTotalMembers(ctx context.Context) (int, error) { return total, nil } -// BanMember bans a member from a room. +// BanMember bans a member from a room and removes their membership, as the +// local backend does. It used to record the ban and leave the user a member. func (s *RoomStore) BanMember(ctx context.Context, roomID, userID string, ban streaming.RoomBan) error { bansKey := fmt.Sprintf("%s:%s:bans", s.prefix, roomID) + membersKey := fmt.Sprintf("%s:%s:members", s.prefix, roomID) banData, err := json.Marshal(ban) if err != nil { return err } - return s.client.HSet(ctx, bansKey, userID, banData).Err() + pipe := s.client.TxPipeline() + pipe.HSet(ctx, bansKey, userID, banData) + pipe.HDel(ctx, membersKey, userID) + + _, err = pipe.Exec(ctx) + + return err } // UnbanMember removes a ban from a member. @@ -558,6 +566,8 @@ func (s *RoomStore) GetBans(ctx context.Context, roomID string) ([]streaming.Roo return nil, err } + now := time.Now() + bans := make([]streaming.RoomBan, 0, len(bansData)) for _, banJSON := range bansData { var ban streaming.RoomBan @@ -565,6 +575,11 @@ func (s *RoomStore) GetBans(ctx context.Context, roomID string) ([]streaming.Roo continue } + // Expired bans are not bans. The local backend filters them the same way. + if ban.ExpiresAt != nil && !ban.ExpiresAt.After(now) { + continue + } + bans = append(bans, ban) } @@ -575,12 +590,36 @@ func (s *RoomStore) GetBans(ctx context.Context, roomID string) ([]streaming.Roo return bans, nil } -// IsBanned checks if a user is banned from a room. +// IsBanned checks if a user is currently banned from a room. +// +// It honours RoomBan.ExpiresAt. It used to answer from HExists alone, so a +// temporary ban never ran out. An expired entry is deleted on the way past, +// which a read can safely do here since Redis serialises the HDel. func (s *RoomStore) IsBanned(ctx context.Context, roomID, userID string) (bool, error) { bansKey := fmt.Sprintf("%s:%s:bans", s.prefix, roomID) - exists, err := s.client.HExists(ctx, bansKey, userID).Result() - return exists, err + data, err := s.client.HGet(ctx, bansKey, userID).Result() + if errors.Is(err, redis.Nil) { + return false, nil + } + + if err != nil { + return false, err + } + + var ban streaming.RoomBan + if err := json.Unmarshal([]byte(data), &ban); err != nil { + // Unreadable, but a ban was recorded: err on the side of the ban. + return true, nil //nolint:nilerr // a corrupt ban entry still counts as a ban + } + + if ban.ExpiresAt != nil && !ban.ExpiresAt.After(time.Now()) { + _ = s.client.HDel(ctx, bansKey, userID).Err() + + return false, nil + } + + return true, nil } // SaveInvite saves an invite for a room. @@ -751,20 +790,28 @@ func (r *redisRoom) TransferOwnership(ctx context.Context, newOwnerID string) er return streaming.ErrInvalidRoom } +// BanMember bans userID through the room's store. Like the local backend, +// these used to return ErrInvalidRoom, so Manager.BanUser always failed. func (r *redisRoom) BanMember(ctx context.Context, userID string, reason string, until *time.Time) error { - return streaming.ErrInvalidRoom + return r.store.BanMember(ctx, r.id, userID, streaming.RoomBan{ + UserID: userID, + RoomID: r.id, + Reason: reason, + BannedAt: time.Now(), + ExpiresAt: until, + }) } func (r *redisRoom) UnbanMember(ctx context.Context, userID string) error { - return streaming.ErrInvalidRoom + return r.store.UnbanMember(ctx, r.id, userID) } func (r *redisRoom) IsBanned(ctx context.Context, userID string) (bool, error) { - return false, streaming.ErrInvalidRoom + return r.store.IsBanned(ctx, r.id, userID) } func (r *redisRoom) GetBannedMembers(ctx context.Context) ([]streaming.RoomBan, error) { - return nil, streaming.ErrInvalidRoom + return r.store.GetBans(ctx, r.id) } func (r *redisRoom) MuteMember(ctx context.Context, userID string, duration time.Duration) error { diff --git a/extensions/streaming/manager.go b/extensions/streaming/manager.go index 77dd576d0..4f8ced633 100644 --- a/extensions/streaming/manager.go +++ b/extensions/streaming/manager.go @@ -776,6 +776,17 @@ func (m *manager) JoinRoom(ctx context.Context, connID, roomID string) error { } } + // A banned user may not rejoin, whichever path the join came by: a client + // frame, ?rooms= on an SSE connection, the subscribe endpoint or a + // resumed session. The default room authorizer does not look at bans. + if banned, bErr := m.roomStore.IsBanned(ctx, roomID, userID); bErr == nil && banned { + if m.metrics != nil { + m.metrics.Counter("streaming.rooms.joins_denied").Inc() + } + + return ErrUserBanned + } + // Check room limit. Counts store membership, which is only meaningful // because the store write below actually happens. userRooms, _ := m.roomStore.GetUserRooms(ctx, userID) @@ -1326,16 +1337,19 @@ func (m *manager) authorizeSend(ctx context.Context, message *Message, sender Co } } - // Moderation state, which the room already tracks and nothing consulted. + // Moderation state. Bans are read from the store, not the Room: the + // local Room's IsBanned only ever returned an error, which this check + // read as "not banned", and a store read also sees a ban made on + // another node for a connection that is still in the room here. if userID != "" { + if banned, bErr := m.roomStore.IsBanned(ctx, message.RoomID, userID); bErr == nil && banned { + return ErrUserBanned + } + if room, err := m.roomStore.Get(ctx, message.RoomID); err == nil { if muted, mErr := room.IsMuted(ctx, userID); mErr == nil && muted { return ErrUserMuted } - - if banned, bErr := room.IsBanned(ctx, userID); bErr == nil && banned { - return ErrUserBanned - } } } @@ -3096,18 +3110,40 @@ func (m *manager) UnmuteUser(ctx context.Context, userID, roomID string) error { return nil } +// BanUser bans a user from a room, removes their membership, and takes every +// connection of theirs on this node out of the room. +// +// It goes through the room store rather than the Room object. The local +// backend's Room returned ErrInvalidRoom from every ban method, so this failed +// on every local room. It also used to leave the user's live connections in +// the room, still receiving its traffic. func (m *manager) BanUser(ctx context.Context, userID, roomID string, reason string, until *time.Time) error { - // Get the room to access moderation methods - room, err := m.GetRoom(ctx, roomID) - if err != nil { + if _, err := m.GetRoom(ctx, roomID); err != nil { return err } - // Use the room's ban functionality - if err := room.BanMember(ctx, userID, reason, until); err != nil { + ban := streaming.RoomBan{ + UserID: userID, + RoomID: roomID, + Reason: reason, + BannedAt: time.Now(), + ExpiresAt: until, + } + + if err := m.roomStore.BanMember(ctx, roomID, userID, ban); err != nil { return err } + // The bundled stores drop the membership as part of the ban. A custom + // store may not, and a banned user must not stay a member. + if err := m.roomStore.RemoveMember(ctx, roomID, userID); err != nil && + !errors.Is(err, streaming.ErrNotRoomMember) && + !errors.Is(err, streaming.ErrRoomNotFound) { + return fmt.Errorf("failed to remove banned member: %w", err) + } + + m.evictFromRoom(ctx, userID, roomID, reason) + if m.logger != nil { m.logger.Info("user banned", forge.F("user_id", userID), @@ -3120,15 +3156,44 @@ func (m *manager) BanUser(ctx context.Context, userID, roomID string, reason str return nil } +// evictFromRoom takes the user's connections on this node out of a room and +// tells each one why. Connections on other nodes keep their local membership +// until they reconnect, but the ban check in authorizeSend refuses their +// sends, since it asks the shared store. +func (m *manager) evictFromRoom(ctx context.Context, userID, roomID, reason string) { + for _, conn := range m.GetUserConnections(userID) { + if !conn.IsInRoom(roomID) { + continue + } + + conn.RemoveRoom(roomID) + m.indexRoomLeave(roomID, conn.ID()) + + notice := NewLifecycleMessage(streaming.MessageTypeSystem, "room.banned") + notice.ID = fmt.Sprintf("ban_%d", time.Now().UnixNano()) + notice.UserID = "system" + notice.RoomID = roomID + notice.Data = map[string]any{"reason": reason} + + if err := conn.WriteJSON(notice); err != nil && m.logger != nil { + m.logger.Debug("failed to send ban notice", + forge.F("conn_id", conn.ID()), + forge.F("error", err), + ) + } + + if m.hooks != nil { + m.hooks.FireOnRoomLeave(ctx, conn, roomID) + } + } +} + func (m *manager) UnbanUser(ctx context.Context, userID, roomID string) error { - // Get the room to access moderation methods - room, err := m.GetRoom(ctx, roomID) - if err != nil { + if _, err := m.GetRoom(ctx, roomID); err != nil { return err } - // Use the room's unban functionality - if err := room.UnbanMember(ctx, userID); err != nil { + if err := m.roomStore.UnbanMember(ctx, roomID, userID); err != nil { return err } diff --git a/extensions/streaming/room_bans_test.go b/extensions/streaming/room_bans_test.go new file mode 100644 index 000000000..9ba99ae9a --- /dev/null +++ b/extensions/streaming/room_bans_test.go @@ -0,0 +1,247 @@ +package streaming + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsutil" + "github.com/xraph/forge/extensions/streaming/backends/local" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +func lifecycleOf(msg *Message) string { + if msg == nil || msg.Metadata == nil { + return "" + } + + s, _ := msg.Metadata[LifecycleMetadataKey].(string) + + return s +} + +// BanUser failed on every local room, because it went through the local +// Room's ban methods, which only returned ErrInvalidRoom. A ban must now drop +// the membership, take the user's live connections out of the room, keep them +// out, and refuse their sends. +func TestBanUser_RemovesEvictsAndKeepsOut(t *testing.T) { + m, rooms, _ := realManager(t) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + tab1 := newTestConn("a1", "alice") + tab2 := newTestConn("a2", "alice") + bob := newTestConn("b1", "bob") + + for _, c := range []*testConn{tab1, tab2, bob} { + assertNoError(t, m.Register(c)) + assertNoError(t, m.JoinRoom(ctx, c.ID(), "lobby")) + } + + assertNoError(t, m.BanUser(ctx, "alice", "lobby", "spam", nil)) + + if member, _ := rooms.IsMember(ctx, "lobby", "alice"); member { + t.Error("alice is still a room member after the ban") + } + + for _, c := range []*testConn{tab1, tab2} { + if c.IsInRoom("lobby") { + t.Errorf("%s still in the room after the ban", c.ID()) + } + + c.waitQuiet(t) + + if got := lifecycleOf(c.rec.lastJSON(t)); got != "room.banned" { + t.Errorf("%s: last frame lifecycle = %q, want room.banned", c.ID(), got) + } + } + + before := tab1.rec.totalWrites() + + assertNoError(t, m.BroadcastToRoom(ctx, "lobby", &Message{ID: "m", Type: MessageTypeMessage, RoomID: "lobby", Data: "hi"})) + tab1.waitQuiet(t) + bob.waitQuiet(t) + + if tab1.rec.totalWrites() != before { + t.Error("banned user still receives the room's messages") + } + + if bob.rec.lastJSON(t).ID != "m" { + t.Error("bob, who was not banned, missed the room message") + } + + // Cannot rejoin, by the server API or by a client frame. + assertErrorIs(t, m.JoinRoom(ctx, tab1.ID(), "lobby"), ErrUserBanned) + + _, err := m.ProcessInbound(ctx, &Message{Type: MessageTypeJoin, RoomID: "lobby"}, tab1) + assertErrorIs(t, err, ErrUserBanned) + + // Cannot send. + _, err = m.ProcessInbound(ctx, &Message{Type: MessageTypeMessage, RoomID: "lobby", Data: "x"}, tab1) + if err == nil { + t.Fatal("banned user's message to the room was accepted") + } + + bans, err := rooms.GetBans(ctx, "lobby") + assertNoError(t, err) + + if len(bans) != 1 || bans[0].UserID != "alice" || bans[0].Reason != "spam" { + t.Errorf("GetBans = %+v, want alice for spam", bans) + } + + assertNoError(t, m.UnbanUser(ctx, "alice", "lobby")) + assertNoError(t, m.JoinRoom(ctx, tab1.ID(), "lobby")) +} + +// A connection can still be in the room locally when the ban was made +// elsewhere, on another node in distributed mode. The send check reads the +// shared store, so it refuses the send anyway. It used to ask the local Room, +// which answered with an error that the check read as "not banned". +func TestProcessInbound_RefusesSendFromBannedMemberStillInRoom(t *testing.T) { + m, rooms, _ := realManager(t) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + c := newTestConn("a1", "alice") + assertNoError(t, m.Register(c)) + assertNoError(t, m.JoinRoom(ctx, c.ID(), "lobby")) + + assertNoError(t, rooms.BanMember(ctx, "lobby", "alice", streaming.RoomBan{UserID: "alice", RoomID: "lobby"})) + + if !c.IsInRoom("lobby") { + t.Fatal("setup: the connection should still be in the room locally") + } + + _, err := m.ProcessInbound(ctx, &Message{Type: MessageTypeMessage, RoomID: "lobby", Data: "x"}, c) + assertErrorIs(t, err, ErrUserBanned) +} + +func TestBanUser_ExpiresAtUntil(t *testing.T) { + m, rooms, _ := realManager(t) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + c := newTestConn("a1", "alice") + assertNoError(t, m.Register(c)) + + until := time.Now().Add(100 * time.Millisecond) + assertNoError(t, m.BanUser(ctx, "alice", "lobby", "cool off", &until)) + assertErrorIs(t, m.JoinRoom(ctx, c.ID(), "lobby"), ErrUserBanned) + + time.Sleep(time.Until(until) + 20*time.Millisecond) + + assertNoError(t, m.JoinRoom(ctx, c.ID(), "lobby")) +} + +func TestBanUser_UnknownRoom(t *testing.T) { + m, _, _ := realManager(t) + + assertErrorIs(t, m.BanUser(context.Background(), "alice", "nowhere", "", nil), ErrRoomNotFound) +} + +// End to end over a real WebSocket: a banned client is told so, stops getting +// the room's messages, cannot send to it, and cannot join it again until it +// is unbanned. +func TestWebSocket_BannedClient(t *testing.T) { + ext, srv := newPresenceServer(t) + ctx := context.Background() + + if err := ext.Manager().CreateRoom(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"})); err != nil { + t.Fatal(err) + } + + cli, _, _, err := ws.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/ws?uid=alice") + if err != nil { + t.Fatal(err) + } + defer cli.Close() + + send := func(frame map[string]any) { + t.Helper() + + data, err := json.Marshal(frame) + if err != nil { + t.Fatal(err) + } + + if err := wsutil.WriteClientText(cli, data); err != nil { + t.Fatal(err) + } + } + + // next returns the next frame that is not a heartbeat. + next := func() *Message { + t.Helper() + + _ = cli.SetReadDeadline(time.Now().Add(3 * time.Second)) + + for { + data, err := wsutil.ReadServerText(cli) + if err != nil { + t.Fatalf("reading from the server: %v", err) + } + + var msg Message + if err := json.Unmarshal(data, &msg); err != nil { + t.Fatalf("undecodable frame %s: %v", data, err) + } + + if lifecycleOf(&msg) == "ping" { + continue + } + + return &msg + } + } + + errorCode := func(msg *Message) string { + data, _ := msg.Data.(map[string]any) + code, _ := data["code"].(string) + + return code + } + + send(map[string]any{"type": MessageTypeJoin, "room_id": "lobby"}) + send(map[string]any{"type": MessageTypeMessage, "room_id": "lobby", "data": "before"}) + + if got := next(); got.Type != MessageTypeMessage || got.Data != "before" { + t.Fatalf("expected own room message before the ban, got %+v", got) + } + + if err := ext.Manager().BanUser(ctx, "alice", "lobby", "spam", nil); err != nil { + t.Fatal(err) + } + + if got := next(); lifecycleOf(got) != "room.banned" || got.RoomID != "lobby" { + t.Fatalf("expected a room.banned notice, got %+v", got) + } + + send(map[string]any{"type": MessageTypeMessage, "room_id": "lobby", "data": "after"}) + + if got := next(); got.Type != MessageTypeError { + t.Fatalf("send after the ban was not refused: %+v", got) + } + + send(map[string]any{"type": MessageTypeJoin, "room_id": "lobby"}) + + if got := next(); got.Type != MessageTypeError || errorCode(got) != "banned" { + t.Fatalf("rejoin after the ban: got %+v, want a banned error", got) + } + + if err := ext.Manager().UnbanUser(ctx, "alice", "lobby"); err != nil { + t.Fatal(err) + } + + send(map[string]any{"type": MessageTypeJoin, "room_id": "lobby"}) + send(map[string]any{"type": MessageTypeMessage, "room_id": "lobby", "data": "again"}) + + if got := next(); got.Type != MessageTypeMessage || got.Data != "again" { + t.Fatalf("expected own room message after the unban, got %+v", got) + } +} diff --git a/extensions/streaming/testing_test.go b/extensions/streaming/testing_test.go index e671ec343..7dfc8d89c 100644 --- a/extensions/streaming/testing_test.go +++ b/extensions/streaming/testing_test.go @@ -284,6 +284,8 @@ type fakeRoomStore struct { removeMemberCalls []removeMemberCall connectCalls int disconnectCalls int + + bans map[string]map[string]bool // roomID -> userID -> banned } type addMemberCall struct { @@ -382,6 +384,41 @@ func (s *fakeRoomStore) AddMember(ctx context.Context, roomID string, member str return nil } +// IsBanned reports bans recorded by BanMember. The manager consults it on +// joins and sends. +func (s *fakeRoomStore) IsBanned(ctx context.Context, roomID, userID string) (bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + + return s.bans[roomID][userID], nil +} + +func (s *fakeRoomStore) BanMember(ctx context.Context, roomID, userID string, ban streaming.RoomBan) error { + s.mu.Lock() + defer s.mu.Unlock() + + if s.bans == nil { + s.bans = make(map[string]map[string]bool) + } + + if s.bans[roomID] == nil { + s.bans[roomID] = make(map[string]bool) + } + + s.bans[roomID][userID] = true + + return nil +} + +func (s *fakeRoomStore) UnbanMember(ctx context.Context, roomID, userID string) error { + s.mu.Lock() + defer s.mu.Unlock() + + delete(s.bans[roomID], userID) + + return nil +} + func (s *fakeRoomStore) RemoveMember(ctx context.Context, roomID, userID string) error { s.mu.Lock() defer s.mu.Unlock() From 6ca13642607dc4d7df50e97a7342936a6c8adf4c Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 23:05:44 -0600 Subject: [PATCH 13/17] feat(streaming): implement room mutes on the Redis backend The Redis room's MuteMember, UnmuteMember and IsMuted returned ErrInvalidRoom, so Manager.MuteUser failed on every Redis room, and the send check, which reads IsMuted, treated the error as "not muted". A muted user could keep sending. Mutes now live in a per-room hash of user id to the time the mute ends, with the same now+duration semantics as the local backend. IsMuted treats an elapsed mute as absent and deletes it on the way past. Deleting a room now also drops its bans and mutes, so a room recreated under the same id does not inherit them. The local backend's IsMuted deleted elapsed mutes from the map while holding only the read lock, a data race with concurrent readers. It now only reads, and MuteMember reclaims elapsed entries under the write lock. A manager-level test runs the send gate against both backends: a muted member stays in the room but its sends are refused until it is unmuted or the mute runs out. --- .../backends/local/room_bans_test.go | 28 ++++++ .../streaming/backends/local/room_store.go | 21 ++-- .../backends/redis/room_mutes_test.go | 84 ++++++++++++++++ .../streaming/backends/redis/room_store.go | 61 +++++++++++- extensions/streaming/room_mutes_test.go | 97 +++++++++++++++++++ 5 files changed, 280 insertions(+), 11 deletions(-) create mode 100644 extensions/streaming/backends/redis/room_mutes_test.go create mode 100644 extensions/streaming/room_mutes_test.go diff --git a/extensions/streaming/backends/local/room_bans_test.go b/extensions/streaming/backends/local/room_bans_test.go index f9fa66320..11c9bd1d9 100644 --- a/extensions/streaming/backends/local/room_bans_test.go +++ b/extensions/streaming/backends/local/room_bans_test.go @@ -3,6 +3,7 @@ package local import ( "context" "errors" + "sync" "testing" "time" @@ -63,3 +64,30 @@ func TestLocalRoom_BanMethodsUseTheStore(t *testing.T) { t.Error("expired ban still reported") } } + +// IsMuted used to delete an elapsed mute while holding only the read lock, +// which races with concurrent readers. Run with -race. +func TestLocalRoom_IsMutedIsSafeConcurrently(t *testing.T) { + ctx := context.Background() + room := NewRoom(streaming.RoomOptions{ID: "r1", Name: "r1"}) + + if err := room.MuteMember(ctx, "alice", -time.Second); err != nil { + t.Fatal(err) + } + + var wg sync.WaitGroup + + for range 8 { + wg.Go(func() { + for range 100 { + if muted, _ := room.IsMuted(ctx, "alice"); muted { + t.Error("elapsed mute reported") + + return + } + } + }) + } + + wg.Wait() +} diff --git a/extensions/streaming/backends/local/room_store.go b/extensions/streaming/backends/local/room_store.go index 24d80d7b0..ad920dacb 100644 --- a/extensions/streaming/backends/local/room_store.go +++ b/extensions/streaming/backends/local/room_store.go @@ -990,11 +990,21 @@ func (r *LocalRoom) GetBannedMembers(ctx context.Context) ([]streaming.RoomBan, return s.GetBans(ctx, r.GetID()) } +// MuteMember mutes userID until now+duration. func (r *LocalRoom) MuteMember(ctx context.Context, userID string, duration time.Duration) error { r.mu.Lock() defer r.mu.Unlock() - r.mutedMembers[userID] = time.Now().Add(duration) + // Reclaim expired entries here, under the write lock, rather than in + // IsMuted. + now := time.Now() + for uid, until := range r.mutedMembers { + if !until.After(now) { + delete(r.mutedMembers, uid) + } + } + + r.mutedMembers[userID] = now.Add(duration) return nil } @@ -1012,12 +1022,11 @@ func (r *LocalRoom) IsMuted(ctx context.Context, userID string) (bool, error) { r.mu.RLock() defer r.mu.RUnlock() + // No delete of an expired entry here: this holds only the read lock, and + // deleting from the map under it raced with every concurrent reader. + // MuteMember and UnmuteMember reclaim expired entries. if muteUntil, exists := r.mutedMembers[userID]; exists { - if muteUntil.After(time.Now()) { - return true, nil - } - // Mute expired, clean it up - delete(r.mutedMembers, userID) + return muteUntil.After(time.Now()), nil } return false, nil diff --git a/extensions/streaming/backends/redis/room_mutes_test.go b/extensions/streaming/backends/redis/room_mutes_test.go new file mode 100644 index 000000000..6aacd5299 --- /dev/null +++ b/extensions/streaming/backends/redis/room_mutes_test.go @@ -0,0 +1,84 @@ +package redis + +import ( + "context" + "testing" + "time" + + "github.com/xraph/forge/extensions/streaming/backends/local" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// The Redis room's mute methods returned ErrInvalidRoom, so MuteUser failed +// and a muted user could keep sending. +func TestRedisRoom_Mutes(t *testing.T) { + ctx := context.Background() + client := newTestClient(t) + s := NewRoomStore(client, "test:rooms") + + if err := s.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"})); err != nil { + t.Fatal(err) + } + + room, err := s.Get(ctx, "lobby") + if err != nil { + t.Fatal(err) + } + + if err := room.MuteMember(ctx, "alice", time.Hour); err != nil { + t.Fatalf("MuteMember: %v", err) + } + + if muted, err := room.IsMuted(ctx, "alice"); err != nil || !muted { + t.Fatalf("IsMuted(alice) = %v, %v; want true", muted, err) + } + + if muted, _ := room.IsMuted(ctx, "bob"); muted { + t.Fatal("bob reported muted without a mute") + } + + // Visible through a second Room handle, as on another node. + other, err := s.Get(ctx, "lobby") + if err != nil { + t.Fatal(err) + } + + if muted, _ := other.IsMuted(ctx, "alice"); !muted { + t.Fatal("mute not visible through another handle on the same room") + } + + if err := room.UnmuteMember(ctx, "alice"); err != nil { + t.Fatalf("UnmuteMember: %v", err) + } + + if muted, _ := room.IsMuted(ctx, "alice"); muted { + t.Fatal("alice still muted after UnmuteMember") + } + + // An elapsed mute is no mute, and is cleaned up when read. + if err := room.MuteMember(ctx, "carol", -time.Second); err != nil { + t.Fatal(err) + } + + if muted, _ := room.IsMuted(ctx, "carol"); muted { + t.Fatal("elapsed mute still reported") + } + + if n, _ := client.HLen(ctx, "test:rooms:lobby:mutes").Result(); n != 0 { + t.Fatalf("elapsed mute left %d entries behind", n) + } + + // Deleting the room drops its mutes, so a room recreated under the same + // id does not inherit them. + if err := room.MuteMember(ctx, "dave", time.Hour); err != nil { + t.Fatal(err) + } + + if err := s.Delete(ctx, "lobby"); err != nil { + t.Fatal(err) + } + + if n, _ := client.Exists(ctx, "test:rooms:lobby:mutes").Result(); n != 0 { + t.Fatal("room delete left its mutes behind") + } +} diff --git a/extensions/streaming/backends/redis/room_store.go b/extensions/streaming/backends/redis/room_store.go index 4c2f46ee7..b9ba40940 100644 --- a/extensions/streaming/backends/redis/room_store.go +++ b/extensions/streaming/backends/redis/room_store.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "slices" + "strconv" "strings" "time" @@ -143,10 +144,12 @@ func (s *RoomStore) Delete(ctx context.Context, roomID string) error { key := fmt.Sprintf("%s:%s", s.prefix, roomID) membersKey := fmt.Sprintf("%s:%s:members", s.prefix, roomID) - // Delete room, members, and from list + // Delete room, members, moderation state, and from list. Bans and mutes + // are dropped too, so a room recreated under the same id starts clean. pipe := s.client.Pipeline() pipe.Del(ctx, key) pipe.Del(ctx, membersKey) + pipe.Del(ctx, s.bansKey(roomID), s.mutesKey(roomID)) pipe.SRem(ctx, s.prefix+":list", roomID) _, err := pipe.Exec(ctx) @@ -384,7 +387,7 @@ func (s *RoomStore) DeleteMany(ctx context.Context, roomIDs []string) error { bansKey := fmt.Sprintf("%s:%s:bans", s.prefix, roomID) invitesKey := fmt.Sprintf("%s:%s:invites", s.prefix, roomID) - pipe.Del(ctx, key, membersKey, bansKey, invitesKey) + pipe.Del(ctx, key, membersKey, bansKey, invitesKey, s.mutesKey(roomID)) pipe.SRem(ctx, s.prefix+":list", roomID) } @@ -590,6 +593,49 @@ func (s *RoomStore) GetBans(ctx context.Context, roomID string) ([]streaming.Roo return bans, nil } +func (s *RoomStore) bansKey(roomID string) string { + return fmt.Sprintf("%s:%s:bans", s.prefix, roomID) +} + +// mutesKey names the hash of a room's mutes: user id to the time the mute +// ends, in Unix nanoseconds. +func (s *RoomStore) mutesKey(roomID string) string { + return fmt.Sprintf("%s:%s:mutes", s.prefix, roomID) +} + +func (s *RoomStore) muteMember(ctx context.Context, roomID, userID string, duration time.Duration) error { + until := time.Now().Add(duration).UnixNano() + + return s.client.HSet(ctx, s.mutesKey(roomID), userID, strconv.FormatInt(until, 10)).Err() +} + +// isMuted reports whether a mute is in force. An expired one is deleted on the +// way past, the same way IsBanned treats an expired ban. +func (s *RoomStore) isMuted(ctx context.Context, roomID, userID string) (bool, error) { + data, err := s.client.HGet(ctx, s.mutesKey(roomID), userID).Result() + if errors.Is(err, redis.Nil) { + return false, nil + } + + if err != nil { + return false, err + } + + until, err := strconv.ParseInt(data, 10, 64) + if err != nil { + // Unreadable, but a mute was recorded: err on the side of the mute. + return true, nil //nolint:nilerr // a corrupt mute entry still counts as a mute + } + + if until <= time.Now().UnixNano() { + _ = s.client.HDel(ctx, s.mutesKey(roomID), userID).Err() + + return false, nil + } + + return true, nil +} + // IsBanned checks if a user is currently banned from a room. // // It honours RoomBan.ExpiresAt. It used to answer from HExists alone, so a @@ -814,16 +860,21 @@ func (r *redisRoom) GetBannedMembers(ctx context.Context) ([]streaming.RoomBan, return r.store.GetBans(ctx, r.id) } +// MuteMember mutes userID in the room until now+duration, as the local +// backend does. +// +// These used to return ErrInvalidRoom, so Manager.MuteUser failed on every +// Redis room and the send check, which reads IsMuted, never saw a mute. func (r *redisRoom) MuteMember(ctx context.Context, userID string, duration time.Duration) error { - return streaming.ErrInvalidRoom + return r.store.muteMember(ctx, r.id, userID, duration) } func (r *redisRoom) UnmuteMember(ctx context.Context, userID string) error { - return streaming.ErrInvalidRoom + return r.store.client.HDel(ctx, r.store.mutesKey(r.id), userID).Err() } func (r *redisRoom) IsMuted(ctx context.Context, userID string) (bool, error) { - return false, streaming.ErrInvalidRoom + return r.store.isMuted(ctx, r.id, userID) } // Invitations. diff --git a/extensions/streaming/room_mutes_test.go b/extensions/streaming/room_mutes_test.go new file mode 100644 index 000000000..d6822854a --- /dev/null +++ b/extensions/streaming/room_mutes_test.go @@ -0,0 +1,97 @@ +package streaming + +import ( + "context" + "testing" + "time" + + "github.com/alicebob/miniredis/v2" + goredis "github.com/redis/go-redis/v9" + streamauth "github.com/xraph/forge/extensions/streaming/auth" + "github.com/xraph/forge/extensions/streaming/backends/local" + redisbackend "github.com/xraph/forge/extensions/streaming/backends/redis" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// muteBackends returns a manager over each room store backend. +func muteBackends(t *testing.T) map[string]func(t *testing.T) (Manager, streaming.RoomStore) { + t.Helper() + + build := func(rooms streaming.RoomStore) Manager { + msgs := local.NewMessageStore() + ra := streamauth.NewRoomAuthorizer(rooms) + + return NewManager(DefaultConfig(), rooms, local.NewChannelStore(), msgs, + newFakePresenceTracker(), newFakeTypingTracker(), nil, nil, nil, + WithRoomAuthorizer(ra), + WithMessageAuthorizer(streamauth.NewMessageAuthorizer(ra, newAuthMessageStore(msgs))), + ) + } + + return map[string]func(t *testing.T) (Manager, streaming.RoomStore){ + "local": func(t *testing.T) (Manager, streaming.RoomStore) { + t.Helper() + + rooms := local.NewRoomStore() + + return build(rooms), rooms + }, + "redis": func(t *testing.T) (Manager, streaming.RoomStore) { + t.Helper() + + client := goredis.NewClient(&goredis.Options{Addr: miniredis.RunT(t).Addr()}) + t.Cleanup(func() { _ = client.Close() }) + + rooms := redisbackend.NewRoomStore(client, "test:rooms") + + return build(rooms), rooms + }, + } +} + +// A muted member stays in the room and keeps receiving it, but the send gate +// refuses what they send until the mute is lifted or runs out. On the Redis +// backend MuteUser used to fail outright. +func TestMuteUser_RefusesSendsOnEveryBackend(t *testing.T) { + for name, newManager := range muteBackends(t) { + t.Run(name, func(t *testing.T) { + m, rooms := newManager(t) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + alice := newTestConn("a1", "alice") + bob := newTestConn("b1", "bob") + + for _, c := range []*testConn{alice, bob} { + assertNoError(t, m.Register(c)) + assertNoError(t, m.JoinRoom(ctx, c.ID(), "lobby")) + } + + send := func(c *testConn) error { + _, err := m.ProcessInbound(ctx, &Message{Type: MessageTypeMessage, RoomID: "lobby", Data: "hi"}, c) + + return err + } + + assertNoError(t, m.MuteUser(ctx, "alice", "lobby", time.Hour)) + assertErrorIs(t, send(alice), ErrUserMuted) + assertNoError(t, send(bob)) + + if !alice.IsInRoom("lobby") { + t.Fatal("a mute must not take the user out of the room") + } + + assertNoError(t, m.UnmuteUser(ctx, "alice", "lobby")) + assertNoError(t, send(alice)) + + // A mute with an end runs out on its own. + assertNoError(t, m.MuteUser(ctx, "alice", "lobby", 100*time.Millisecond)) + assertErrorIs(t, send(alice), ErrUserMuted) + + time.Sleep(150 * time.Millisecond) + + assertNoError(t, send(alice)) + }) + } +} From 40c9f4dc3731264d384e9714a69ff7ea77845aa8 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 23:09:49 -0600 Subject: [PATCH 14/17] fix(streaming): evict banned users on every node BanUser took the banned user's connections out of the room only on the node that ran it. Every node keeps its own connections and room index, so a banned user connected to another node stayed in that node's index and kept receiving the room until they reconnected. The store-backed send check stopped them sending, but not receiving. BanUser now announces the ban through the coordinator after writing it to the store, as a new room.member.ban control event. Each node that receives it removes the user's local connections from the room and sends each one the same room.banned system frame the origin node sends. - coordinator.EventPublisher is a new optional interface with PublishEvent, implemented by the Redis and NATS coordinators on their global channel. It is separate from StreamCoordinator so existing implementations keep compiling, and the manager does without it when it is missing. - DecodeMessage decodes the event's payload into a *RoomBanEvent carrying the reason and expiry. - Handling is idempotent. A connection that is not in the room is left alone and gets no notice, so a duplicate or replayed event does nothing. - A node evicts on receipt without waiting for the store, so an event that beats the store write, or a deployment whose stores are not shared, still evicts. If the store does not show the ban yet, the node checks again after 500 ms and evicts once more if it does by then. That catches a user who rejoined through that node in the gap. An event for a ban that has already expired is ignored. The test runs two started managers sharing a Redis room store and Redis coordinators on miniredis. A ban issued on one node removes the user from the room on the other, delivers the notice there, and a room message relayed afterwards reaches a control member on that node but not the banned user. --- .../streaming/coordinator/coordinator.go | 34 ++- .../streaming/coordinator/decode_test.go | 27 ++ extensions/streaming/coordinator/nats.go | 24 ++ extensions/streaming/coordinator/redis.go | 19 ++ extensions/streaming/manager.go | 97 ++++++- .../streaming/room_ban_distributed_test.go | 259 ++++++++++++++++++ 6 files changed, 456 insertions(+), 4 deletions(-) create mode 100644 extensions/streaming/room_ban_distributed_test.go diff --git a/extensions/streaming/coordinator/coordinator.go b/extensions/streaming/coordinator/coordinator.go index 53c40d0dd..fd8916cb8 100644 --- a/extensions/streaming/coordinator/coordinator.go +++ b/extensions/streaming/coordinator/coordinator.go @@ -82,8 +82,29 @@ const ( MessageTypeMemberLeave = "room.member.leave" MessageTypeNodeRegister = "node.register" MessageTypeNodeUnregister = "node.unregister" + + // MessageTypeRoomBan tells every node a user was banned from a room, so + // each can take that user's local connections out of it. UserID and + // RoomID name the ban; the payload is a *RoomBanEvent. + MessageTypeRoomBan = "room.member.ban" ) +// RoomBanEvent is the payload of a MessageTypeRoomBan message. +type RoomBanEvent struct { + Reason string `json:"reason,omitempty"` + ExpiresAt *time.Time `json:"expiresAt,omitempty"` +} + +// EventPublisher is implemented by coordinators that can send a control event +// to every other node. It is separate from StreamCoordinator so coordinators +// written against that interface keep compiling; the manager checks for it +// and does without when it is missing. +type EventPublisher interface { + // PublishEvent sends msg to every node. NodeID and Timestamp are filled in + // when empty, so the sending node skips its own event. + PublishEvent(ctx context.Context, msg *CoordinatorMessage) error +} + // rawCoordinatorMessage is CoordinatorMessage with the payload left encoded. // The outer Payload field shadows the embedded one for encoding/json. type rawCoordinatorMessage struct { @@ -112,7 +133,8 @@ func DecodeMessage(data []byte) (*CoordinatorMessage, error) { return &msg, nil } - if msg.Type == MessageTypeBroadcast { + switch msg.Type { + case MessageTypeBroadcast: var sm streaming.Message if err := json.Unmarshal(raw.Payload, &sm); err != nil { return nil, err @@ -120,6 +142,16 @@ func DecodeMessage(data []byte) (*CoordinatorMessage, error) { msg.Payload = &sm + return &msg, nil + + case MessageTypeRoomBan: + var ev RoomBanEvent + if err := json.Unmarshal(raw.Payload, &ev); err != nil { + return nil, err + } + + msg.Payload = &ev + return &msg, nil } diff --git a/extensions/streaming/coordinator/decode_test.go b/extensions/streaming/coordinator/decode_test.go index 35ef5dfc0..b107c2b42 100644 --- a/extensions/streaming/coordinator/decode_test.go +++ b/extensions/streaming/coordinator/decode_test.go @@ -3,6 +3,7 @@ package coordinator import ( "encoding/json" "testing" + "time" streaming "github.com/xraph/forge/extensions/streaming/internal" ) @@ -58,3 +59,29 @@ func TestDecodeMessage_OtherPayloadsStayGeneric(t *testing.T) { t.Fatalf("null payload decoded to %#v", got.Payload) } } + +func TestDecodeMessage_RoomBanPayload(t *testing.T) { + until := time.Now().Add(time.Hour).UTC().Truncate(time.Second) + + wire, err := json.Marshal(CoordinatorMessage{ + Type: MessageTypeRoomBan, NodeID: "n1", UserID: "alice", RoomID: "lobby", + Payload: &RoomBanEvent{Reason: "spam", ExpiresAt: &until}, + }) + if err != nil { + t.Fatal(err) + } + + got, err := DecodeMessage(wire) + if err != nil { + t.Fatal(err) + } + + ev, ok := got.Payload.(*RoomBanEvent) + if !ok { + t.Fatalf("payload is %T, want *RoomBanEvent", got.Payload) + } + + if ev.Reason != "spam" || ev.ExpiresAt == nil || !ev.ExpiresAt.Equal(until) || got.UserID != "alice" || got.RoomID != "lobby" { + t.Fatalf("decoded %+v / %+v", got, ev) + } +} diff --git a/extensions/streaming/coordinator/nats.go b/extensions/streaming/coordinator/nats.go index a52690b23..a6a146546 100644 --- a/extensions/streaming/coordinator/nats.go +++ b/extensions/streaming/coordinator/nats.go @@ -420,6 +420,30 @@ func (nc *natsCoordinator) UnregisterNode(ctx context.Context, nodeID string) er return err } +// PublishEvent implements EventPublisher on the global subject. +// +// Note that the global subject is consumed through the "streaming-workers" +// queue group, so today one node rather than every node receives each global +// message. That limits this event exactly as it limits BroadcastGlobal. +func (nc *natsCoordinator) PublishEvent(ctx context.Context, msg *CoordinatorMessage) error { + if msg.NodeID == "" { + msg.NodeID = nc.nodeID + } + + if msg.Timestamp.IsZero() { + msg.Timestamp = time.Now() + } + + data, err := json.Marshal(msg) + if err != nil { + return fmt.Errorf("failed to marshal coordinator event: %w", err) + } + + _, err = nc.js.Publish("streaming.broadcast.global", data, nats.Context(ctx)) + + return err +} + // Subscribe subscribes to coordinator events. func (nc *natsCoordinator) Subscribe(ctx context.Context, handler MessageHandler) error { nc.handler = handler diff --git a/extensions/streaming/coordinator/redis.go b/extensions/streaming/coordinator/redis.go index 11c482f18..d4aa08f0f 100644 --- a/extensions/streaming/coordinator/redis.go +++ b/extensions/streaming/coordinator/redis.go @@ -282,6 +282,25 @@ func (rc *redisCoordinator) UnregisterNode(ctx context.Context, nodeID string) e return rc.client.Publish(ctx, "streaming:broadcast:global", data).Err() } +// PublishEvent implements EventPublisher. Events go out on the global +// channel, which every node subscribes to. +func (rc *redisCoordinator) PublishEvent(ctx context.Context, msg *CoordinatorMessage) error { + if msg.NodeID == "" { + msg.NodeID = rc.nodeID + } + + if msg.Timestamp.IsZero() { + msg.Timestamp = time.Now() + } + + data, err := json.Marshal(msg) + if err != nil { + return fmt.Errorf("failed to marshal coordinator event: %w", err) + } + + return rc.client.Publish(ctx, "streaming:broadcast:global", data).Err() +} + // Subscribe subscribes to coordinator events. func (rc *redisCoordinator) Subscribe(ctx context.Context, handler MessageHandler) error { rc.handler = handler diff --git a/extensions/streaming/manager.go b/extensions/streaming/manager.go index 4f8ced633..926fe2d68 100644 --- a/extensions/streaming/manager.go +++ b/extensions/streaming/manager.go @@ -3144,6 +3144,12 @@ func (m *manager) BanUser(ctx context.Context, userID, roomID string, reason str m.evictFromRoom(ctx, userID, roomID, reason) + // Tell the other nodes. Each one holds its own connections and its own + // room index, so without this a banned user connected elsewhere kept + // receiving the room until they reconnected. Sent after the store write, + // so a node that checks the store on receipt finds the ban there. + m.publishRoomBan(ctx, userID, roomID, reason, until) + if m.logger != nil { m.logger.Info("user banned", forge.F("user_id", userID), @@ -3156,10 +3162,91 @@ func (m *manager) BanUser(ctx context.Context, userID, roomID string, reason str return nil } +// banRecheckDelay is how long a node waits before looking at the store again +// after a ban event that the store did not yet reflect. See handleRoomBan. +const banRecheckDelay = 500 * time.Millisecond + +// publishRoomBan announces a ban to the other nodes, when the coordinator can +// carry it. A failure is logged and not returned: the ban is already stored, +// and the send and join checks, which read the store, enforce it on every +// node regardless. +func (m *manager) publishRoomBan(ctx context.Context, userID, roomID, reason string, until *time.Time) { + pub, ok := m.coordinator.(coordinator.EventPublisher) + if !ok { + return + } + + err := pub.PublishEvent(ctx, &coordinator.CoordinatorMessage{ + Type: coordinator.MessageTypeRoomBan, + NodeID: m.nodeID, + UserID: userID, + RoomID: roomID, + Payload: &coordinator.RoomBanEvent{Reason: reason, ExpiresAt: until}, + }) + if err != nil && m.logger != nil { + m.logger.Warn("failed to publish room ban to other nodes", + forge.F("user_id", userID), + forge.F("room_id", roomID), + forge.F("error", err), + ) + } +} + +// handleRoomBan applies a ban made on another node to this node's +// connections. +// +// It evicts on receipt without asking the store first. Normally the store +// already has the ban, since the origin writes before it publishes, but a +// deployment whose stores are not shared would never see it, and a +// replicated store may lag. Eviction is idempotent: a connection that is not +// in the room is left alone and gets no notice, so a duplicate or replayed +// event does nothing. +// +// When the store does not show the ban yet, the node looks again after +// banRecheckDelay and evicts once more if it does by then. That catches a +// user who rejoined through this node in the gap, before JoinRoom could see +// the ban. An event for a ban that has already expired is ignored. One that +// arrives after an unban still evicts, which costs the user a rejoin and +// nothing else. +func (m *manager) handleRoomBan(ctx context.Context, msg *coordinator.CoordinatorMessage) { + if msg.UserID == "" || msg.RoomID == "" { + return + } + + var reason string + + switch ev := msg.Payload.(type) { + case *coordinator.RoomBanEvent: + if ev.ExpiresAt != nil && !ev.ExpiresAt.After(time.Now()) { + return + } + + reason = ev.Reason + case map[string]any: + reason, _ = ev["reason"].(string) + } + + m.evictFromRoom(ctx, msg.UserID, msg.RoomID, reason) + + if banned, err := m.roomStore.IsBanned(ctx, msg.RoomID, msg.UserID); err == nil && banned { + return + } + + userID, roomID := msg.UserID, msg.RoomID + + time.AfterFunc(banRecheckDelay, func() { + rctx, cancel := context.WithTimeout(context.Background(), coordinatorCallTimeout) + defer cancel() + + if banned, err := m.roomStore.IsBanned(rctx, roomID, userID); err == nil && banned { + m.evictFromRoom(rctx, userID, roomID, reason) + } + }) +} + // evictFromRoom takes the user's connections on this node out of a room and -// tells each one why. Connections on other nodes keep their local membership -// until they reconnect, but the ban check in authorizeSend refuses their -// sends, since it asks the shared store. +// tells each one why. Other nodes do the same for their own connections when +// the ban event reaches them (handleRoomBan). func (m *manager) evictFromRoom(ctx context.Context, userID, roomID, reason string) { for _, conn := range m.GetUserConnections(userID) { if !conn.IsInRoom(roomID) { @@ -3490,6 +3577,10 @@ func (m *manager) handleCoordinatorMessage(ctx context.Context, msg *coordinator // Handle node lifecycle events for load balancer switch msg.Type { + case coordinator.MessageTypeRoomBan: + m.handleRoomBan(ctx, msg) + + return nil case coordinator.MessageTypeNodeRegister: m.handleNodeRegister(ctx, msg) diff --git a/extensions/streaming/room_ban_distributed_test.go b/extensions/streaming/room_ban_distributed_test.go new file mode 100644 index 000000000..245a539c1 --- /dev/null +++ b/extensions/streaming/room_ban_distributed_test.go @@ -0,0 +1,259 @@ +package streaming + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/alicebob/miniredis/v2" + "github.com/google/uuid" + goredis "github.com/redis/go-redis/v9" + streamauth "github.com/xraph/forge/extensions/streaming/auth" + "github.com/xraph/forge/extensions/streaming/backends/local" + redisbackend "github.com/xraph/forge/extensions/streaming/backends/redis" + "github.com/xraph/forge/extensions/streaming/coordinator" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// newClusterNode builds a started manager that shares a room store and a +// Redis coordinator with the rest of the cluster, as a real node does. +func newClusterNode(t *testing.T, addr, nodeID string, rooms streaming.RoomStore) Manager { + t.Helper() + + client := goredis.NewClient(&goredis.Options{Addr: addr}) + + t.Cleanup(func() { _ = client.Close() }) + + cfg := DefaultConfig() + cfg.NodeID = nodeID + + msgs := local.NewMessageStore() + ra := streamauth.NewRoomAuthorizer(rooms) + + m := NewManager(cfg, rooms, local.NewChannelStore(), msgs, + newFakePresenceTracker(), newFakeTypingTracker(), nil, nil, nil, + WithRoomAuthorizer(ra), + WithMessageAuthorizer(streamauth.NewMessageAuthorizer(ra, newAuthMessageStore(msgs))), + WithCoordinator(coordinator.NewRedisCoordinator(client, nodeID)), + WithManagerNodeID(nodeID), + ) + + ctx, cancel := context.WithCancel(context.Background()) + + if err := m.Start(ctx); err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { + _ = m.Stop(context.Background()) + + cancel() + }) + + return m +} + +func newMessageID() string { return uuid.NewString() } + +// receivedFrames decodes every JSON frame the connection's transport got. +func receivedFrames(c *testConn) []Message { + c.rec.mu.Lock() + defer c.rec.mu.Unlock() + + out := make([]Message, 0, len(c.rec.jsonWrites)) + + for _, w := range c.rec.jsonWrites { + var raw []byte + + switch v := w.(type) { + case json.RawMessage: + raw = v + case *Message: + out = append(out, *v) + + continue + default: + continue + } + + var msg Message + if json.Unmarshal(raw, &msg) == nil { + out = append(out, msg) + } + } + + return out +} + +func countData(c *testConn, data string) int { + n := 0 + + for _, m := range receivedFrames(c) { + if m.Data == data { + n++ + } + } + + return n +} + +func receivedData(c *testConn, data string) bool { return countData(c, data) > 0 } + +func countLifecycle(c *testConn, lifecycle string) int { + n := 0 + + frames := receivedFrames(c) + for i := range frames { + if lifecycleOf(&frames[i]) == lifecycle { + n++ + } + } + + return n +} + +func receivedLifecycle(c *testConn, lifecycle string) bool { return countLifecycle(c, lifecycle) > 0 } + +// eventually polls cond for up to two seconds. +func eventually(t *testing.T, what string, cond func() bool) { + t.Helper() + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if cond() { + return + } + + time.Sleep(5 * time.Millisecond) + } + + t.Fatalf("timed out waiting for %s", what) +} + +// A ban made on one node used to evict only that node's connections. A +// banned user connected to another node stayed in that node's room index and +// kept receiving the room until they reconnected. +func TestBanUser_EvictsOnEveryNode(t *testing.T) { + srv := miniredis.RunT(t) + ctx := context.Background() + + shared := goredis.NewClient(&goredis.Options{Addr: srv.Addr()}) + + t.Cleanup(func() { _ = shared.Close() }) + + rooms := redisbackend.NewRoomStore(shared, "cluster:rooms") + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + nodeA := newClusterNode(t, srv.Addr(), "node-a", rooms) + nodeB := newClusterNode(t, srv.Addr(), "node-b", rooms) + + bob := newTestConn("bob-1", "bob") // on node A, where the ban is issued + alice := newTestConn("alice-1", "alice") // on node B, the one being banned + carol := newTestConn("carol-1", "carol") // on node B, a control + + assertNoError(t, nodeA.Register(bob)) + assertNoError(t, nodeA.JoinRoom(ctx, bob.ID(), "lobby")) + + for _, c := range []*testConn{alice, carol} { + assertNoError(t, nodeB.Register(c)) + assertNoError(t, nodeB.JoinRoom(ctx, c.ID(), "lobby")) + } + + // Wait until node B hears node A, which also proves the relay works. + eventually(t, "node B to receive node A's room messages", func() bool { + _ = nodeA.BroadcastToRoom(ctx, "lobby", &Message{ID: newMessageID(), Type: MessageTypeMessage, RoomID: "lobby", Data: "warmup"}) + + return receivedData(alice, "warmup") + }) + + assertNoError(t, nodeA.BanUser(ctx, "alice", "lobby", "spam", nil)) + + eventually(t, "node B to take alice out of the room", func() bool { return !alice.IsInRoom("lobby") }) + + eventually(t, "alice's room.banned notice", func() bool { return receivedLifecycle(alice, "room.banned") }) + + before := countData(alice, "after the ban") + + assertNoError(t, nodeA.BroadcastToRoom(ctx, "lobby", + &Message{ID: newMessageID(), Type: MessageTypeMessage, RoomID: "lobby", Data: "after the ban"})) + + // Carol is on the same node as alice: once she has the message, node B has + // done its delivery, so alice's count is final. + eventually(t, "carol to receive the post-ban message", func() bool { return receivedData(carol, "after the ban") }) + alice.waitQuiet(t) + + if countData(alice, "after the ban") != before { + t.Fatal("alice, banned on node A, still received the room message on node B") + } + + // Idempotent: a duplicate event changes nothing and sends no second notice. + notices := countLifecycle(alice, "room.banned") + + assertNoError(t, nodeB.(*manager).handleCoordinatorMessage(ctx, &coordinator.CoordinatorMessage{ + Type: coordinator.MessageTypeRoomBan, NodeID: "node-a", UserID: "alice", RoomID: "lobby", + Payload: &coordinator.RoomBanEvent{Reason: "spam"}, + })) + alice.waitQuiet(t) + + if countLifecycle(alice, "room.banned") != notices { + t.Fatal("a duplicate ban event sent a second notice") + } +} + +// The event can beat the store write, for instance on a lagging replica. The +// node evicts on receipt anyway, and if the user rejoins in the gap, before +// JoinRoom can see the ban, a later recheck takes them out again. +func TestHandleRoomBan_BeforeStoreWrite(t *testing.T) { + m, rooms, _ := realManager(t) + mgr := m.(*manager) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + alice := newTestConn("alice-1", "alice") + assertNoError(t, m.Register(alice)) + assertNoError(t, m.JoinRoom(ctx, alice.ID(), "lobby")) + + event := &coordinator.CoordinatorMessage{ + Type: coordinator.MessageTypeRoomBan, NodeID: "elsewhere", UserID: "alice", RoomID: "lobby", + Payload: &coordinator.RoomBanEvent{Reason: "spam"}, + } + + assertNoError(t, mgr.handleCoordinatorMessage(ctx, event)) + + if alice.IsInRoom("lobby") { + t.Fatal("not evicted on an event that arrived before the store write") + } + + // Rejoin in the gap: the store has no ban yet, so this succeeds. + assertNoError(t, m.JoinRoom(ctx, alice.ID(), "lobby")) + + // The origin's store write lands. + assertNoError(t, rooms.BanMember(ctx, "lobby", "alice", streaming.RoomBan{UserID: "alice", RoomID: "lobby"})) + + eventually(t, "the recheck to evict the rejoined connection", func() bool { return !alice.IsInRoom("lobby") }) +} + +// An event for a ban that has already run out does nothing. +func TestHandleRoomBan_IgnoresExpiredBan(t *testing.T) { + m, rooms, _ := realManager(t) + ctx := context.Background() + + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + alice := newTestConn("alice-1", "alice") + assertNoError(t, m.Register(alice)) + assertNoError(t, m.JoinRoom(ctx, alice.ID(), "lobby")) + + past := time.Now().Add(-time.Minute) + + assertNoError(t, m.(*manager).handleCoordinatorMessage(ctx, &coordinator.CoordinatorMessage{ + Type: coordinator.MessageTypeRoomBan, NodeID: "elsewhere", UserID: "alice", RoomID: "lobby", + Payload: &coordinator.RoomBanEvent{ExpiresAt: &past}, + })) + + if !alice.IsInRoom("lobby") { + t.Fatal("an expired ban event evicted the user") + } +} From 99153e6dc235798018a698185501c2acf3db7da1 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 23:15:00 -0600 Subject: [PATCH 15/17] fix(streaming): deliver NATS global messages to every node The NATS coordinator consumed every subject through one shared "streaming-workers" queue group. A queue group gives each message to a single member, which suits a work queue and none of these subjects: a global broadcast, a ban event, a room broadcast, a presence or room state update all have to reach every node, because every node holds its own connections. Each one reached one node at random. Against a real JetStream server the shared durable queue consumer could not even be created for the second subject, so Start failed outright. Every subject now has a plain subscription with its own ephemeral consumer, so every node gets every message. Nothing the coordinator carries is a job for exactly one worker, and the node subject is already addressed to a single node, so no queue group remains. The subscriptions use DeliverNew, because the streams retain an hour of broadcasts and a node that starts must not replay that backlog to its clients as live. The room broadcast subject had no subscriber at all and now has one. BroadcastGlobal, BroadcastToRoom, SyncPresence and SyncRoomState now set NodeID to the sender, as the Redis coordinator does, so a node skips its own messages instead of delivering them twice. BroadcastToNode put the target's id in NodeID on both NATS and Redis, so the target took every node message for its own and dropped it. NodeID is now the sender. BroadcastToUser also names the user on the message; without it the receiving manager would have treated the message as global and given one user's message to every connection on that node. Stopping a manager set its dedup tracker to nil while the coordinator's listener could still be reading it, a data race the new cluster tests hit. The tracker is now held in an atomic pointer. Tests use an embedded nats-server, added as a test dependency, which raises nats.go from v1.47.0 to v1.53.1. Three coordinators show that a global broadcast, a ban event and a room broadcast reach every other node exactly once and never echo to the sender, that a node message reaches only its target, and that a node started late does not replay the backlog. Two managers on NATS show that a global broadcast reaches each client exactly once, the sender's own included, and that a ban evicts the user on the other node. A Redis test shows a user message reaching that user on another node and nobody else there. --- extensions/streaming/coordinator/nats.go | 119 ++++----- extensions/streaming/coordinator/nats_test.go | 235 ++++++++++++++++++ extensions/streaming/coordinator/redis.go | 28 ++- extensions/streaming/go.mod | 15 +- extensions/streaming/go.sum | 29 ++- extensions/streaming/manager.go | 17 +- extensions/streaming/nats_cluster_test.go | 133 ++++++++++ .../streaming/room_ban_distributed_test.go | 37 +++ 8 files changed, 525 insertions(+), 88 deletions(-) create mode 100644 extensions/streaming/coordinator/nats_test.go create mode 100644 extensions/streaming/nats_cluster_test.go diff --git a/extensions/streaming/coordinator/nats.go b/extensions/streaming/coordinator/nats.go index a6a146546..82c6c57ce 100644 --- a/extensions/streaming/coordinator/nats.go +++ b/extensions/streaming/coordinator/nats.go @@ -83,58 +83,48 @@ func (nc *natsCoordinator) Start(ctx context.Context) error { return errors.New("coordinator already running") } - // Subscribe to global broadcasts - sub1, err := nc.js.QueueSubscribe( + // Every subject here is a plain subscription with its own ephemeral + // consumer, so every node receives every message. + // + // They used to share the "streaming-workers" queue group, which hands + // each message to exactly one member of the group. That is right for a + // work queue and wrong for all of these: a global broadcast, a ban event, + // a room broadcast, a presence or room state update each have to reach + // every node, because every node holds its own connections and its own + // view. With the queue group each one reached a single node chosen at + // random. Nothing the coordinator carries is a job for one worker; the + // node subject is addressed to one node already, and only that node + // subscribes to it. + // + // DeliverNew because the streams retain messages (an hour for + // broadcasts). A node that starts must not replay that backlog to its + // clients as if it were live. + // + // The room subject had no subscriber at all, so BroadcastToRoom never + // reached another node. + subjects := []string{ "streaming.broadcast.global", - "streaming-workers", - nc.messageHandler, - nats.ManualAck(), - ) - if err != nil { - return fmt.Errorf("failed to subscribe to global broadcasts: %w", err) + "streaming.broadcast.node." + nc.nodeID, + "streaming.broadcast.room.>", + "streaming.presence.*", + "streaming.state.rooms.*", } - nc.subs = append(nc.subs, sub1) + for _, subject := range subjects { + sub, err := nc.js.Subscribe(subject, nc.messageHandler, nats.ManualAck(), nats.DeliverNew()) + if err != nil { + for _, s := range nc.subs { + _ = s.Unsubscribe() + } - // Subscribe to node-specific broadcasts - sub2, err := nc.js.QueueSubscribe( - "streaming.broadcast.node."+nc.nodeID, - "streaming-workers", - nc.messageHandler, - nats.ManualAck(), - ) - if err != nil { - return fmt.Errorf("failed to subscribe to node broadcasts: %w", err) - } + nc.subs = nil - nc.subs = append(nc.subs, sub2) + return fmt.Errorf("failed to subscribe to %s: %w", subject, err) + } - // Subscribe to presence updates - sub3, err := nc.js.QueueSubscribe( - "streaming.presence.*", - "streaming-workers", - nc.messageHandler, - nats.ManualAck(), - ) - if err != nil { - return fmt.Errorf("failed to subscribe to presence updates: %w", err) + nc.subs = append(nc.subs, sub) } - nc.subs = append(nc.subs, sub3) - - // Subscribe to state updates - sub4, err := nc.js.QueueSubscribe( - "streaming.state.rooms.*", - "streaming-workers", - nc.messageHandler, - nats.ManualAck(), - ) - if err != nil { - return fmt.Errorf("failed to subscribe to state updates: %w", err) - } - - nc.subs = append(nc.subs, sub4) - nc.running = true return nil @@ -163,21 +153,26 @@ func (nc *natsCoordinator) Stop(ctx context.Context) error { } // BroadcastToNode sends message to specific node. +// +// NodeID is the sender, as on every other message, and the subject carries +// the target. It used to be the target, so the target's own-message check +// matched and it dropped every message addressed to it. func (nc *natsCoordinator) BroadcastToNode(ctx context.Context, nodeID string, msg *streaming.Message) error { - coordMsg := &CoordinatorMessage{ + return nc.publishToNode(nodeID, &CoordinatorMessage{ Type: MessageTypeBroadcast, - NodeID: nodeID, + NodeID: nc.nodeID, Payload: msg, Timestamp: time.Now(), - } + }) +} +func (nc *natsCoordinator) publishToNode(nodeID string, coordMsg *CoordinatorMessage) error { data, err := json.Marshal(coordMsg) if err != nil { return fmt.Errorf("failed to marshal message: %w", err) } - subject := "streaming.broadcast.node." + nodeID - _, err = nc.js.Publish(subject, data) + _, err = nc.js.Publish("streaming.broadcast.node."+nodeID, data) return err } @@ -190,9 +185,17 @@ func (nc *natsCoordinator) BroadcastToUser(ctx context.Context, userID string, m return err } - // Broadcast to each node + // Broadcast to each node, naming the user. Without UserID the receiving + // manager treats a node message as global and would hand one user's + // message to every connection on that node. for _, nodeID := range nodes { - if err := nc.BroadcastToNode(ctx, nodeID, msg); err != nil { + if err := nc.publishToNode(nodeID, &CoordinatorMessage{ + Type: MessageTypeBroadcast, + NodeID: nc.nodeID, + UserID: userID, + Payload: msg, + Timestamp: time.Now(), + }); err != nil { // Log error but continue continue } @@ -205,6 +208,7 @@ func (nc *natsCoordinator) BroadcastToUser(ctx context.Context, userID string, m func (nc *natsCoordinator) BroadcastToRoom(ctx context.Context, roomID string, msg *streaming.Message) error { coordMsg := &CoordinatorMessage{ Type: MessageTypeBroadcast, + NodeID: nc.nodeID, RoomID: roomID, Payload: msg, Timestamp: time.Now(), @@ -221,10 +225,12 @@ func (nc *natsCoordinator) BroadcastToRoom(ctx context.Context, roomID string, m return err } -// BroadcastGlobal sends to all nodes. +// BroadcastGlobal sends to all nodes. NodeID names the sender so it skips its +// own message, as on Redis; it has already delivered locally. func (nc *natsCoordinator) BroadcastGlobal(ctx context.Context, msg *streaming.Message) error { coordMsg := &CoordinatorMessage{ Type: MessageTypeBroadcast, + NodeID: nc.nodeID, Payload: msg, Timestamp: time.Now(), } @@ -243,6 +249,7 @@ func (nc *natsCoordinator) BroadcastGlobal(ctx context.Context, msg *streaming.M func (nc *natsCoordinator) SyncPresence(ctx context.Context, presence *streaming.UserPresence) error { coordMsg := &CoordinatorMessage{ Type: MessageTypePresenceUpdate, + NodeID: nc.nodeID, UserID: presence.UserID, Payload: presence, Timestamp: time.Now(), @@ -263,6 +270,7 @@ func (nc *natsCoordinator) SyncPresence(ctx context.Context, presence *streaming func (nc *natsCoordinator) SyncRoomState(ctx context.Context, roomID string, state *RoomState) error { coordMsg := &CoordinatorMessage{ Type: MessageTypeRoomStateSync, + NodeID: nc.nodeID, RoomID: roomID, Payload: state, Timestamp: time.Now(), @@ -420,11 +428,8 @@ func (nc *natsCoordinator) UnregisterNode(ctx context.Context, nodeID string) er return err } -// PublishEvent implements EventPublisher on the global subject. -// -// Note that the global subject is consumed through the "streaming-workers" -// queue group, so today one node rather than every node receives each global -// message. That limits this event exactly as it limits BroadcastGlobal. +// PublishEvent implements EventPublisher on the global subject, which every +// node subscribes to. func (nc *natsCoordinator) PublishEvent(ctx context.Context, msg *CoordinatorMessage) error { if msg.NodeID == "" { msg.NodeID = nc.nodeID diff --git a/extensions/streaming/coordinator/nats_test.go b/extensions/streaming/coordinator/nats_test.go new file mode 100644 index 000000000..0af58ebaf --- /dev/null +++ b/extensions/streaming/coordinator/nats_test.go @@ -0,0 +1,235 @@ +package coordinator + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/nats-io/nats-server/v2/server" + nats "github.com/nats-io/nats.go" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +// runNATS starts an embedded NATS server with JetStream on a random port. +func runNATS(t *testing.T) string { + t.Helper() + + srv, err := server.NewServer(&server.Options{ + Host: "127.0.0.1", + Port: -1, + JetStream: true, + StoreDir: t.TempDir(), + NoLog: true, + NoSigs: true, + }) + if err != nil { + t.Fatal(err) + } + + go srv.Start() + + if !srv.ReadyForConnections(10 * time.Second) { + t.Fatal("embedded NATS server did not start") + } + + t.Cleanup(srv.Shutdown) + + return srv.ClientURL() +} + +// natsNode is one coordinator plus everything its handler received. +type natsNode struct { + id string + coord StreamCoordinator + + mu sync.Mutex + msgs []*CoordinatorMessage +} + +func (n *natsNode) received() []*CoordinatorMessage { + n.mu.Lock() + defer n.mu.Unlock() + + return append([]*CoordinatorMessage(nil), n.msgs...) +} + +// count returns how many received messages match. +func (n *natsNode) count(match func(*CoordinatorMessage) bool) int { + c := 0 + + for _, m := range n.received() { + if match(m) { + c++ + } + } + + return c +} + +func startNATSNode(t *testing.T, url, nodeID string) *natsNode { + t.Helper() + + conn, err := nats.Connect(url) + if err != nil { + t.Fatal(err) + } + + t.Cleanup(conn.Close) + + coord, err := NewNATSCoordinator(conn, nodeID) + if err != nil { + t.Fatal(err) + } + + n := &natsNode{id: nodeID, coord: coord} + + if err := coord.Subscribe(context.Background(), func(_ context.Context, msg *CoordinatorMessage) error { + n.mu.Lock() + defer n.mu.Unlock() + + n.msgs = append(n.msgs, msg) + + return nil + }); err != nil { + t.Fatal(err) + } + + if err := coord.Start(context.Background()); err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = coord.Stop(context.Background()) }) + + return n +} + +func payloadID(m *CoordinatorMessage) string { + if sm, ok := m.Payload.(*streaming.Message); ok { + return sm.ID + } + + return "" +} + +// waitCount polls until every node has exactly want matching messages, then +// holds a moment longer to catch late duplicates. +func waitCount(t *testing.T, what string, nodes []*natsNode, want int, match func(*CoordinatorMessage) bool) { + t.Helper() + + deadline := time.Now().Add(5 * time.Second) + + for time.Now().Before(deadline) { + done := true + + for _, n := range nodes { + if n.count(match) < want { + done = false + } + } + + if done { + break + } + + time.Sleep(10 * time.Millisecond) + } + + time.Sleep(200 * time.Millisecond) + + for _, n := range nodes { + if got := n.count(match); got != want { + t.Errorf("%s: node %s received %d, want %d", what, n.id, got, want) + } + } +} + +// The NATS coordinator consumed every subject through one queue group, so a +// global broadcast or ban event reached one node instead of all of them, and +// BroadcastGlobal carried no sender, so the sender handled its own message. +func TestNATSCoordinator_FanOutReachesEveryNode(t *testing.T) { + url := runNATS(t) + ctx := context.Background() + + a := startNATSNode(t, url, "node-a") + b := startNATSNode(t, url, "node-b") + c := startNATSNode(t, url, "node-c") + others := []*natsNode{b, c} + + isID := func(id string) func(*CoordinatorMessage) bool { + return func(m *CoordinatorMessage) bool { return payloadID(m) == id } + } + + // Global broadcast: every other node once, the sender never. + if err := a.coord.BroadcastGlobal(ctx, &streaming.Message{ID: "g1", Type: streaming.MessageTypeMessage}); err != nil { + t.Fatal(err) + } + + waitCount(t, "global broadcast", others, 1, isID("g1")) + waitCount(t, "global broadcast echo", []*natsNode{a}, 0, isID("g1")) + + for _, m := range b.received() { + if payloadID(m) == "g1" && m.NodeID != "node-a" { + t.Errorf("global broadcast NodeID = %q, want the sender node-a", m.NodeID) + } + } + + // Ban event: same. + pub, ok := a.coord.(EventPublisher) + if !ok { + t.Fatal("NATS coordinator does not implement EventPublisher") + } + + if err := pub.PublishEvent(ctx, &CoordinatorMessage{ + Type: MessageTypeRoomBan, UserID: "alice", RoomID: "lobby", Payload: &RoomBanEvent{Reason: "spam"}, + }); err != nil { + t.Fatal(err) + } + + isBan := func(m *CoordinatorMessage) bool { + ev, ok := m.Payload.(*RoomBanEvent) + + return m.Type == MessageTypeRoomBan && ok && ev.Reason == "spam" && m.UserID == "alice" && m.RoomID == "lobby" + } + + waitCount(t, "ban event", others, 1, isBan) + waitCount(t, "ban event echo", []*natsNode{a}, 0, isBan) + + // Room broadcasts had no subscriber at all. + if err := a.coord.BroadcastToRoom(ctx, "lobby", &streaming.Message{ID: "r1", RoomID: "lobby"}); err != nil { + t.Fatal(err) + } + + waitCount(t, "room broadcast", others, 1, isID("r1")) + waitCount(t, "room broadcast echo", []*natsNode{a}, 0, isID("r1")) + + // A node message reaches its target only. The target used to drop it, + // because NodeID carried the target and matched its own id. + if err := a.coord.BroadcastToNode(ctx, "node-b", &streaming.Message{ID: "n1"}); err != nil { + t.Fatal(err) + } + + waitCount(t, "node message", []*natsNode{b}, 1, isID("n1")) + waitCount(t, "node message to others", []*natsNode{a, c}, 0, isID("n1")) +} + +// A node that starts late must not replay the retained backlog as live. +func TestNATSCoordinator_NewNodeDoesNotReplayBacklog(t *testing.T) { + url := runNATS(t) + ctx := context.Background() + + a := startNATSNode(t, url, "node-a") + + if err := a.coord.BroadcastGlobal(ctx, &streaming.Message{ID: "old"}); err != nil { + t.Fatal(err) + } + + late := startNATSNode(t, url, "node-late") + + if err := a.coord.BroadcastGlobal(ctx, &streaming.Message{ID: "new"}); err != nil { + t.Fatal(err) + } + + waitCount(t, "live message", []*natsNode{late}, 1, func(m *CoordinatorMessage) bool { return payloadID(m) == "new" }) + waitCount(t, "backlog", []*natsNode{late}, 0, func(m *CoordinatorMessage) bool { return payloadID(m) == "old" }) +} diff --git a/extensions/streaming/coordinator/redis.go b/extensions/streaming/coordinator/redis.go index d4aa08f0f..7f99ec940 100644 --- a/extensions/streaming/coordinator/redis.go +++ b/extensions/streaming/coordinator/redis.go @@ -74,22 +74,26 @@ func (rc *redisCoordinator) Stop(ctx context.Context) error { } // BroadcastToNode sends message to specific node. +// +// NodeID is the sender and the channel carries the target. It used to be the +// target, so the target's own-message check matched and it dropped every +// message addressed to it. func (rc *redisCoordinator) BroadcastToNode(ctx context.Context, nodeID string, msg *streaming.Message) error { - coordMsg := &CoordinatorMessage{ + return rc.publishToNode(ctx, nodeID, &CoordinatorMessage{ Type: MessageTypeBroadcast, - NodeID: nodeID, + NodeID: rc.nodeID, Payload: msg, Timestamp: time.Now(), - } + }) +} +func (rc *redisCoordinator) publishToNode(ctx context.Context, nodeID string, coordMsg *CoordinatorMessage) error { data, err := json.Marshal(coordMsg) if err != nil { return fmt.Errorf("failed to marshal message: %w", err) } - channel := "streaming:broadcast:node:" + nodeID - - return rc.client.Publish(ctx, channel, data).Err() + return rc.client.Publish(ctx, "streaming:broadcast:node:"+nodeID, data).Err() } // BroadcastToUser sends to user across all nodes. @@ -100,9 +104,17 @@ func (rc *redisCoordinator) BroadcastToUser(ctx context.Context, userID string, return err } - // Broadcast to each node + // Broadcast to each node, naming the user. Without UserID the receiving + // manager treats a node message as global and would hand one user's + // message to every connection on that node. for _, nodeID := range nodes { - if err := rc.BroadcastToNode(ctx, nodeID, msg); err != nil { + if err := rc.publishToNode(ctx, nodeID, &CoordinatorMessage{ + Type: MessageTypeBroadcast, + NodeID: rc.nodeID, + UserID: userID, + Payload: msg, + Timestamp: time.Now(), + }); err != nil { // Log error but continue continue } diff --git a/extensions/streaming/go.mod b/extensions/streaming/go.mod index b3e61ce89..f05bbc3e3 100644 --- a/extensions/streaming/go.mod +++ b/extensions/streaming/go.mod @@ -6,8 +6,10 @@ retract v1.12.1 // tagged at the wrong commit by a manual release run on 2026-10 require ( github.com/alicebob/miniredis/v2 v2.35.0 + github.com/gobwas/ws v1.4.0 github.com/google/uuid v1.6.0 - github.com/nats-io/nats.go v1.47.0 + github.com/nats-io/nats-server/v2 v2.14.8 + github.com/nats-io/nats.go v1.53.1 github.com/redis/go-redis/v9 v9.21.0 github.com/xraph/forge v1.12.9 github.com/xraph/forge/extensions/auth v1.12.9 @@ -16,6 +18,7 @@ require ( require ( github.com/BurntSushi/toml v1.6.0 // indirect + github.com/antithesishq/antithesis-sdk-go v0.8.0-default-no-op // indirect github.com/armon/go-metrics v0.4.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect @@ -50,8 +53,8 @@ require ( github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/gobwas/httphead v0.1.0 // indirect github.com/gobwas/pool v0.2.1 // indirect - github.com/gobwas/ws v1.4.0 // indirect github.com/google/gnostic-models v0.7.1 // indirect + github.com/google/go-tpm v0.9.8 // indirect github.com/grafana/pyroscope-go v1.4.3 // indirect github.com/grafana/pyroscope-go/godeltaprof v0.1.11 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect @@ -66,15 +69,17 @@ require ( github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/hashicorp/serf v0.10.4 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.19.1 // indirect + github.com/klauspost/compress v1.20.1 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/mattn/go-colorable v0.1.15 // indirect github.com/mattn/go-isatty v0.0.24 // indirect + github.com/minio/highwayhash v1.0.4 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/nats-io/nkeys v0.4.11 // indirect + github.com/nats-io/jwt/v2 v2.8.2 // indirect + github.com/nats-io/nkeys v0.4.16 // indirect github.com/nats-io/nuid v1.0.1 // indirect github.com/prometheus/client_golang v1.24.1 // indirect github.com/prometheus/client_model v0.6.2 // indirect @@ -113,7 +118,7 @@ require ( golang.org/x/sys v0.48.0 // indirect golang.org/x/term v0.46.0 // indirect golang.org/x/text v0.42.0 // indirect - golang.org/x/time v0.15.0 // indirect + golang.org/x/time v0.16.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect google.golang.org/grpc v1.83.2 // indirect diff --git a/extensions/streaming/go.sum b/extensions/streaming/go.sum index 1f87fa575..144f832ed 100644 --- a/extensions/streaming/go.sum +++ b/extensions/streaming/go.sum @@ -7,6 +7,8 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI= github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= +github.com/antithesishq/antithesis-sdk-go v0.8.0-default-no-op h1:1BOWQJweNyvZMlpAHXGLiZQn9S+QXGcz3xh94lC0w6E= +github.com/antithesishq/antithesis-sdk-go v0.8.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI= github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= @@ -41,8 +43,6 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5 github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/fxamacker/cbor/v2 v2.9.2 h1:X4Ksno9+x3cz0TZv69ec1hxP/+tymuR8PXQJyDwfh78= github.com/fxamacker/cbor/v2 v2.9.2/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI= -github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= @@ -119,6 +119,8 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo= +github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -171,8 +173,8 @@ github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/u github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -199,6 +201,8 @@ github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= +github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4= +github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -212,10 +216,14 @@ github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWu github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/nats-io/nats.go v1.47.0 h1:YQdADw6J/UfGUd2Oy6tn4Hq6YHxCaJrVKayxxFqYrgM= -github.com/nats-io/nats.go v1.47.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g= -github.com/nats-io/nkeys v0.4.11 h1:q44qGV008kYd9W1b1nEBkNzvnWxtRSQ7A8BoqRrcfa0= -github.com/nats-io/nkeys v0.4.11/go.mod h1:szDimtgmfOi9n25JpfIdGw12tZFYXqhGxjhVxsatHVE= +github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc= +github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc= +github.com/nats-io/nats-server/v2 v2.14.8 h1:EWd82pDFZ05U3iMS68LRgbNzgi4JB5Er93JpWHA5ng8= +github.com/nats-io/nats-server/v2 v2.14.8/go.mod h1:8lHkzklmT09g8/Vb3I6uQMtuGjDQ3e9DRHb5Ietg7Z8= +github.com/nats-io/nats.go v1.53.1 h1:Otsq3uLc/kLdjmkNHkXH0jBqwUquwdKFoe3fq6/3/Xo= +github.com/nats-io/nats.go v1.53.1/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno= +github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= +github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= @@ -363,6 +371,7 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= @@ -370,8 +379,8 @@ golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= -golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/extensions/streaming/manager.go b/extensions/streaming/manager.go index 926fe2d68..fa94acfb7 100644 --- a/extensions/streaming/manager.go +++ b/extensions/streaming/manager.go @@ -71,8 +71,10 @@ type manager struct { hooks *HookRegistry codecs *CodecRegistry - // Message deduplication for distributed mode - dedup *messageDedup + // Message deduplication for distributed mode. Atomic because the + // coordinator's listener goroutine reads it while Stop swaps it out: a + // message in flight when the node stops raced with the plain field. + dedup atomic.Pointer[messageDedup] // Connection registry connections map[string]Connection // connID -> connection @@ -2013,7 +2015,7 @@ func (m *manager) Start(ctx context.Context) error { // Initialize message deduplication for distributed mode if m.coordinator != nil { - m.dedup = newMessageDedup(10000, 30*time.Second) + m.dedup.Store(newMessageDedup(10000, 30*time.Second)) } // Start coordinator if enabled @@ -2195,9 +2197,8 @@ func (m *manager) Stop(ctx context.Context) error { // in-memory session store run an unstoppable ticker loop until closed, so // without this every start/stop cycle leaked one of each — most visibly in // tests, which construct and discard managers repeatedly. - if m.dedup != nil { - _ = m.dedup.Close() - m.dedup = nil + if d := m.dedup.Swap(nil); d != nil { + _ = d.Close() } if closer, ok := m.sessionStore.(interface{ Close() error }); ok && m.sessionStore != nil { @@ -3631,8 +3632,8 @@ func (m *manager) handleCoordinatorMessage(ctx context.Context, msg *coordinator } // Check message-ID-level dedup (same message may arrive via multiple paths) - if m.dedup != nil && streamMsg.ID != "" { - if m.dedup.IsDuplicate(streamMsg.ID) { + if d := m.dedup.Load(); d != nil && streamMsg.ID != "" { + if d.IsDuplicate(streamMsg.ID) { return nil } } diff --git a/extensions/streaming/nats_cluster_test.go b/extensions/streaming/nats_cluster_test.go new file mode 100644 index 000000000..cdb142dc4 --- /dev/null +++ b/extensions/streaming/nats_cluster_test.go @@ -0,0 +1,133 @@ +package streaming + +import ( + "context" + "testing" + "time" + + "github.com/nats-io/nats-server/v2/server" + nats "github.com/nats-io/nats.go" + streamauth "github.com/xraph/forge/extensions/streaming/auth" + "github.com/xraph/forge/extensions/streaming/backends/local" + "github.com/xraph/forge/extensions/streaming/coordinator" + streaming "github.com/xraph/forge/extensions/streaming/internal" +) + +func runEmbeddedNATS(t *testing.T) string { + t.Helper() + + srv, err := server.NewServer(&server.Options{ + Host: "127.0.0.1", Port: -1, JetStream: true, StoreDir: t.TempDir(), NoLog: true, NoSigs: true, + }) + if err != nil { + t.Fatal(err) + } + + go srv.Start() + + if !srv.ReadyForConnections(10 * time.Second) { + t.Fatal("embedded NATS server did not start") + } + + t.Cleanup(srv.Shutdown) + + return srv.ClientURL() +} + +// newNATSNode builds a started manager on a NATS coordinator. The room store +// is shared, standing in for the shared store a real cluster uses. +func newNATSNode(t *testing.T, url, nodeID string, rooms streaming.RoomStore) Manager { + t.Helper() + + conn, err := nats.Connect(url) + if err != nil { + t.Fatal(err) + } + + t.Cleanup(conn.Close) + + coord, err := coordinator.NewNATSCoordinator(conn, nodeID) + if err != nil { + t.Fatal(err) + } + + cfg := DefaultConfig() + cfg.NodeID = nodeID + + msgs := local.NewMessageStore() + ra := streamauth.NewRoomAuthorizer(rooms) + + m := NewManager(cfg, rooms, local.NewChannelStore(), msgs, + newFakePresenceTracker(), newFakeTypingTracker(), nil, nil, nil, + WithRoomAuthorizer(ra), + WithMessageAuthorizer(streamauth.NewMessageAuthorizer(ra, newAuthMessageStore(msgs))), + WithCoordinator(coord), + WithManagerNodeID(nodeID), + ) + + ctx, cancel := context.WithCancel(context.Background()) + + if err := m.Start(ctx); err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { + _ = m.Stop(context.Background()) + + cancel() + }) + + return m +} + +// End to end on NATS: a global broadcast reaches clients on every node +// exactly once, including the sender's own clients, and a ban issued on one +// node takes the user out of the room on another. +func TestNATSCluster_GlobalBroadcastAndBan(t *testing.T) { + url := runEmbeddedNATS(t) + ctx := context.Background() + + rooms := local.NewRoomStore() + assertNoError(t, rooms.Create(ctx, local.NewRoom(streaming.RoomOptions{ID: "lobby", Name: "lobby", Owner: "o"}))) + + nodeA := newNATSNode(t, url, "node-a", rooms) + nodeB := newNATSNode(t, url, "node-b", rooms) + + bob := newTestConn("bob-1", "bob") + alice := newTestConn("alice-1", "alice") + carol := newTestConn("carol-1", "carol") + + assertNoError(t, nodeA.Register(bob)) + assertNoError(t, nodeA.JoinRoom(ctx, bob.ID(), "lobby")) + + for _, c := range []*testConn{alice, carol} { + assertNoError(t, nodeB.Register(c)) + assertNoError(t, nodeB.JoinRoom(ctx, c.ID(), "lobby")) + } + + assertNoError(t, nodeA.Broadcast(ctx, &Message{ID: newMessageID(), Type: MessageTypeMessage, Data: "everyone"})) + + eventually(t, "node B clients to get the global broadcast", func() bool { + return receivedData(alice, "everyone") && receivedData(carol, "everyone") + }) + + // Give any echo of node A's own message time to arrive. + time.Sleep(200 * time.Millisecond) + + for _, c := range []*testConn{bob, alice, carol} { + c.waitQuiet(t) + + if n := countData(c, "everyone"); n != 1 { + t.Errorf("%s received the global broadcast %d times, want 1", c.ID(), n) + } + } + + assertNoError(t, nodeA.BanUser(ctx, "alice", "lobby", "spam", nil)) + + eventually(t, "node B to take alice out of the room", func() bool { return !alice.IsInRoom("lobby") }) + eventually(t, "alice's room.banned notice", func() bool { return receivedLifecycle(alice, "room.banned") }) + + if !carol.IsInRoom("lobby") { + t.Fatal("the ban took an unrelated user out of the room") + } +} diff --git a/extensions/streaming/room_ban_distributed_test.go b/extensions/streaming/room_ban_distributed_test.go index 245a539c1..fa0687af6 100644 --- a/extensions/streaming/room_ban_distributed_test.go +++ b/extensions/streaming/room_ban_distributed_test.go @@ -257,3 +257,40 @@ func TestHandleRoomBan_IgnoresExpiredBan(t *testing.T) { t.Fatal("an expired ban event evicted the user") } } + +// A user-targeted message relayed over Redis used to be dropped by the target +// node, because BroadcastToNode put the target's id in NodeID and the target +// took it for its own message. It also carried no UserID, so once delivered +// it would have gone to every connection on that node. +func TestSendToUser_ReachesUserOnAnotherNodeOnly(t *testing.T) { + srv := miniredis.RunT(t) + ctx := context.Background() + + shared := goredis.NewClient(&goredis.Options{Addr: srv.Addr()}) + + t.Cleanup(func() { _ = shared.Close() }) + + rooms := redisbackend.NewRoomStore(shared, "cluster:rooms") + + nodeA := newClusterNode(t, srv.Addr(), "node-a", rooms) + nodeB := newClusterNode(t, srv.Addr(), "node-b", rooms) + + alice := newTestConn("alice-1", "alice") + carol := newTestConn("carol-1", "carol") + + for _, c := range []*testConn{alice, carol} { + assertNoError(t, nodeB.Register(c)) + } + + eventually(t, "alice's message to arrive on node B", func() bool { + _ = nodeA.SendToUser(ctx, "alice", &Message{ID: newMessageID(), Type: MessageTypeMessage, Data: "for alice"}) + + return receivedData(alice, "for alice") + }) + + carol.waitQuiet(t) + + if receivedData(carol, "for alice") { + t.Fatal("a message for alice was delivered to carol on the same node") + } +} From 0efd25872936578ac68871697bf575a9be6914da Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 17 Nov 2026 18:28:01 -0600 Subject: [PATCH 16/17] build(deps): update modules that build streaming from the local checkout extensions/webrtc and examples/webtransport build the streaming extension through a replace directive. The NATS fix added nats-server as a test dependency of streaming, which raised nats.go to v1.53.1, nkeys to v0.4.16, klauspost/compress to v1.20.1 and x/time to v0.16.0. Both modules needed the same versions, so CI failed to build them with "go: updates to go.mod needed". --- examples/webtransport/go.mod | 8 ++++---- examples/webtransport/go.sum | 26 ++++++++++++++++++-------- extensions/webrtc/go.mod | 8 ++++---- extensions/webrtc/go.sum | 26 ++++++++++++++++++-------- 4 files changed, 44 insertions(+), 24 deletions(-) diff --git a/examples/webtransport/go.mod b/examples/webtransport/go.mod index 9add06d6a..05343d3e0 100644 --- a/examples/webtransport/go.mod +++ b/examples/webtransport/go.mod @@ -64,7 +64,7 @@ require ( github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/hashicorp/serf v0.10.4 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.19.1 // indirect + github.com/klauspost/compress v1.20.1 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/mattn/go-colorable v0.1.15 // indirect github.com/mattn/go-isatty v0.0.24 // indirect @@ -72,8 +72,8 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/nats-io/nats.go v1.47.0 // indirect - github.com/nats-io/nkeys v0.4.11 // indirect + github.com/nats-io/nats.go v1.53.1 // indirect + github.com/nats-io/nkeys v0.4.16 // indirect github.com/nats-io/nuid v1.0.1 // indirect github.com/prometheus/client_golang v1.24.1 // indirect github.com/prometheus/client_model v0.6.2 // indirect @@ -114,7 +114,7 @@ require ( golang.org/x/sys v0.48.0 // indirect golang.org/x/term v0.46.0 // indirect golang.org/x/text v0.42.0 // indirect - golang.org/x/time v0.15.0 // indirect + golang.org/x/time v0.16.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect google.golang.org/grpc v1.83.2 // indirect diff --git a/examples/webtransport/go.sum b/examples/webtransport/go.sum index 3e588b7bb..56de64ba8 100644 --- a/examples/webtransport/go.sum +++ b/examples/webtransport/go.sum @@ -7,6 +7,8 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI= github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= +github.com/antithesishq/antithesis-sdk-go v0.8.0-default-no-op h1:1BOWQJweNyvZMlpAHXGLiZQn9S+QXGcz3xh94lC0w6E= +github.com/antithesishq/antithesis-sdk-go v0.8.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI= github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= @@ -119,6 +121,8 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo= +github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -171,8 +175,8 @@ github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/u github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -199,6 +203,8 @@ github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= +github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4= +github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -212,10 +218,14 @@ github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWu github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/nats-io/nats.go v1.47.0 h1:YQdADw6J/UfGUd2Oy6tn4Hq6YHxCaJrVKayxxFqYrgM= -github.com/nats-io/nats.go v1.47.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g= -github.com/nats-io/nkeys v0.4.11 h1:q44qGV008kYd9W1b1nEBkNzvnWxtRSQ7A8BoqRrcfa0= -github.com/nats-io/nkeys v0.4.11/go.mod h1:szDimtgmfOi9n25JpfIdGw12tZFYXqhGxjhVxsatHVE= +github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc= +github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc= +github.com/nats-io/nats-server/v2 v2.14.8 h1:EWd82pDFZ05U3iMS68LRgbNzgi4JB5Er93JpWHA5ng8= +github.com/nats-io/nats-server/v2 v2.14.8/go.mod h1:8lHkzklmT09g8/Vb3I6uQMtuGjDQ3e9DRHb5Ietg7Z8= +github.com/nats-io/nats.go v1.53.1 h1:Otsq3uLc/kLdjmkNHkXH0jBqwUquwdKFoe3fq6/3/Xo= +github.com/nats-io/nats.go v1.53.1/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno= +github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= +github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= @@ -370,8 +380,8 @@ golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= -golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/extensions/webrtc/go.mod b/extensions/webrtc/go.mod index 2b4483f80..0f57e6bce 100644 --- a/extensions/webrtc/go.mod +++ b/extensions/webrtc/go.mod @@ -65,7 +65,7 @@ require ( github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/hashicorp/serf v0.10.4 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.19.1 // indirect + github.com/klauspost/compress v1.20.1 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/mattn/go-colorable v0.1.15 // indirect github.com/mattn/go-isatty v0.0.24 // indirect @@ -73,8 +73,8 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/nats-io/nats.go v1.47.0 // indirect - github.com/nats-io/nkeys v0.4.11 // indirect + github.com/nats-io/nats.go v1.53.1 // indirect + github.com/nats-io/nkeys v0.4.16 // indirect github.com/nats-io/nuid v1.0.1 // indirect github.com/pion/datachannel v1.6.2 // indirect github.com/pion/dtls/v3 v3.1.5 // indirect @@ -129,7 +129,7 @@ require ( golang.org/x/sys v0.48.0 // indirect golang.org/x/term v0.46.0 // indirect golang.org/x/text v0.42.0 // indirect - golang.org/x/time v0.15.0 // indirect + golang.org/x/time v0.16.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect google.golang.org/grpc v1.83.2 // indirect diff --git a/extensions/webrtc/go.sum b/extensions/webrtc/go.sum index 1b97439bd..ae098d336 100644 --- a/extensions/webrtc/go.sum +++ b/extensions/webrtc/go.sum @@ -7,6 +7,8 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI= github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= +github.com/antithesishq/antithesis-sdk-go v0.8.0-default-no-op h1:1BOWQJweNyvZMlpAHXGLiZQn9S+QXGcz3xh94lC0w6E= +github.com/antithesishq/antithesis-sdk-go v0.8.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI= github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= @@ -119,6 +121,8 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo= +github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -171,8 +175,8 @@ github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/u github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -199,6 +203,8 @@ github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= +github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4= +github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -212,10 +218,14 @@ github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWu github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/nats-io/nats.go v1.47.0 h1:YQdADw6J/UfGUd2Oy6tn4Hq6YHxCaJrVKayxxFqYrgM= -github.com/nats-io/nats.go v1.47.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g= -github.com/nats-io/nkeys v0.4.11 h1:q44qGV008kYd9W1b1nEBkNzvnWxtRSQ7A8BoqRrcfa0= -github.com/nats-io/nkeys v0.4.11/go.mod h1:szDimtgmfOi9n25JpfIdGw12tZFYXqhGxjhVxsatHVE= +github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc= +github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc= +github.com/nats-io/nats-server/v2 v2.14.8 h1:EWd82pDFZ05U3iMS68LRgbNzgi4JB5Er93JpWHA5ng8= +github.com/nats-io/nats-server/v2 v2.14.8/go.mod h1:8lHkzklmT09g8/Vb3I6uQMtuGjDQ3e9DRHb5Ietg7Z8= +github.com/nats-io/nats.go v1.53.1 h1:Otsq3uLc/kLdjmkNHkXH0jBqwUquwdKFoe3fq6/3/Xo= +github.com/nats-io/nats.go v1.53.1/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno= +github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= +github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= @@ -406,8 +416,8 @@ golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= -golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= From b920aa72063ccdd82d5796116c6a9448173896cc Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 17 Nov 2026 18:28:01 -0600 Subject: [PATCH 17/17] test(streaming): use t.Context in the channel authorization test --- extensions/streaming/channel_auth_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/extensions/streaming/channel_auth_test.go b/extensions/streaming/channel_auth_test.go index dcfd35d03..371a0d915 100644 --- a/extensions/streaming/channel_auth_test.go +++ b/extensions/streaming/channel_auth_test.go @@ -165,8 +165,7 @@ func TestHandleSSE_AnonymousChannelsParamIsRefused(t *testing.T) { srv := httptest.NewServer(app.Router().(http.Handler)) defer srv.Close() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() if err := ext.Manager().CreateChannel(ctx, local.NewLocalChannel(streaming.ChannelOptions{ ID: "user-42-notifications", Name: "n", Private: true,