config: count lk. participant attributes against their own size limit (#5130)

* config: count lk. participant attributes against their own size limit

LiveKit services set participant attributes with the lk. prefix. These
attributes now count against a new max_lk_attributes_size limit
(default 1024 bytes), so they do not use up the customer's
max_attributes_size budget. All attribute size checks enforce both
limits and keep the existing error types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rtc: check attribute limits against the merged participant attributes

UpdateMetadata checked only the attributes in the update, but
SetAttributes merges them into the stored attributes. Sequential
updates could each pass and leave the participant above either limit.
The check now runs on the attributes that the update would store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* service: return invalid argument when merged attributes exceed a limit

The admin API checks only the attributes in the request. The participant
checks them merged with the attributes it already has, so a request can
pass the first check and fail the second. That error reached the caller
as unknown. Return InvalidArgument for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Raja SubramanianandClaude Opus 5.5 authored and GitHub committed 2026-11-16 16:39:06 +05:30
1 parent c641421db1
commit 80cfa6e73f
12 files changed
+213 -7

No files matched your search

+4 -1
View File
@@ -440,8 +440,11 @@ keys:
# subscription_limit_audio: 0
# # limit size of room and participant's metadata, 0 for no limit
# max_metadata_size: 0
# # limit size of participant attributes, 0 for no limit
# # limit size of participant attributes without the lk. prefix, 0 for no limit
# max_attributes_size: 0
# # limit size of participant attributes with the lk. prefix, which LiveKit services set.
# # defaults to 2 KiB, 0 for no limit
# max_lk_attributes_size: 2048
# # limit length of room names
# max_room_name_length: 0
# # limit length of participant identity
+23 -5
View File
@@ -51,6 +51,9 @@ const (
generatedCLIFlagUsage = "generated"
// LKAttributePrefix marks participant attributes that LiveKit services set
LKAttributePrefix = "lk."
// TURNMaxTTLSeconds is the operational maximum for TURN credential TTLs (24 hours).
// It bounds credential lifetime and prevents time.Duration overflow when multiplying
// by time.Second (values above ~9.2e9 seconds wrap on 64-bit builds).
@@ -388,8 +391,10 @@ type LimitConfig struct {
SubscriptionLimitVideo int32 `yaml:"subscription_limit_video,omitempty"`
SubscriptionLimitAudio int32 `yaml:"subscription_limit_audio,omitempty"`
MaxMetadataSize uint32 `yaml:"max_metadata_size,omitempty"`
// total size of all attributes on a participant
MaxAttributesSize uint32 `yaml:"max_attributes_size,omitempty"`
// total size of all attributes on a participant, except those with the lk. prefix
MaxAttributesSize uint32 `yaml:"max_attributes_size,omitempty"`
// total size of attributes with the lk. prefix, which LiveKit services set
MaxLKAttributesSize uint32 `yaml:"max_lk_attributes_size,omitempty"`
MaxRoomNameLength int `yaml:"max_room_name_length,omitempty"`
MaxParticipantIdentityLength int `yaml:"max_participant_identity_length,omitempty"`
MaxParticipantNameLength int `yaml:"max_participant_name_length,omitempty"`
@@ -434,16 +439,28 @@ func (l LimitConfig) CheckMetadataSize(metadata string) bool {
return l.MaxMetadataSize == 0 || uint32(len(metadata)) <= l.MaxMetadataSize
}
// CheckAttributesSize checks attributes without the lk. prefix against MaxAttributesSize.
func (l LimitConfig) CheckAttributesSize(attributes map[string]string) bool {
if l.MaxAttributesSize == 0 {
return checkAttributesSize(attributes, false, l.MaxAttributesSize)
}
// CheckLKAttributesSize checks attributes with the lk. prefix against MaxLKAttributesSize.
func (l LimitConfig) CheckLKAttributesSize(attributes map[string]string) bool {
return checkAttributesSize(attributes, true, l.MaxLKAttributesSize)
}
func checkAttributesSize(attributes map[string]string, lk bool, limit uint32) bool {
if limit == 0 {
return true
}
total := 0
for k, v := range attributes {
total += len(k) + len(v)
if strings.HasPrefix(k, LKAttributePrefix) == lk {
total += len(k) + len(v)
}
}
return uint32(total) <= l.MaxAttributesSize
return uint32(total) <= limit
}
// DataBlobKeyLength returns the length of the identifying content of a data blob key.
@@ -647,6 +664,7 @@ var DefaultConfig = Config{
Limit: LimitConfig{
MaxMetadataSize: 512 * 1024,
MaxAttributesSize: 64 * 1024,
MaxLKAttributesSize: 2 * 1024,
MaxRoomNameLength: 256,
MaxParticipantIdentityLength: 256,
MaxParticipantNameLength: 256,
+23
View File
@@ -66,6 +66,29 @@ func TestConfig_SignalMessageSizeLimitOverride(t *testing.T) {
require.Equal(t, int64(0), conf.Limit.AgentSignalMessageSizeLimit)
}
func TestCheckAttributesSize(t *testing.T) {
conf, err := NewConfig("", true, nil, nil)
require.NoError(t, err)
require.Equal(t, uint32(2*1024), conf.Limit.MaxLKAttributesSize)
l := LimitConfig{MaxAttributesSize: 5, MaxLKAttributesSize: 10}
// "k"+"vvvv" is 5 bytes, "lk.k"+"vvvvvv" is 10 bytes, each at its own limit
attrs := map[string]string{"k": "vvvv", "lk.k": "vvvvvv"}
require.True(t, l.CheckAttributesSize(attrs))
require.True(t, l.CheckLKAttributesSize(attrs))
attrs["k"] = "vvvvv"
require.False(t, l.CheckAttributesSize(attrs))
require.True(t, l.CheckLKAttributesSize(attrs))
attrs["k"] = "vvvv"
attrs["lk.k"] = "vvvvvvv"
require.True(t, l.CheckAttributesSize(attrs))
require.False(t, l.CheckLKAttributesSize(attrs))
require.True(t, LimitConfig{}.CheckLKAttributesSize(attrs))
}
func TestConfig_PSRPCCompressionDefaults(t *testing.T) {
conf, err := NewConfig("", true, nil, nil)
require.NoError(t, err)
+32 -1
View File
@@ -95,6 +95,8 @@ const (
var (
ErrMoveOldClientVersion = psrpc.NewErrorf(psrpc.FailedPrecondition, "participant client version does not support moving")
errLKAttributesExceedsLimits = fmt.Errorf("%w: lk. attributes", signalling.ErrAttributesExceedsLimits)
)
// -------------------------------------------------
@@ -712,6 +714,10 @@ func (p *ParticipantImpl) checkMetadataLimits(
return signalling.ErrAttributesExceedsLimits
}
if !p.params.LimitConfig.CheckLKAttributesSize(attributes) {
return errLKAttributesExceedsLimits
}
return nil
}
@@ -746,7 +752,8 @@ func (p *ParticipantImpl) UpdateMetadata(update *livekit.UpdateParticipantMetada
return sendRequestResponse()
}
if err = p.checkMetadataLimits(update.Name, update.Metadata, update.Attributes); err != nil {
// shortcut: two concurrent updates can each pass before either is stored, serialize check and store if that matters
if err = p.checkMetadataLimits(update.Name, update.Metadata, p.mergedAttributes(update.Attributes)); err != nil {
switch err {
case signalling.ErrNameExceedsLimits:
requestResponse.Reason = livekit.RequestResponse_LIMIT_EXCEEDED
@@ -759,6 +766,10 @@ func (p *ParticipantImpl) UpdateMetadata(update *livekit.UpdateParticipantMetada
case signalling.ErrAttributesExceedsLimits:
requestResponse.Reason = livekit.RequestResponse_LIMIT_EXCEEDED
requestResponse.Message = "exceeds attributes size limit"
case errLKAttributesExceedsLimits:
requestResponse.Reason = livekit.RequestResponse_LIMIT_EXCEEDED
requestResponse.Message = "exceeds lk. attributes size limit"
}
return sendRequestResponse()
}
@@ -824,6 +835,26 @@ func (p *ParticipantImpl) SetMetadata(metadata string) {
}
}
// mergedAttributes returns the attributes that SetAttributes(update) would store, so limits check the result
func (p *ParticipantImpl) mergedAttributes(update map[string]string) map[string]string {
if len(update) == 0 {
return nil
}
merged := maps.Clone(p.grants.Load().Attributes)
if merged == nil {
merged = make(map[string]string, len(update))
}
for k, v := range update {
if v == "" {
delete(merged, k)
} else {
merged[k] = v
}
}
return merged
}
func (p *ParticipantImpl) SetAttributes(attrs map[string]string) {
if len(attrs) == 0 {
return
+33
View File
@@ -47,6 +47,7 @@ import (
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/routing/routingfakes"
rtcsignalling "github.com/livekit/livekit-server/pkg/rtc/signalling"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/rtc/types/typesfakes"
"github.com/livekit/livekit-server/pkg/testutils"
@@ -671,6 +672,38 @@ func TestCloseDone(t *testing.T) {
}
}
func TestCheckMetadataLimitsLKAttributes(t *testing.T) {
p := newParticipantForTest("test")
p.params.LimitConfig = config.LimitConfig{MaxAttributesSize: 5, MaxLKAttributesSize: 10}
require.NoError(t, p.checkMetadataLimits("", "", map[string]string{"k": "vvvv", "lk.k": "vvvvvv"}))
err := p.checkMetadataLimits("", "", map[string]string{"lk.k": "vvvvvvv"})
require.Equal(t, errLKAttributesExceedsLimits, err)
require.ErrorIs(t, err, rtcsignalling.ErrAttributesExceedsLimits)
}
func TestUpdateMetadataChecksMergedAttributes(t *testing.T) {
p := newParticipantForTest("test")
p.params.LimitConfig = config.LimitConfig{MaxAttributesSize: 5, MaxLKAttributesSize: 10}
// each update fits the lk. limit alone, but the stored total would not
require.NoError(t, p.UpdateMetadata(&livekit.UpdateParticipantMetadata{Attributes: map[string]string{"lk.a": "vvvv"}}, true))
err := p.UpdateMetadata(&livekit.UpdateParticipantMetadata{Attributes: map[string]string{"lk.b": "vvvv"}}, true)
require.ErrorIs(t, err, rtcsignalling.ErrAttributesExceedsLimits)
require.Equal(t, map[string]string{"lk.a": "vvvv"}, p.ClaimGrants().Attributes)
// replacing a key counts its new value only, and an empty value deletes the key
require.NoError(t, p.UpdateMetadata(&livekit.UpdateParticipantMetadata{Attributes: map[string]string{"lk.a": "vvvvvv"}}, true))
require.NoError(t, p.UpdateMetadata(&livekit.UpdateParticipantMetadata{Attributes: map[string]string{"lk.a": "", "lk.b": "vvvvvv"}}, true))
require.Equal(t, map[string]string{"lk.b": "vvvvvv"}, p.ClaimGrants().Attributes)
// customer attributes accumulate against their own limit the same way
require.NoError(t, p.UpdateMetadata(&livekit.UpdateParticipantMetadata{Attributes: map[string]string{"a": "vv"}}, true))
err = p.UpdateMetadata(&livekit.UpdateParticipantMetadata{Attributes: map[string]string{"b": "vv"}}, true)
require.Equal(t, rtcsignalling.ErrAttributesExceedsLimits, err)
}
func TestCorrectJoinedAt(t *testing.T) {
p := newParticipantForTest("test")
info := p.ToProto()
+3
View File
@@ -75,6 +75,9 @@ func (ag *AgentDispatchService) CreateDispatch(ctx context.Context, req *livekit
if !ag.limitConf.CheckAttributesSize(req.Attributes) {
return nil, ErrAttributeExceedsLimits
}
if !ag.limitConf.CheckLKAttributesSize(req.Attributes) {
return nil, fmt.Errorf("%w: lk. attributes max size %d", ErrAttributeExceedsLimits, ag.limitConf.MaxLKAttributesSize)
}
if err := agent.ValidateThreadID(req.GetThreadId()); err != nil {
return nil, twirp.InvalidArgumentError("thread_id", err.Error())
}
+15
View File
@@ -81,6 +81,12 @@ func ConnectLimitCases() []ConnectLimitCase {
Grant: grantWith(func(g *auth.ClaimGrants) { g.Attributes = map[string]string{"k": "abcdefg"} }),
Err: ErrAttributeExceedsLimits,
},
{
Name: "lk attributes exceeds",
Limit: config.LimitConfig{MaxAttributesSize: 100, MaxLKAttributesSize: 5},
Grant: grantWith(func(g *auth.ClaimGrants) { g.Attributes = map[string]string{"lk.k": "abcdefg"} }),
Err: ErrAttributeExceedsLimits,
},
}
}
@@ -135,4 +141,13 @@ func TestConnectLimits(t *testing.T) {
require.NoError(t, err)
require.Equal(t, http.StatusOK, code)
})
t.Run("lk attributes do not count against attributes limit", func(t *testing.T) {
g := baseGrant()
g.Attributes = map[string]string{"k": "abcd", "lk.k": "abcdefg"}
limit := config.LimitConfig{MaxAttributesSize: 5, MaxLKAttributesSize: 11}
_, code, err := ValidateConnectRequest(logger.GetLogger(), grantRequest(g), limit, ValidateConnectRequestParams{}, nil, stubRoomAllocator{})
require.NoError(t, err)
require.Equal(t, http.StatusOK, code)
})
}
+5
View File
@@ -52,6 +52,7 @@ import (
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/rtc/signalling"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/telemetry"
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
@@ -897,6 +898,10 @@ func (r *RoomManager) UpdateParticipant(ctx context.Context, req *livekit.Update
Metadata: req.Metadata,
Attributes: req.Attributes,
}, true); err != nil {
if errors.Is(err, signalling.ErrAttributesExceedsLimits) {
// the request passed the patch check, but the merged attributes exceed a limit
return nil, psrpc.NewError(psrpc.InvalidArgument, err)
}
return nil, err
}
+6
View File
@@ -98,6 +98,9 @@ func (s *RoomService) CreateRoom(ctx context.Context, req *livekit.CreateRoomReq
if !s.limitConf.CheckAttributesSize(ad.Attributes) {
return nil, twirp.InvalidArgumentError(ErrAttributeExceedsLimits.Error(), strconv.Itoa(int(s.limitConf.MaxAttributesSize)))
}
if !s.limitConf.CheckLKAttributesSize(ad.Attributes) {
return nil, twirp.InvalidArgumentError(ErrAttributeExceedsLimits.Error(), "lk. attributes max size "+strconv.Itoa(int(s.limitConf.MaxLKAttributesSize)))
}
if err := agent.ValidateThreadID(ad.GetThreadId()); err != nil {
return nil, twirp.InvalidArgumentError("thread_id", err.Error())
}
@@ -279,6 +282,9 @@ func (s *RoomService) UpdateParticipant(ctx context.Context, req *livekit.Update
if !s.limitConf.CheckAttributesSize(req.Attributes) {
return nil, twirp.InvalidArgumentError(ErrAttributeExceedsLimits.Error(), strconv.Itoa(int(s.limitConf.MaxAttributesSize)))
}
if !s.limitConf.CheckLKAttributesSize(req.Attributes) {
return nil, twirp.InvalidArgumentError(ErrAttributeExceedsLimits.Error(), "lk. attributes max size "+strconv.Itoa(int(s.limitConf.MaxLKAttributesSize)))
}
if err := EnsureAdminPermission(ctx, livekit.RoomName(req.Room)); err != nil {
return nil, twirpAuthError(err)
+27
View File
@@ -106,6 +106,24 @@ func TestMetaDataLimits(t *testing.T) {
requireInvalidArg(t, err)
})
t.Run("lk attributes exceed lk limit", func(t *testing.T) {
svc := newTestRoomService(config.LimitConfig{MaxAttributesSize: 100, MaxLKAttributesSize: 5})
attrs := map[string]string{"lk.key": "abcdefg"}
_, err := svc.UpdateParticipant(adminCtx(), &livekit.UpdateParticipantRequest{
Room: "testroom",
Identity: "123",
Attributes: attrs,
})
requireInvalidArg(t, err)
_, err = svc.CreateRoom(createCtx(), &livekit.CreateRoomRequest{
Name: "testroom",
Agents: []*livekit.RoomAgentDispatch{{AgentName: "bot", Attributes: attrs}},
})
requireInvalidArg(t, err)
})
notExceedsLimitsSvc := map[string]*TestRoomService{
"metadata exceeds limits": newTestRoomService(config.LimitConfig{
MaxMetadataSize: 5,
@@ -172,6 +190,15 @@ func TestAgentDispatchMetadataLimits(t *testing.T) {
require.ErrorIs(t, err, service.ErrAttributeExceedsLimits)
})
t.Run("lk attributes exceeds limits", func(t *testing.T) {
svc := newTestAgentDispatchService(config.LimitConfig{MaxAttributesSize: 100, MaxLKAttributesSize: 5})
_, err := svc.CreateDispatch(ctx, &livekit.CreateAgentDispatchRequest{
Room: "testroom",
Attributes: map[string]string{"lk.key": "abcdefg"},
})
require.ErrorIs(t, err, service.ErrAttributeExceedsLimits)
})
t.Run("room name exceeds limits", func(t *testing.T) {
allocator := &servicefakes.FakeRoomAllocator{}
allocator.AutoCreateEnabledReturns(true)
+3
View File
@@ -479,6 +479,9 @@ func CheckConnectLimits(limitConfig config.LimitConfig, identity string, roomNam
if !limitConfig.CheckAttributesSize(grants.Attributes) {
return fmt.Errorf("%w: max size %d", ErrAttributeExceedsLimits, limitConfig.MaxAttributesSize)
}
if !limitConfig.CheckLKAttributesSize(grants.Attributes) {
return fmt.Errorf("%w: lk. attributes max size %d", ErrAttributeExceedsLimits, limitConfig.MaxLKAttributesSize)
}
return nil
}
+39
View File
@@ -599,6 +599,45 @@ func TestSingleNodeUpdateParticipant(t *testing.T) {
})
}
// each patch fits the attribute limits, but the merged attributes do not
func TestSingleNodeUpdateParticipantMergedAttributesLimit(t *testing.T) {
if testing.Short() {
t.SkipNow()
return
}
_, finish := setupSingleNodeTestWithConfig("TestSingleNodeUpdateParticipantMergedAttributesLimit", func(conf *config.Config) {
conf.Limit.MaxAttributesSize = 5
// the join sets lk.rtc.joinRequestTime to a 13 digit time, leave room for one more 7 byte attribute
conf.Limit.MaxLKAttributesSize = uint32(len(livekit.AttrRTCJoinRequestTime) + 13 + 10)
})
defer finish()
c := createRTCClient("c", defaultServerPort, testRTCServicePathv1, nil)
waitUntilConnected(t, c)
defer stopClients(c)
adminCtx := contextWithToken(adminRoomToken(testRoom))
update := func(attributes map[string]string) error {
_, err := roomClient.UpdateParticipant(adminCtx, &livekit.UpdateParticipantRequest{
Room: testRoom,
Identity: "c",
Attributes: attributes,
})
return err
}
requireInvalidArgument := func(err error) {
var twErr twirp.Error
require.True(t, errors.As(err, &twErr), "error: %v", err)
require.Equal(t, twirp.InvalidArgument, twErr.Code())
}
require.NoError(t, update(map[string]string{"a": "vv"}))
requireInvalidArgument(update(map[string]string{"b": "vv"}))
require.NoError(t, update(map[string]string{"lk.a": "vvv"}))
requireInvalidArgument(update(map[string]string{"lk.b": "vvv"}))
}
// Ensure that CORS headers are returned
func TestSingleNodeCORS(t *testing.T) {
if testing.Short() {