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:
co-authored by
Claude Opus 4.8
parent
fad2cc4afe
commit
3c6e56232e
@@ -376,3 +376,8 @@ keys:
|
|||||||
# max_room_name_length: 0
|
# max_room_name_length: 0
|
||||||
# # limit length of participant identity
|
# # limit length of participant identity
|
||||||
# max_participant_identity_length: 0
|
# max_participant_identity_length: 0
|
||||||
|
# # max size (bytes) of a single client-facing signalling WebSocket message; oversized
|
||||||
|
# # frames are rejected by the transport before being buffered. defaults to 2 MiB, 0 for no limit
|
||||||
|
# signal_message_size_limit: 2097152
|
||||||
|
# # same as above, but for agent worker WebSocket connections. defaults to 2 MiB, 0 for no limit
|
||||||
|
# agent_signal_message_size_limit: 2097152
|
||||||
|
|||||||
@@ -337,6 +337,14 @@ type LimitConfig struct {
|
|||||||
MaxDataBlobSize uint32 `yaml:"max_data_blobs_size,omitempty"`
|
MaxDataBlobSize uint32 `yaml:"max_data_blobs_size,omitempty"`
|
||||||
|
|
||||||
MaxDataTrackCustomEncodingLength int `yaml:"max_data_track_custom_encoding_length,omitempty"`
|
MaxDataTrackCustomEncodingLength int `yaml:"max_data_track_custom_encoding_length,omitempty"`
|
||||||
|
|
||||||
|
// maximum size (in bytes) of a single message read off a client-facing
|
||||||
|
// signalling WebSocket connection. Frames larger than this are rejected by the
|
||||||
|
// transport before being buffered, guarding against single-frame memory
|
||||||
|
// exhaustion. A value of 0 disables the limit (unbounded).
|
||||||
|
SignalMessageSizeLimit int64 `yaml:"signal_message_size_limit,omitempty"`
|
||||||
|
// same as SignalMessageSizeLimit, but for agent worker WebSocket connections.
|
||||||
|
AgentSignalMessageSizeLimit int64 `yaml:"agent_signal_message_size_limit,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l LimitConfig) CheckRoomNameLength(name string) bool {
|
func (l LimitConfig) CheckRoomNameLength(name string) bool {
|
||||||
@@ -543,6 +551,8 @@ var DefaultConfig = Config{
|
|||||||
MaxDataBlobKeyLength: 256,
|
MaxDataBlobKeyLength: 256,
|
||||||
MaxDataBlobSize: 64000,
|
MaxDataBlobSize: 64000,
|
||||||
MaxDataTrackCustomEncodingLength: 32,
|
MaxDataTrackCustomEncodingLength: 32,
|
||||||
|
SignalMessageSizeLimit: 2 << 20, // 2 MiB
|
||||||
|
AgentSignalMessageSizeLimit: 2 << 20, // 2 MiB
|
||||||
},
|
},
|
||||||
Logging: LoggingConfig{
|
Logging: LoggingConfig{
|
||||||
PionLevel: "error",
|
PionLevel: "error",
|
||||||
|
|||||||
@@ -42,6 +42,25 @@ func TestConfig_DefaultsKept(t *testing.T) {
|
|||||||
require.Equal(t, uint32(10), conf.Room.EmptyTimeout)
|
require.Equal(t, uint32(10), conf.Room.EmptyTimeout)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestConfig_SignalMessageSizeLimitDefaults(t *testing.T) {
|
||||||
|
conf, err := NewConfig("", true, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
// both default to 2 MiB when not specified
|
||||||
|
require.Equal(t, int64(2<<20), conf.Limit.SignalMessageSizeLimit)
|
||||||
|
require.Equal(t, int64(2<<20), conf.Limit.AgentSignalMessageSizeLimit)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfig_SignalMessageSizeLimitOverride(t *testing.T) {
|
||||||
|
const content = `limit:
|
||||||
|
signal_message_size_limit: 1024
|
||||||
|
agent_signal_message_size_limit: 0`
|
||||||
|
conf, err := NewConfig(content, true, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, int64(1024), conf.Limit.SignalMessageSizeLimit)
|
||||||
|
// 0 explicitly disables the limit
|
||||||
|
require.Equal(t, int64(0), conf.Limit.AgentSignalMessageSizeLimit)
|
||||||
|
}
|
||||||
|
|
||||||
func TestConfig_UnknownKeys(t *testing.T) {
|
func TestConfig_UnknownKeys(t *testing.T) {
|
||||||
const content = `unknown: 10
|
const content = `unknown: 10
|
||||||
room:
|
room:
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ package types
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pion/rtcp"
|
"github.com/pion/rtcp"
|
||||||
@@ -43,6 +44,7 @@ import (
|
|||||||
//counterfeiter:generate . WebsocketClient
|
//counterfeiter:generate . WebsocketClient
|
||||||
type WebsocketClient interface {
|
type WebsocketClient interface {
|
||||||
ReadMessage() (messageType int, p []byte, err error)
|
ReadMessage() (messageType int, p []byte, err error)
|
||||||
|
NextReader() (messageType int, r io.Reader, err error)
|
||||||
WriteMessage(messageType int, data []byte) error
|
WriteMessage(messageType int, data []byte) error
|
||||||
WriteControl(messageType int, data []byte, deadline time.Time) error
|
WriteControl(messageType int, data []byte, deadline time.Time) error
|
||||||
SetReadDeadline(deadline time.Time) error
|
SetReadDeadline(deadline time.Time) error
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
package typesfakes
|
package typesfakes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"io"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -19,6 +20,20 @@ type FakeWebsocketClient struct {
|
|||||||
closeReturnsOnCall map[int]struct {
|
closeReturnsOnCall map[int]struct {
|
||||||
result1 error
|
result1 error
|
||||||
}
|
}
|
||||||
|
NextReaderStub func() (int, io.Reader, error)
|
||||||
|
nextReaderMutex sync.RWMutex
|
||||||
|
nextReaderArgsForCall []struct {
|
||||||
|
}
|
||||||
|
nextReaderReturns struct {
|
||||||
|
result1 int
|
||||||
|
result2 io.Reader
|
||||||
|
result3 error
|
||||||
|
}
|
||||||
|
nextReaderReturnsOnCall map[int]struct {
|
||||||
|
result1 int
|
||||||
|
result2 io.Reader
|
||||||
|
result3 error
|
||||||
|
}
|
||||||
ReadMessageStub func() (int, []byte, error)
|
ReadMessageStub func() (int, []byte, error)
|
||||||
readMessageMutex sync.RWMutex
|
readMessageMutex sync.RWMutex
|
||||||
readMessageArgsForCall []struct {
|
readMessageArgsForCall []struct {
|
||||||
@@ -126,6 +141,65 @@ func (fake *FakeWebsocketClient) CloseReturnsOnCall(i int, result1 error) {
|
|||||||
}{result1}
|
}{result1}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (fake *FakeWebsocketClient) NextReader() (int, io.Reader, error) {
|
||||||
|
fake.nextReaderMutex.Lock()
|
||||||
|
ret, specificReturn := fake.nextReaderReturnsOnCall[len(fake.nextReaderArgsForCall)]
|
||||||
|
fake.nextReaderArgsForCall = append(fake.nextReaderArgsForCall, struct {
|
||||||
|
}{})
|
||||||
|
stub := fake.NextReaderStub
|
||||||
|
fakeReturns := fake.nextReaderReturns
|
||||||
|
fake.recordInvocation("NextReader", []interface{}{})
|
||||||
|
fake.nextReaderMutex.Unlock()
|
||||||
|
if stub != nil {
|
||||||
|
return stub()
|
||||||
|
}
|
||||||
|
if specificReturn {
|
||||||
|
return ret.result1, ret.result2, ret.result3
|
||||||
|
}
|
||||||
|
return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fake *FakeWebsocketClient) NextReaderCallCount() int {
|
||||||
|
fake.nextReaderMutex.RLock()
|
||||||
|
defer fake.nextReaderMutex.RUnlock()
|
||||||
|
return len(fake.nextReaderArgsForCall)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fake *FakeWebsocketClient) NextReaderCalls(stub func() (int, io.Reader, error)) {
|
||||||
|
fake.nextReaderMutex.Lock()
|
||||||
|
defer fake.nextReaderMutex.Unlock()
|
||||||
|
fake.NextReaderStub = stub
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fake *FakeWebsocketClient) NextReaderReturns(result1 int, result2 io.Reader, result3 error) {
|
||||||
|
fake.nextReaderMutex.Lock()
|
||||||
|
defer fake.nextReaderMutex.Unlock()
|
||||||
|
fake.NextReaderStub = nil
|
||||||
|
fake.nextReaderReturns = struct {
|
||||||
|
result1 int
|
||||||
|
result2 io.Reader
|
||||||
|
result3 error
|
||||||
|
}{result1, result2, result3}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fake *FakeWebsocketClient) NextReaderReturnsOnCall(i int, result1 int, result2 io.Reader, result3 error) {
|
||||||
|
fake.nextReaderMutex.Lock()
|
||||||
|
defer fake.nextReaderMutex.Unlock()
|
||||||
|
fake.NextReaderStub = nil
|
||||||
|
if fake.nextReaderReturnsOnCall == nil {
|
||||||
|
fake.nextReaderReturnsOnCall = make(map[int]struct {
|
||||||
|
result1 int
|
||||||
|
result2 io.Reader
|
||||||
|
result3 error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fake.nextReaderReturnsOnCall[i] = struct {
|
||||||
|
result1 int
|
||||||
|
result2 io.Reader
|
||||||
|
result3 error
|
||||||
|
}{result1, result2, result3}
|
||||||
|
}
|
||||||
|
|
||||||
func (fake *FakeWebsocketClient) ReadMessage() (int, []byte, error) {
|
func (fake *FakeWebsocketClient) ReadMessage() (int, []byte, error) {
|
||||||
fake.readMessageMutex.Lock()
|
fake.readMessageMutex.Lock()
|
||||||
ret, specificReturn := fake.readMessageReturnsOnCall[len(fake.readMessageArgsForCall)]
|
ret, specificReturn := fake.readMessageReturnsOnCall[len(fake.readMessageArgsForCall)]
|
||||||
|
|||||||
@@ -131,6 +131,8 @@ func HandshakeAgentWorker(c agent.SignalConn, serverInfo *livekit.ServerInfo, re
|
|||||||
type AgentService struct {
|
type AgentService struct {
|
||||||
upgrader AgentSocketUpgrader
|
upgrader AgentSocketUpgrader
|
||||||
|
|
||||||
|
signalMessageSizeLimit int64
|
||||||
|
|
||||||
*AgentHandler
|
*AgentHandler
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,7 +172,9 @@ func NewAgentService(
|
|||||||
bus psrpc.MessageBus,
|
bus psrpc.MessageBus,
|
||||||
keyProvider auth.KeyProvider,
|
keyProvider auth.KeyProvider,
|
||||||
) (*AgentService, error) {
|
) (*AgentService, error) {
|
||||||
s := &AgentService{}
|
s := &AgentService{
|
||||||
|
signalMessageSizeLimit: conf.Limit.AgentSignalMessageSizeLimit,
|
||||||
|
}
|
||||||
|
|
||||||
serverInfo := &livekit.ServerInfo{
|
serverInfo := &livekit.ServerInfo{
|
||||||
Edition: livekit.ServerInfo_Standard,
|
Edition: livekit.ServerInfo_Standard,
|
||||||
@@ -200,7 +204,14 @@ func NewAgentService(
|
|||||||
|
|
||||||
func (s *AgentService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (s *AgentService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
if conn, registration, ok := s.upgrader.Upgrade(w, r, nil); ok {
|
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()
|
conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -447,6 +447,13 @@ func (s *RTCService) serve(w http.ResponseWriter, r *http.Request, needsJoinRequ
|
|||||||
HandleError(w, r, http.StatusInternalServerError, err, getLoggerFields()...)
|
HandleError(w, r, http.StatusInternalServerError, err, getLoggerFields()...)
|
||||||
return
|
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.mu.Lock()
|
||||||
s.connections[conn] = struct{}{}
|
s.connections[conn] = struct{}{}
|
||||||
@@ -459,7 +466,7 @@ func (s *RTCService) serve(w http.ResponseWriter, r *http.Request, needsJoinRequ
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
// websocket established
|
// websocket established
|
||||||
sigConn := NewWSSignalConnection(conn)
|
sigConn := NewWSSignalConnection(conn, s.limits.SignalMessageSizeLimit)
|
||||||
pLogger.Debugw("sending initial response", "response", logger.Proto(initialResponse))
|
pLogger.Debugw("sending initial response", "response", logger.Proto(initialResponse))
|
||||||
count, err := sigConn.WriteResponse(initialResponse)
|
count, err := sigConn.WriteResponse(initialResponse)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -41,18 +42,51 @@ type WSSignalConnection struct {
|
|||||||
conn types.WebsocketClient
|
conn types.WebsocketClient
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
useJSON bool
|
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{
|
wsc := &WSSignalConnection{
|
||||||
conn: conn,
|
conn: conn,
|
||||||
mu: sync.Mutex{},
|
mu: sync.Mutex{},
|
||||||
useJSON: false,
|
useJSON: false,
|
||||||
|
messageSizeLimit: messageSizeLimit,
|
||||||
}
|
}
|
||||||
go wsc.pingWorker()
|
go wsc.pingWorker()
|
||||||
return wsc
|
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 {
|
func (c *WSSignalConnection) Close() error {
|
||||||
return c.conn.Close()
|
return c.conn.Close()
|
||||||
}
|
}
|
||||||
@@ -69,7 +103,7 @@ func (c *WSSignalConnection) SetReadDeadline(deadline time.Time) error {
|
|||||||
|
|
||||||
func (c *WSSignalConnection) ReadRequest() (*livekit.SignalRequest, int, error) {
|
func (c *WSSignalConnection) ReadRequest() (*livekit.SignalRequest, int, error) {
|
||||||
// handle special messages and pass on the rest
|
// handle special messages and pass on the rest
|
||||||
messageType, payload, err := c.conn.ReadMessage()
|
messageType, payload, err := c.readMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
@@ -101,7 +135,7 @@ func (c *WSSignalConnection) ReadRequest() (*livekit.SignalRequest, int, error)
|
|||||||
|
|
||||||
func (c *WSSignalConnection) ReadWorkerMessage() (*livekit.WorkerMessage, int, error) {
|
func (c *WSSignalConnection) ReadWorkerMessage() (*livekit.WorkerMessage, int, error) {
|
||||||
// handle special messages and pass on the rest
|
// handle special messages and pass on the rest
|
||||||
messageType, payload, err := c.conn.ReadMessage()
|
messageType, payload, err := c.readMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -63,8 +63,12 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func setupSingleNodeTest(name string) (*service.LivekitServer, func()) {
|
func setupSingleNodeTest(name string) (*service.LivekitServer, func()) {
|
||||||
|
return setupSingleNodeTestWithConfig(name, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func setupSingleNodeTestWithConfig(name string, configUpdater func(*config.Config)) (*service.LivekitServer, func()) {
|
||||||
logger.Infow("----------------STARTING TEST----------------", "test", name)
|
logger.Infow("----------------STARTING TEST----------------", "test", name)
|
||||||
s := createSingleNodeServer(nil)
|
s := createSingleNodeServer(configUpdater)
|
||||||
go func() {
|
go func() {
|
||||||
if err := s.Start(); err != nil {
|
if err := s.Start(); err != nil {
|
||||||
logger.Errorw("server returned error", err)
|
logger.Errorw("server returned error", err)
|
||||||
|
|||||||
@@ -0,0 +1,223 @@
|
|||||||
|
// 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 test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"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/config"
|
||||||
|
"github.com/livekit/livekit-server/pkg/rtc/types"
|
||||||
|
testclient "github.com/livekit/livekit-server/test/client"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSignalMessageSizeLimit drives the full /rtc signalling path: a real client
|
||||||
|
// connects to a single-node server configured with a small read-message size
|
||||||
|
// limit and sends an oversized frame. The server must reject it at the transport
|
||||||
|
// and close the connection with a 1009 (message too big) close code.
|
||||||
|
func TestSignalMessageSizeLimit(t *testing.T) {
|
||||||
|
if testing.Short() {
|
||||||
|
t.SkipNow()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const limit = 1024
|
||||||
|
_, finish := setupSingleNodeTestWithConfig("TestSignalMessageSizeLimit", func(conf *config.Config) {
|
||||||
|
conf.Limit.SignalMessageSizeLimit = limit
|
||||||
|
})
|
||||||
|
defer finish()
|
||||||
|
|
||||||
|
token := joinToken(testRoom, "oversized", nil)
|
||||||
|
opts := &testclient.Options{AutoSubscribe: true}
|
||||||
|
testRTCServicePathToTestClientOptions(testRTCServicePathv0, opts)
|
||||||
|
|
||||||
|
ws, err := testclient.NewWebSocketConn(fmt.Sprintf("ws://localhost:%d", defaultServerPort), token, opts)
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer ws.Close()
|
||||||
|
|
||||||
|
// send a frame well over the configured limit
|
||||||
|
require.NoError(t, ws.WriteMessage(websocket.BinaryMessage, make([]byte, limit*4)))
|
||||||
|
|
||||||
|
// the server rejects the oversized frame and closes the connection; drain any
|
||||||
|
// buffered server messages (e.g. JoinResponse) until the close surfaces
|
||||||
|
_ = ws.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||||
|
for {
|
||||||
|
if _, _, err = ws.ReadMessage(); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.True(t, websocket.IsCloseError(err, websocket.CloseMessageTooBig), "got %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSignalMessageSizeLimitDisabled verifies that a limit of 0 leaves the
|
||||||
|
// connection unbounded: a frame larger than the default limit is not rejected by
|
||||||
|
// the transport with a 1009 close, and the server still delivers its signalling
|
||||||
|
// messages (e.g. the JoinResponse).
|
||||||
|
func TestSignalMessageSizeLimitDisabled(t *testing.T) {
|
||||||
|
if testing.Short() {
|
||||||
|
t.SkipNow()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, finish := setupSingleNodeTestWithConfig("TestSignalMessageSizeLimitDisabled", func(conf *config.Config) {
|
||||||
|
conf.Limit.SignalMessageSizeLimit = 0
|
||||||
|
})
|
||||||
|
defer finish()
|
||||||
|
|
||||||
|
token := joinToken(testRoom, "oversized-disabled", nil)
|
||||||
|
opts := &testclient.Options{AutoSubscribe: true}
|
||||||
|
testRTCServicePathToTestClientOptions(testRTCServicePathv0, opts)
|
||||||
|
|
||||||
|
ws, err := testclient.NewWebSocketConn(fmt.Sprintf("ws://localhost:%d", defaultServerPort), token, opts)
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer ws.Close()
|
||||||
|
|
||||||
|
// send a frame larger than the default 2 MiB limit; with the limit disabled the
|
||||||
|
// transport must not reject it
|
||||||
|
require.NoError(t, ws.WriteMessage(websocket.BinaryMessage, make([]byte, 3<<20)))
|
||||||
|
|
||||||
|
// the server still delivers signalling (the JoinResponse) and never closes with
|
||||||
|
// a 1009; drain until an error and assert it is not a message-too-big close
|
||||||
|
_ = ws.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||||
|
var reads int
|
||||||
|
for {
|
||||||
|
if _, _, err = ws.ReadMessage(); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
reads++
|
||||||
|
}
|
||||||
|
require.Positive(t, reads, "expected to read at least one server message")
|
||||||
|
require.False(t, websocket.IsCloseError(err, websocket.CloseMessageTooBig), "got %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// dialCompressed opens a permessage-deflate signalling connection to /rtc and
|
||||||
|
// returns a valid, highly compressible SignalRequest whose marshaled (uncompressed)
|
||||||
|
// size exceeds sizeAtLeast. On the wire the frame compresses to a few hundred
|
||||||
|
// bytes, staying well under the transport read limit, so only the decompressed
|
||||||
|
// bound can reject it.
|
||||||
|
func dialCompressed(t *testing.T, identity string, sizeAtLeast int) (*websocket.Conn, []byte) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
token := joinToken(testRoom, identity, nil)
|
||||||
|
header := make(http.Header)
|
||||||
|
testclient.SetAuthorizationToken(header, token)
|
||||||
|
|
||||||
|
dialer := websocket.Dialer{EnableCompression: true}
|
||||||
|
url := fmt.Sprintf(
|
||||||
|
"ws://localhost:%d/rtc?protocol=%d&auto_subscribe=true&sdk=go",
|
||||||
|
defaultServerPort, types.CurrentProtocol,
|
||||||
|
)
|
||||||
|
ws, _, err := dialer.Dial(url, header)
|
||||||
|
require.NoError(t, err)
|
||||||
|
ws.EnableWriteCompression(true)
|
||||||
|
|
||||||
|
req := &livekit.SignalRequest{
|
||||||
|
Message: &livekit.SignalRequest_UpdateMetadata{
|
||||||
|
UpdateMetadata: &livekit.UpdateParticipantMetadata{
|
||||||
|
Metadata: strings.Repeat("a", sizeAtLeast),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
payload, err := proto.Marshal(req)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Greater(t, len(payload), sizeAtLeast)
|
||||||
|
|
||||||
|
return ws, payload
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSignalMessageSizeLimitDecompressed reproduces the permessage-deflate
|
||||||
|
// amplification case: a valid frame stays tiny on the wire (well under the
|
||||||
|
// transport read limit) but inflates past the limit once decompressed. The
|
||||||
|
// decompressed-size guard must reject it and the server must close the connection.
|
||||||
|
func TestSignalMessageSizeLimitDecompressed(t *testing.T) {
|
||||||
|
if testing.Short() {
|
||||||
|
t.SkipNow()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const limit = 64 << 10 // 64 KiB
|
||||||
|
_, finish := setupSingleNodeTestWithConfig("TestSignalMessageSizeLimitDecompressed", func(conf *config.Config) {
|
||||||
|
conf.Limit.SignalMessageSizeLimit = limit
|
||||||
|
})
|
||||||
|
defer finish()
|
||||||
|
|
||||||
|
ws, payload := dialCompressed(t, "compressed", limit*8)
|
||||||
|
defer ws.Close()
|
||||||
|
require.NoError(t, ws.WriteMessage(websocket.BinaryMessage, payload))
|
||||||
|
|
||||||
|
// the server rejects the oversized decompressed message and tears down the
|
||||||
|
// connection: draining eventually yields a close/EOF rather than a read timeout
|
||||||
|
_ = ws.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||||
|
var err error
|
||||||
|
for {
|
||||||
|
if _, _, err = ws.ReadMessage(); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.Error(t, err)
|
||||||
|
require.False(t, isTimeout(err), "connection should be closed by the server, not time out; got %v", err)
|
||||||
|
require.False(t, websocket.IsCloseError(err, websocket.CloseMessageTooBig), "got %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSignalMessageSizeLimitDecompressedDisabled is the counterpart to
|
||||||
|
// TestSignalMessageSizeLimitDecompressed: with the limit disabled the same valid
|
||||||
|
// large frame is accepted and the connection stays open (the drain times out
|
||||||
|
// rather than being closed).
|
||||||
|
func TestSignalMessageSizeLimitDecompressedDisabled(t *testing.T) {
|
||||||
|
if testing.Short() {
|
||||||
|
t.SkipNow()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, finish := setupSingleNodeTestWithConfig("TestSignalMessageSizeLimitDecompressedDisabled", func(conf *config.Config) {
|
||||||
|
conf.Limit.SignalMessageSizeLimit = 0
|
||||||
|
})
|
||||||
|
defer finish()
|
||||||
|
|
||||||
|
ws, payload := dialCompressed(t, "compressed-disabled", 1<<20)
|
||||||
|
defer ws.Close()
|
||||||
|
require.NoError(t, ws.WriteMessage(websocket.BinaryMessage, payload))
|
||||||
|
|
||||||
|
// the message is accepted; the connection stays open, so draining blocks until
|
||||||
|
// the read deadline instead of observing a server-initiated close
|
||||||
|
_ = ws.SetReadDeadline(time.Now().Add(2 * time.Second))
|
||||||
|
var err error
|
||||||
|
for {
|
||||||
|
if _, _, err = ws.ReadMessage(); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.Error(t, err)
|
||||||
|
require.True(t, isTimeout(err), "connection should stay open and time out; got %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isTimeout(err error) bool {
|
||||||
|
var netErr net.Error
|
||||||
|
if errors.As(err, &netErr) {
|
||||||
|
return netErr.Timeout()
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user