Repository navigation
fix(streaming): stop connection leaks, authorize channels and make bans work - #128
Merged
Merged
Conversation
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.
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.
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.
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.
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.
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.
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
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
…nd 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.
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.
…oses 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.
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.
Contributor
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
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.
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.
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.
Contributor
Conventional Commits ValidationPR Title: valid |
Contributor
Conventional Commits ValidationPR Title: valid |
Contributor
Conventional Commits ValidationPR Title: valid |
Contributor
Conventional Commits ValidationPR Title: valid |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
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".
Contributor
Conventional Commits ValidationPR Title: valid |
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes in
extensions/streamingand the router's WebSocket and WebTransport code, from a security and performance review. Every fix has a regression test.Fixes
Goroutine leak: every WebSocket and SSE connection leaked its send-queue writer, about 19 KB each. Connections are now closed on every exit path.
Channel subscriptions had no authorization, and
Privatewas never enforced. An anonymousGET /sse?channels=user-42-notificationsreceived another user's messages. There is a newChannelAuthorizer, anonymous subscribers are refused by default, and private channels need an authorizer.WebSocket pings were answered outside the write lock, so a pong could land mid-frame and corrupt the stream. Control replies now go out under the lock with a deadline.
Fan-out JSON-encoded a broadcast once per recipient. It now encodes once: a 1,000-member room uses 0.13 MB instead of 1.47 MB.
Relayed room messages scanned every local connection. They now use the room index: about 25 µs with 20,000 connections, instead of 9 to 21 ms.
Locking: Redis calls on connect and disconnect ran under the manager's global lock with no timeout. They now run outside it, with a 2 s timeout.
WebTransport JSON reads had no size cap. They are now capped at 1 MiB, configurable.
Anonymous connections are now rate limited.
Functional bugs:
Last-Event-IDresume never worked.Room bans never worked on the local backend, and the Redis store kept banned users as members and ignored expiry. Bans now work on both backends, evict the user's connections on the banning node, and block rejoin and send everywhere.
Redis room mutes were unimplemented. They now work with expiry, a muted member's sends are refused on both backends, and deleting a Redis room clears its bans and mutes.
Bans on other nodes: a ban is now broadcast through the coordinator, so the banned user's connections are removed on every node immediately, not when they reconnect.
NATS coordinator:
Every node now gets fan-out messages exactly once, without replaying the stream's backlog, and ignores its own.
Node-to-node messages:
SendToUsernever arrived on NATS or Redis, because the target's ID was in the sender field;BroadcastToUserdidn't name the user, which would have delivered one user's message to everyone on the receiving node.Both fixed.
Behaviour changes
WithAnonymousSubscriptions(true)restores them).ChannelAuthorizer.*streaming.Message.nats-server/v2is a new test dependency. It moves nats.go to v1.53.1, klauspost/compress to v1.20.1, nkeys to v0.4.16 and x/time to v0.16.0.BroadcastToUserover NATS reaches no node yet.Testing
go test -race ./...passes inextensions/streaming, and so doesgo test -race ./internal/router/.... golangci-lint is clean.