Add configurable read-message size limit on signalling WebSockets (#4743)

* Add configurable read-message size limit on signalling WebSockets

Set a read limit on both the client-facing (/rtc) and agent worker
WebSocket connections so an oversized frame is rejected by the transport
before being buffered. The limits are operator-tunable via
signal_message_size_limit and agent_signal_message_size_limit, both
defaulting to 2 MiB (0 disables).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add tests for signalling WebSocket read-message size limit

Cover the configurable signal_message_size_limit added in the prior
commit:
- config: assert both limits default to 2 MiB and that a YAML override
  (including 0 to disable) is parsed correctly.
- full-path integration: a real client connects to /rtc on a single-node
  server and an oversized frame is rejected by the transport with a 1009
  close; a 0 limit leaves the connection unbounded and signalling
  proceeds.

Adds setupSingleNodeTestWithConfig so a single-node server can be started
with config overrides.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Bound decompressed size of signalling WebSocket messages

conn.SetReadLimit only accounts for the compressed bytes read off the
wire, and the client-facing /rtc upgrader negotiates permessage-deflate,
so a small compressed frame could still expand into a much larger buffer
once inflated. Enforce the same limit on the decompressed message by
reading through NextReader + io.LimitReader in WSSignalConnection instead
of the unbounded ReadMessage.

The transport-level SetReadLimit is kept as the cheap wire-level guard;
the new check is the decompressed-size backstop.

Adds NextReader to the WebsocketClient interface (regenerated fake) and a
unit test plus permessage-deflate integration tests covering the
amplification case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Raja Subramanian
2026-08-12 12:07:26 +05:30
committed by GitHub
co-authored by Claude Opus 4.8
parent fad2cc4afe
commit 3c6e56232e
11 changed files with 473 additions and 10 deletions
+13 -2
View File
@@ -131,6 +131,8 @@ func HandshakeAgentWorker(c agent.SignalConn, serverInfo *livekit.ServerInfo, re
type AgentService struct {
upgrader AgentSocketUpgrader
signalMessageSizeLimit int64
*AgentHandler
}
@@ -170,7 +172,9 @@ func NewAgentService(
bus psrpc.MessageBus,
keyProvider auth.KeyProvider,
) (*AgentService, error) {
s := &AgentService{}
s := &AgentService{
signalMessageSizeLimit: conf.Limit.AgentSignalMessageSizeLimit,
}
serverInfo := &livekit.ServerInfo{
Edition: livekit.ServerInfo_Standard,
@@ -200,7 +204,14 @@ func NewAgentService(
func (s *AgentService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if conn, registration, ok := s.upgrader.Upgrade(w, r, nil); ok {
s.HandleConnection(r.Context(), NewWSSignalConnection(conn), registration)
// bound the size of a single signalling frame so an oversized message is
// rejected by the transport before being fully buffered in memory. This
// limits the compressed bytes read off the wire; the decompressed size is
// bounded separately in WSSignalConnection.
if s.signalMessageSizeLimit > 0 {
conn.SetReadLimit(s.signalMessageSizeLimit)
}
s.HandleConnection(r.Context(), NewWSSignalConnection(conn, s.signalMessageSizeLimit), registration)
conn.Close()
}
}
+8 -1
View File
@@ -447,6 +447,13 @@ func (s *RTCService) serve(w http.ResponseWriter, r *http.Request, needsJoinRequ
HandleError(w, r, http.StatusInternalServerError, err, getLoggerFields()...)
return
}
// bound the size of a single signalling frame so an oversized message is
// rejected by the transport before being fully buffered in memory. This limits
// the compressed bytes read off the wire; the decompressed size is bounded
// separately in WSSignalConnection below.
if s.limits.SignalMessageSizeLimit > 0 {
conn.SetReadLimit(s.limits.SignalMessageSizeLimit)
}
s.mu.Lock()
s.connections[conn] = struct{}{}
@@ -459,7 +466,7 @@ func (s *RTCService) serve(w http.ResponseWriter, r *http.Request, needsJoinRequ
}()
// websocket established
sigConn := NewWSSignalConnection(conn)
sigConn := NewWSSignalConnection(conn, s.limits.SignalMessageSizeLimit)
pLogger.Debugw("sending initial response", "response", logger.Proto(initialResponse))
count, err := sigConn.WriteResponse(initialResponse)
if err != nil {
+40 -6
View File
@@ -16,6 +16,7 @@ package service
import (
"errors"
"fmt"
"io"
"strings"
"sync"
@@ -41,18 +42,51 @@ type WSSignalConnection struct {
conn types.WebsocketClient
mu sync.Mutex
useJSON bool
// maximum size (in bytes) of a single decompressed message; 0 disables the limit
messageSizeLimit int64
}
func NewWSSignalConnection(conn types.WebsocketClient) *WSSignalConnection {
func NewWSSignalConnection(conn types.WebsocketClient, messageSizeLimit int64) *WSSignalConnection {
wsc := &WSSignalConnection{
conn: conn,
mu: sync.Mutex{},
useJSON: false,
conn: conn,
mu: sync.Mutex{},
useJSON: false,
messageSizeLimit: messageSizeLimit,
}
go wsc.pingWorker()
return wsc
}
// readMessage reads a single websocket message, bounding the size of the
// decompressed payload. The transport-level read limit (SetReadLimit) only
// accounts for the compressed bytes read off the wire, so a small compressed
// frame can still expand into a much larger buffer once inflated. Reading through
// an io.LimitReader caps the decompressed size at the same limit.
func (c *WSSignalConnection) readMessage() (int, []byte, error) {
messageType, r, err := c.conn.NextReader()
if err != nil {
return messageType, nil, err
}
if c.messageSizeLimit > 0 {
// read one byte past the limit so an exactly-at-limit message is accepted
// while anything larger is detected and rejected
limited := io.LimitReader(r, c.messageSizeLimit+1)
payload, err := io.ReadAll(limited)
if err != nil {
return messageType, nil, err
}
if int64(len(payload)) > c.messageSizeLimit {
return messageType, nil, fmt.Errorf("signal message exceeds size limit of %d bytes", c.messageSizeLimit)
}
return messageType, payload, nil
}
payload, err := io.ReadAll(r)
return messageType, payload, err
}
func (c *WSSignalConnection) Close() error {
return c.conn.Close()
}
@@ -69,7 +103,7 @@ func (c *WSSignalConnection) SetReadDeadline(deadline time.Time) error {
func (c *WSSignalConnection) ReadRequest() (*livekit.SignalRequest, int, error) {
// handle special messages and pass on the rest
messageType, payload, err := c.conn.ReadMessage()
messageType, payload, err := c.readMessage()
if err != nil {
return nil, 0, err
}
@@ -101,7 +135,7 @@ func (c *WSSignalConnection) ReadRequest() (*livekit.SignalRequest, int, error)
func (c *WSSignalConnection) ReadWorkerMessage() (*livekit.WorkerMessage, int, error) {
// handle special messages and pass on the rest
messageType, payload, err := c.conn.ReadMessage()
messageType, payload, err := c.readMessage()
if err != nil {
return nil, 0, err
}
+74
View File
@@ -0,0 +1,74 @@
// Copyright 2026 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package service_test
import (
"bytes"
"testing"
"github.com/gorilla/websocket"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"github.com/livekit/protocol/livekit"
"github.com/livekit/livekit-server/pkg/rtc/types/typesfakes"
"github.com/livekit/livekit-server/pkg/service"
)
// TestWSSignalConnectionMessageSizeLimit exercises the decompressed-size bound in
// WSSignalConnection. NextReader returns the (already decompressed) message
// stream, so a reader larger than the limit stands in for a small compressed
// frame that expands past the limit once inflated.
func TestWSSignalConnectionMessageSizeLimit(t *testing.T) {
const limit = 1024
t.Run("rejects message larger than limit", func(t *testing.T) {
fake := &typesfakes.FakeWebsocketClient{}
fake.NextReaderReturns(websocket.BinaryMessage, bytes.NewReader(make([]byte, limit+1)), nil)
c := service.NewWSSignalConnection(fake, limit)
_, _, err := c.ReadRequest()
require.Error(t, err)
require.Contains(t, err.Error(), "exceeds size limit")
})
t.Run("accepts message within limit", func(t *testing.T) {
payload, err := proto.Marshal(&livekit.SignalRequest{})
require.NoError(t, err)
require.LessOrEqual(t, len(payload), limit)
fake := &typesfakes.FakeWebsocketClient{}
fake.NextReaderReturns(websocket.BinaryMessage, bytes.NewReader(payload), nil)
c := service.NewWSSignalConnection(fake, limit)
msg, _, err := c.ReadRequest()
require.NoError(t, err)
require.NotNil(t, msg)
})
t.Run("limit of zero reads unbounded payload", func(t *testing.T) {
// a payload well beyond any typical limit is read in full when disabled
payload, err := proto.Marshal(&livekit.SignalRequest{})
require.NoError(t, err)
fake := &typesfakes.FakeWebsocketClient{}
fake.NextReaderReturns(websocket.BinaryMessage, bytes.NewReader(payload), nil)
c := service.NewWSSignalConnection(fake, 0)
_, _, err = c.ReadRequest()
require.NoError(t, err)
})
}