Files
livekit/pkg/config/config_test.go
T
Raja SubramanianandClaude Opus 5.5 80cfa6e73f 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>
2026-11-16 16:39:06 +05:30

508 lines
18 KiB
Go

// Copyright 2023 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 config
import (
"context"
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/urfave/cli/v3"
"github.com/livekit/livekit-server/pkg/config/configtest"
"github.com/livekit/livekit-server/pkg/sfu/pacer"
)
func TestConfig_UnmarshalKeys(t *testing.T) {
conf, err := NewConfig("", true, nil, nil)
require.NoError(t, err)
require.NoError(t, conf.unmarshalKeys("key1: secret1"))
require.Equal(t, "secret1", conf.Keys["key1"])
}
func TestConfig_DefaultsKept(t *testing.T) {
const content = `room:
empty_timeout: 10`
conf, err := NewConfig(content, true, nil, nil)
require.NoError(t, err)
require.Equal(t, true, conf.Room.AutoCreate)
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 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)
require.Equal(t, 0, conf.PSRPC.Compression.Quality)
require.Equal(t, 1024, conf.PSRPC.Compression.Threshold)
require.Equal(t, 0, conf.PSRPC.Compression.MaxDecompressedSize)
}
func TestConfig_PSRPCCompressionOverride(t *testing.T) {
const content = `psrpc:
compression:
quality: 6
max_decompressed_size: 4096`
conf, err := NewConfig(content, true, nil, nil)
require.NoError(t, err)
require.Equal(t, 6, conf.PSRPC.Compression.Quality)
require.Equal(t, 4096, conf.PSRPC.Compression.MaxDecompressedSize)
require.Equal(t, 1024, conf.PSRPC.Compression.Threshold)
require.Equal(t, 3, conf.PSRPC.MaxAttempts)
}
func TestConfig_UnknownKeys(t *testing.T) {
const content = `unknown: 10
room:
empty_timeout: 10`
_, err := NewConfig(content, true, nil, nil)
require.Error(t, err)
}
func TestGeneratedFlags(t *testing.T) {
generatedFlags, err := GenerateCLIFlags(nil, false)
require.NoError(t, err)
c := &cli.Command{}
c.Name = "test"
c.Flags = append(c.Flags, generatedFlags...)
c.Set("rtc.use_ice_lite", "true")
c.Set("redis.address", "localhost:6379")
c.Set("prometheus.port", "9999")
c.Set("rtc.allow_tcp_fallback", "true")
c.Set("rtc.reconnect_on_publication_error", "true")
c.Set("rtc.reconnect_on_subscription_error", "false")
conf, err := NewConfig("", true, c, nil)
require.NoError(t, err)
require.True(t, conf.RTC.UseICELite)
require.Equal(t, "localhost:6379", conf.Redis.Address)
require.Equal(t, uint32(9999), conf.Prometheus.Port)
require.NotNil(t, conf.RTC.AllowTCPFallback)
require.True(t, *conf.RTC.AllowTCPFallback)
require.NotNil(t, conf.RTC.ReconnectOnPublicationError)
require.True(t, *conf.RTC.ReconnectOnPublicationError)
require.NotNil(t, conf.RTC.ReconnectOnSubscriptionError)
require.False(t, *conf.RTC.ReconnectOnSubscriptionError)
}
// runWithGeneratedFlags runs a command with the generated flags, as cmd/server does,
// so that flag and env var values are parsed.
func runWithGeneratedFlags(t *testing.T, args ...string) (*Config, error) {
generatedFlags, err := GenerateCLIFlags(nil, true)
require.NoError(t, err)
var conf *Config
c := &cli.Command{
Name: "test",
Flags: generatedFlags,
Action: func(_ context.Context, c *cli.Command) error {
var err error
conf, err = NewConfig("", true, c, nil)
return err
},
}
err = c.Run(context.Background(), append([]string{"test"}, args...))
return conf, err
}
func TestGeneratedDurationFlags(t *testing.T) {
run := runWithGeneratedFlags
t.Run("flag", func(t *testing.T) {
conf, err := run(t, "--api.execution_timeout=5s")
require.NoError(t, err)
require.Equal(t, 5*time.Second, conf.API.ExecutionTimeout)
})
t.Run("env var", func(t *testing.T) {
t.Setenv("LIVEKIT_ROOM_CREATE_ROOM_TIMEOUT", "30s")
conf, err := run(t)
require.NoError(t, err)
require.Equal(t, 30*time.Second, conf.Room.CreateRoomTimeout)
})
t.Run("value without a unit", func(t *testing.T) {
// rejected, as in the YAML config, instead of being read as nanoseconds
t.Setenv("LIVEKIT_ROOM_CREATE_ROOM_TIMEOUT", "30")
_, err := run(t)
require.ErrorContains(t, err, "LIVEKIT_ROOM_CREATE_ROOM_TIMEOUT")
})
}
func TestGeneratedNarrowNumericFlags(t *testing.T) {
t.Run("in range", func(t *testing.T) {
t.Setenv("LIVEKIT_TURN_RELAY_RANGE_START", "50000")
t.Setenv("LIVEKIT_TURN_RELAY_RANGE_END", "60000")
t.Setenv("LIVEKIT_LIMIT_MAX_METADATA_SIZE", "4096")
t.Setenv("LIVEKIT_LIMIT_NUM_TRACKS", "-1")
t.Setenv("LIVEKIT_LIMIT_BYTES_PER_SEC", "1000000.5")
conf, err := runWithGeneratedFlags(t)
require.NoError(t, err)
require.Equal(t, uint16(50000), conf.TURN.RelayPortRangeStart)
require.Equal(t, uint16(60000), conf.TURN.RelayPortRangeEnd)
require.Equal(t, uint32(4096), conf.Limit.MaxMetadataSize)
require.Equal(t, int32(-1), conf.Limit.NumTracks)
require.Equal(t, float32(1000000.5), conf.Limit.BytesPerSec)
})
// values that do not fit the config field are rejected, as in the YAML config,
// instead of wrapping around
for env, value := range map[string]string{
"LIVEKIT_TURN_RELAY_RANGE_START": "70000", // uint16, would become 4464
"LIVEKIT_LIMIT_MAX_METADATA_SIZE": "4294967296", // uint32, would become 0 (no limit)
"LIVEKIT_LIMIT_NUM_TRACKS": "2147483648", // int32, would become -2147483648
"LIVEKIT_LIMIT_BYTES_PER_SEC": "1e39", // float32, would become +Inf
} {
t.Run(env, func(t *testing.T) {
t.Setenv(env, value)
_, err := runWithGeneratedFlags(t)
require.ErrorContains(t, err, env)
})
}
}
// numericCLIFlag also covers kinds that no config field uses yet (int8, int16, uint),
// so check every numeric kind directly rather than through the Config struct.
func TestNumericCLIFlagWidths(t *testing.T) {
cases := []struct {
name string
typ reflect.Type
inRange string
want any
tooLarge string
}{
{"int8", reflect.TypeOf(int8(0)), "-128", int8(-128), "128"},
{"int16", reflect.TypeOf(int16(0)), "32767", int16(32767), "32768"},
{"int32", reflect.TypeOf(int32(0)), "-2147483648", int32(-2147483648), "2147483648"},
{"uint", reflect.TypeOf(uint(0)), "42", uint(42), "-1"},
{"uint8", reflect.TypeOf(uint8(0)), "255", uint8(255), "256"},
{"uint16", reflect.TypeOf(uint16(0)), "65535", uint16(65535), "65536"},
{"uint32", reflect.TypeOf(uint32(0)), "4294967295", uint32(4294967295), "4294967296"},
{"float32", reflect.TypeOf(float32(0)), "0.5", float32(0.5), "1e39"},
}
run := func(t *testing.T, typ reflect.Type, value string) (any, error) {
const env = "LIVEKIT_TEST_NUMERIC_FLAG"
t.Setenv(env, value)
var got any
flag, err := numericCLIFlag(typ, "test.numeric_flag", env, "", true)
require.NoError(t, err)
c := &cli.Command{
Name: "test",
Flags: []cli.Flag{flag},
Action: func(_ context.Context, c *cli.Command) error {
got = c.Value("test.numeric_flag")
return nil
},
}
err = c.Run(context.Background(), []string{"test"})
return got, err
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, err := run(t, tc.typ, tc.inRange)
require.NoError(t, err)
require.Equal(t, tc.want, got)
_, err = run(t, tc.typ, tc.tooLarge)
require.ErrorContains(t, err, "LIVEKIT_TEST_NUMERIC_FLAG")
})
}
}
func TestNumericCLIFlagUnsupportedKind(t *testing.T) {
flag, err := numericCLIFlag(reflect.TypeOf(complex64(0)), "test.complex_flag", "LIVEKIT_TEST_COMPLEX_FLAG", "", true)
require.Nil(t, flag)
require.ErrorContains(t, err, "test.complex_flag is a complex64")
}
func TestYAMLTag(t *testing.T) {
require.NoError(t, configtest.CheckYAMLTags(Config{}))
}
func TestClampTURNTTLSeconds(t *testing.T) {
cases := []struct {
name string
in int
want int
changed bool
}{
{"negative falls back to default", -1, DefaultTURNTTLSeconds, true},
{"large negative falls back to default", -1 << 40, DefaultTURNTTLSeconds, true},
{"zero falls back to default", 0, DefaultTURNTTLSeconds, true},
{"in range preserved", 600, 600, false},
{"max preserved", TURNMaxTTLSeconds, TURNMaxTTLSeconds, false},
{"over max clamps to max", TURNMaxTTLSeconds + 1, TURNMaxTTLSeconds, true},
{"overflowing value clamps to max", 1<<62 + 1, TURNMaxTTLSeconds, true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, changed := ClampTURNTTLSeconds(c.in)
require.Equal(t, c.want, got)
require.Equal(t, c.changed, changed)
})
}
}
func TestNormalizeTURNTTLs(t *testing.T) {
conf, err := NewConfig("", true, nil, nil)
require.NoError(t, err)
conf.TURN.TTLSeconds = -5
conf.RTC.TURNServers = []TURNServer{
{Host: "over", TTL: TURNMaxTTLSeconds + 100},
{Host: "negative", TTL: -1},
{Host: "default", TTL: 0},
{Host: "ok", TTL: 600},
}
conf.NormalizeTURNTTLs()
// embedded TTL <= 0 falls back to the 5m default
require.Equal(t, DefaultTURNTTLSeconds, conf.TURN.TTLSeconds)
// external TTLs: only the upper bound is capped at load; 0/negative keep their
// "use the default" meaning and are resolved when credentials are generated
require.Equal(t, TURNMaxTTLSeconds, conf.RTC.TURNServers[0].TTL)
require.Equal(t, -1, conf.RTC.TURNServers[1].TTL)
require.Equal(t, 0, conf.RTC.TURNServers[2].TTL)
require.Equal(t, 600, conf.RTC.TURNServers[3].TTL)
}
func TestNewConfigNormalizesTURNTTL(t *testing.T) {
const content = `turn:
ttl_seconds: -10`
conf, err := NewConfig(content, true, nil, nil)
require.NoError(t, err)
require.Equal(t, DefaultTURNTTLSeconds, conf.TURN.TTLSeconds)
}
func TestNewConfigValidatesSendSideBWEPacer(t *testing.T) {
cases := []struct {
name string
pacer string
wantErr bool
}{
{name: "unset keeps the default", pacer: "", wantErr: false},
{name: "pass-through", pacer: string(pacer.PacerBehaviorPassThrough), wantErr: false},
{name: "no-queue", pacer: string(pacer.PacerBehaviorNoQueue), wantErr: false},
{name: "leaky-bucket", pacer: string(pacer.PacerBehaviorLeakybucket), wantErr: false},
{name: "typo is rejected", pacer: "leakybucket", wantErr: true},
{name: "unknown value is rejected", pacer: "not-a-pacer", wantErr: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
content := "rtc:\n congestion_control:\n send_side_bwe_pacer: " + tc.pacer
conf, err := NewConfig(content, true, nil, nil)
if tc.wantErr {
require.Error(t, err)
require.Contains(t, err.Error(), tc.pacer)
return
}
require.NoError(t, err)
if tc.pacer == "" {
require.Equal(t, string(pacer.PacerBehaviorNoQueue), conf.RTC.CongestionControl.SendSideBWEPacer)
return
}
require.Equal(t, tc.pacer, conf.RTC.CongestionControl.SendSideBWEPacer)
})
}
}
func writeSecretFile(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "secret")
require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
return path
}
func TestLoadTURNSecrets(t *testing.T) {
t.Run("empty secret file is rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", SecretFile: writeSecretFile(t, "")}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNSecretEmpty)
})
t.Run("whitespace-only secret file is rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", SecretFile: writeSecretFile(t, " \n\t ")}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNSecretEmpty)
})
t.Run("valid secret file is loaded and trimmed", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", SecretFile: writeSecretFile(t, " topsecret\n")}}
require.NoError(t, conf.LoadTURNSecrets())
require.Equal(t, "topsecret", conf.RTC.TURNServers[0].Secret)
})
t.Run("inline whitespace secret without static creds is rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Secret: " "}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNServerNoCredentials)
})
t.Run("no credentials at all is rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h"}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNServerNoCredentials)
})
t.Run("static credentials are accepted", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Username: "u", Credential: "c"}}
require.NoError(t, conf.LoadTURNSecrets())
})
t.Run("partial static credentials are rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Username: "u"}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNServerNoCredentials)
})
t.Run("inline secret takes precedence and is trimmed", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Secret: " inline ", SecretFile: writeSecretFile(t, "fromfile")}}
require.NoError(t, conf.LoadTURNSecrets())
require.Equal(t, "inline", conf.RTC.TURNServers[0].Secret)
})
t.Run("blank inline secret falls back to secret file", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Secret: " ", SecretFile: writeSecretFile(t, "fromfile")}}
require.NoError(t, conf.LoadTURNSecrets())
require.Equal(t, "fromfile", conf.RTC.TURNServers[0].Secret)
})
}
// Exercise the operator-facing YAML path so this test also runs on the upstream
// branch, where credentials_file is not recognized yet.
func TestTURNCredentialsFile(t *testing.T) {
const (
fileName = "turn-credentials.yaml"
username = "turn-user"
credential = " turn-password "
validCredentials = "username: turn-user\ncredential: ' turn-password '\n"
privateValue = "do-not-log-my-password"
redactedPrefix = "do-not-"
configFormat = "rtc:\n turn_servers:\n - host: turn.example.com\n credentials_file: %q\n%s"
inlineCredentials = " username: inline-user\n credential: inline-password\n"
)
cases := []struct {
name string
data string
mode os.FileMode
inline string
missing bool
directory bool
wantError bool
wantUser string
wantCredential string
}{
{name: "pair loaded from one file", data: validCredentials, mode: 0o600, wantUser: username, wantCredential: credential},
{name: "group-readable file accepted", data: validCredentials, mode: 0o640, wantUser: username, wantCredential: credential},
{name: "inline pair wins without reading missing file", missing: true, inline: inlineCredentials, wantUser: "inline-user", wantCredential: "inline-password"},
{name: "inline whitespace preserved", missing: true, inline: " username: ' u '\n credential: ' c '\n", wantUser: " u ", wantCredential: " c "},
{name: "partial inline username is not mixed with file", data: validCredentials, mode: 0o600, inline: " username: inline-user\n", wantError: true},
{name: "partial inline password is not mixed with file", data: validCredentials, mode: 0o600, inline: " credential: inline-password\n", wantError: true},
{name: "missing file", missing: true, wantError: true},
{name: "directory cannot be read", directory: true, wantError: true},
{name: "others permissions rejected", data: validCredentials, mode: 0o604, wantError: true},
{name: "scalar credentials do not leak in errors", data: privateValue, mode: 0o600, wantError: true},
{name: "invalid YAML", data: "username: [", mode: 0o600, wantError: true},
{name: "empty file", mode: 0o600, wantError: true},
{name: "whitespace file", data: " \n\t", mode: 0o600, wantError: true},
{name: "missing username", data: "credential: password\n", mode: 0o600, wantError: true},
{name: "missing password", data: "username: user\n", mode: 0o600, wantError: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), fileName)
switch {
case tc.directory:
require.NoError(t, os.Mkdir(path, 0o700))
case !tc.missing:
require.NoError(t, os.WriteFile(path, []byte(tc.data), tc.mode))
}
conf, err := NewConfig(fmt.Sprintf(configFormat, path, tc.inline), true, nil, nil)
require.NoError(t, err)
err = conf.LoadTURNSecrets()
if tc.wantError {
require.Error(t, err)
require.NotContains(t, err.Error(), redactedPrefix)
return
}
require.NoError(t, err)
require.Equal(t, tc.wantUser, conf.RTC.TURNServers[0].Username)
require.Equal(t, tc.wantCredential, conf.RTC.TURNServers[0].Credential)
})
}
}