handle agent worker jwt (#3668)

* handle agent worker jwt

* test

* tidy

* tidy

* deps
This commit is contained in:
Paul Wells
2025-05-15 08:23:10 -07:00
committed by GitHub
parent 3b359d8b74
commit c9385edd1e
7 changed files with 75 additions and 33 deletions
+5
View File
@@ -60,6 +60,11 @@ var baseFlags = []cli.Flag{
Usage: "api keys (key: secret\\n)", Usage: "api keys (key: secret\\n)",
EnvVars: []string{"LIVEKIT_KEYS"}, EnvVars: []string{"LIVEKIT_KEYS"},
}, },
&cli.StringFlag{
Name: "agents-jwt-keys",
Usage: "one or more JWT keys for agents",
EnvVars: []string{"AGENTS_JWT_KEYS"},
},
&cli.StringFlag{ &cli.StringFlag{
Name: "region", Name: "region",
Usage: "region of the current node. Used by regionaware node selector", Usage: "region of the current node. Used by regionaware node selector",
+1 -1
View File
@@ -23,7 +23,7 @@ require (
github.com/jxskiss/base62 v1.1.0 github.com/jxskiss/base62 v1.1.0
github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731
github.com/livekit/mediatransportutil v0.0.0-20250416051815-7632a9d1b50d github.com/livekit/mediatransportutil v0.0.0-20250416051815-7632a9d1b50d
github.com/livekit/protocol v1.38.1-0.20250514122219-5cd901715645 github.com/livekit/protocol v1.38.1-0.20250515151618-2b00a15c76e2
github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c
github.com/mackerelio/go-osstat v0.2.5 github.com/mackerelio/go-osstat v0.2.5
github.com/magefile/mage v1.15.0 github.com/magefile/mage v1.15.0
+2 -2
View File
@@ -169,8 +169,8 @@ github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 h1:9x+U2HGLrSw5AT
github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ= github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ=
github.com/livekit/mediatransportutil v0.0.0-20250416051815-7632a9d1b50d h1:okulvWxyywxCffnvgNbfHxpO8v5ISV9bTjF2O1764IU= github.com/livekit/mediatransportutil v0.0.0-20250416051815-7632a9d1b50d h1:okulvWxyywxCffnvgNbfHxpO8v5ISV9bTjF2O1764IU=
github.com/livekit/mediatransportutil v0.0.0-20250416051815-7632a9d1b50d/go.mod h1:CMenkOQQjEbjvs0oJa2ye84oHSfr7tRiXO+sCIZiG9A= github.com/livekit/mediatransportutil v0.0.0-20250416051815-7632a9d1b50d/go.mod h1:CMenkOQQjEbjvs0oJa2ye84oHSfr7tRiXO+sCIZiG9A=
github.com/livekit/protocol v1.38.1-0.20250514122219-5cd901715645 h1:gI5FY86fVTwnf7r/CC72ASFLdBBHGhTTaUWyOwmaLx0= github.com/livekit/protocol v1.38.1-0.20250515151618-2b00a15c76e2 h1:hLZzPe2zP677A7au2x4W28BpvufFzBv58i3MrIRo+sA=
github.com/livekit/protocol v1.38.1-0.20250514122219-5cd901715645/go.mod h1:F5GLzgMUFFFgm7ajoYLIEXxlZVnRNusV5Qlnok4dtlc= github.com/livekit/protocol v1.38.1-0.20250515151618-2b00a15c76e2/go.mod h1:F5GLzgMUFFFgm7ajoYLIEXxlZVnRNusV5Qlnok4dtlc=
github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c h1:WwEr0YBejYbKzk8LSaO9h8h0G9MnE7shyDu8yXQWmEc= github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c h1:WwEr0YBejYbKzk8LSaO9h8h0G9MnE7shyDu8yXQWmEc=
github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c/go.mod h1:kmD+AZPkWu0MaXIMv57jhNlbiSZZ/Jx4bzlxBDVmJes= github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c/go.mod h1:kmD+AZPkWu0MaXIMv57jhNlbiSZZ/Jx4bzlxBDVmJes=
github.com/mackerelio/go-osstat v0.2.5 h1:+MqTbZUhoIt4m8qzkVoXUJg1EuifwlAJSk4Yl2GXh+o= github.com/mackerelio/go-osstat v0.2.5 h1:+MqTbZUhoIt4m8qzkVoXUJg1EuifwlAJSk4Yl2GXh+o=
+2 -2
View File
@@ -27,7 +27,7 @@ import (
) )
type AgentService interface { type AgentService interface {
HandleConnection(context.Context, agent.SignalConn, agent.WorkerProtocolVersion) HandleConnection(context.Context, agent.SignalConn, agent.WorkerRegistration)
DrainConnections(time.Duration) DrainConnections(time.Duration)
} }
@@ -126,7 +126,7 @@ func (h *TestServer) SimulateAgentWorker(opts ...SimulatedWorkerOption) *AgentWo
} }
ctx := service.WithAPIKey(o.Context, &auth.ClaimGrants{}, "test") ctx := service.WithAPIKey(o.Context, &auth.ClaimGrants{}, "test")
go h.HandleConnection(ctx, w, agent.CurrentProtocol) go h.HandleConnection(ctx, w, agent.MakeWorkerRegistration())
return w return w
} }
+14 -12
View File
@@ -147,23 +147,29 @@ type WorkerRegistration struct {
Permissions *livekit.ParticipantPermission Permissions *livekit.ParticipantPermission
} }
func MakeWorkerRegistration() WorkerRegistration {
return WorkerRegistration{
ID: guid.New(guid.AgentWorkerPrefix),
Protocol: CurrentProtocol,
}
}
var _ WorkerSignalHandler = (*WorkerRegisterer)(nil) var _ WorkerSignalHandler = (*WorkerRegisterer)(nil)
type WorkerRegisterer struct { type WorkerRegisterer struct {
WorkerPingHandler WorkerPingHandler
serverInfo *livekit.ServerInfo serverInfo *livekit.ServerInfo
protocol WorkerProtocolVersion
deadline time.Time deadline time.Time
registration WorkerRegistration registration WorkerRegistration
registered bool registered bool
} }
func NewWorkerRegisterer(conn SignalConn, serverInfo *livekit.ServerInfo, protocol WorkerProtocolVersion) *WorkerRegisterer { func NewWorkerRegisterer(conn SignalConn, serverInfo *livekit.ServerInfo, base WorkerRegistration) *WorkerRegisterer {
return &WorkerRegisterer{ return &WorkerRegisterer{
WorkerPingHandler: WorkerPingHandler{conn: conn}, WorkerPingHandler: WorkerPingHandler{conn: conn},
serverInfo: serverInfo, serverInfo: serverInfo,
protocol: protocol, registration: base,
deadline: time.Now().Add(RegisterTimeout), deadline: time.Now().Add(RegisterTimeout),
} }
} }
@@ -195,15 +201,11 @@ func (h *WorkerRegisterer) HandleRegister(req *livekit.RegisterWorkerRequest) er
} }
} }
h.registration = WorkerRegistration{ h.registration.Version = req.Version
Protocol: h.protocol, h.registration.AgentName = req.AgentName
ID: guid.New(guid.AgentWorkerPrefix), h.registration.Namespace = req.GetNamespace()
Version: req.Version, h.registration.JobType = req.GetType()
AgentName: req.AgentName, h.registration.Permissions = permissions
Namespace: req.GetNamespace(),
JobType: req.GetType(),
Permissions: permissions,
}
h.registered = true h.registered = true
_, err := h.conn.WriteServerMessage(&livekit.ServerMessage{ _, err := h.conn.WriteServerMessage(&livekit.ServerMessage{
+9
View File
@@ -34,6 +34,7 @@ import (
"github.com/livekit/livekit-server/pkg/sfu/pacer" "github.com/livekit/livekit-server/pkg/sfu/pacer"
"github.com/livekit/livekit-server/pkg/sfu/streamallocator" "github.com/livekit/livekit-server/pkg/sfu/streamallocator"
"github.com/livekit/mediatransportutil/pkg/rtcconfig" "github.com/livekit/mediatransportutil/pkg/rtcconfig"
"github.com/livekit/protocol/agent"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger" "github.com/livekit/protocol/logger"
redisLiveKit "github.com/livekit/protocol/redis" redisLiveKit "github.com/livekit/protocol/redis"
@@ -64,6 +65,7 @@ type Config struct {
TURN TURNConfig `yaml:"turn,omitempty"` TURN TURNConfig `yaml:"turn,omitempty"`
Ingress IngressConfig `yaml:"ingress,omitempty"` Ingress IngressConfig `yaml:"ingress,omitempty"`
SIP SIPConfig `yaml:"sip,omitempty"` SIP SIPConfig `yaml:"sip,omitempty"`
Agents AgentsConfig `yaml:"agents,omitempty"`
WebHook webhook.WebHookConfig `yaml:"webhook,omitempty"` WebHook webhook.WebHookConfig `yaml:"webhook,omitempty"`
NodeSelector NodeSelectorConfig `yaml:"node_selector,omitempty"` NodeSelector NodeSelectorConfig `yaml:"node_selector,omitempty"`
KeyFile string `yaml:"key_file,omitempty"` KeyFile string `yaml:"key_file,omitempty"`
@@ -273,6 +275,10 @@ type IngressConfig struct {
type SIPConfig struct{} type SIPConfig struct{}
type AgentsConfig struct {
WorkerToken agent.WorkerTokenConfig `yaml:"worker_token,omitempty"`
}
type APIConfig struct { type APIConfig struct {
// amount of time to wait for API to execute, default 2s // amount of time to wait for API to execute, default 2s
ExecutionTimeout time.Duration `yaml:"execution_timeout,omitempty"` ExecutionTimeout time.Duration `yaml:"execution_timeout,omitempty"`
@@ -725,6 +731,9 @@ func (conf *Config) updateFromCLI(c *cli.Context, baseFlags []cli.Flag) error {
return errors.New("Could not parse keys, it needs to be exactly, \"key: secret\", including the space") return errors.New("Could not parse keys, it needs to be exactly, \"key: secret\", including the space")
} }
} }
if c.String("agents-jwt-keys") != "" {
conf.Agents.WorkerToken.Keys = c.String("agents-jwt-keys")
}
if c.IsSet("region") { if c.IsSet("region") {
conf.Region = c.String("region") conf.Region = c.String("region")
} }
+42 -16
View File
@@ -34,6 +34,7 @@ import (
"github.com/livekit/livekit-server/pkg/rtc" "github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/rtc/types" "github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/version" "github.com/livekit/livekit-server/version"
pagent "github.com/livekit/protocol/agent"
"github.com/livekit/protocol/auth" "github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger" "github.com/livekit/protocol/logger"
@@ -44,9 +45,18 @@ import (
type AgentSocketUpgrader struct { type AgentSocketUpgrader struct {
websocket.Upgrader websocket.Upgrader
WorkerTokenProvider *pagent.WorkerTokenProvider
} }
func (u AgentSocketUpgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*websocket.Conn, agent.WorkerProtocolVersion, bool) { func (u AgentSocketUpgrader) Upgrade(
w http.ResponseWriter,
r *http.Request,
responseHeader http.Header,
) (
conn *websocket.Conn,
registration agent.WorkerRegistration,
ok bool,
) {
if u.CheckOrigin == nil { if u.CheckOrigin == nil {
// allow connections from any origin, since script may be hosted anywhere // allow connections from any origin, since script may be hosted anywhere
// security is enforced by access tokens // security is enforced by access tokens
@@ -58,29 +68,40 @@ func (u AgentSocketUpgrader) Upgrade(w http.ResponseWriter, r *http.Request, res
// reject non websocket requests // reject non websocket requests
if !websocket.IsWebSocketUpgrade(r) { if !websocket.IsWebSocketUpgrade(r) {
w.WriteHeader(404) w.WriteHeader(404)
return nil, 0, false return
} }
// require a claim // require a claim
claims := GetGrants(r.Context()) claims := GetGrants(r.Context())
if claims == nil || claims.Video == nil || !claims.Video.Agent { if claims == nil || claims.Video == nil || !claims.Video.Agent {
handleError(w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied) handleError(w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied)
return nil, 0, false return
}
registration = agent.MakeWorkerRegistration()
workerToken := r.FormValue("worker_token")
if workerToken != "" {
claims, err := u.WorkerTokenProvider.Decode(workerToken)
if err != nil {
handleError(w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied)
return
}
registration.ID = claims.Subject
} }
// upgrade // upgrade
conn, err := u.Upgrader.Upgrade(w, r, responseHeader) conn, err := u.Upgrader.Upgrade(w, r, responseHeader)
if err != nil { if err != nil {
handleError(w, r, http.StatusInternalServerError, err) handleError(w, r, http.StatusInternalServerError, err)
return nil, 0, false return
} }
var protocol agent.WorkerProtocolVersion = agent.CurrentProtocol
if pv, err := strconv.Atoi(r.FormValue("protocol")); err == nil { if pv, err := strconv.Atoi(r.FormValue("protocol")); err == nil {
protocol = agent.WorkerProtocolVersion(pv) registration.Protocol = agent.WorkerProtocolVersion(pv)
} }
return conn, protocol, true return conn, registration, true
} }
func DispatchAgentWorkerSignal(c agent.SignalConn, h agent.WorkerSignalHandler, l logger.Logger) bool { func DispatchAgentWorkerSignal(c agent.SignalConn, h agent.WorkerSignalHandler, l logger.Logger) bool {
@@ -102,8 +123,8 @@ func DispatchAgentWorkerSignal(c agent.SignalConn, h agent.WorkerSignalHandler,
return true return true
} }
func HandshakeAgentWorker(c agent.SignalConn, serverInfo *livekit.ServerInfo, protocol agent.WorkerProtocolVersion, l logger.Logger) (r agent.WorkerRegistration, ok bool) { func HandshakeAgentWorker(c agent.SignalConn, serverInfo *livekit.ServerInfo, registration agent.WorkerRegistration, l logger.Logger) (r agent.WorkerRegistration, ok bool) {
wr := agent.NewWorkerRegisterer(c, serverInfo, protocol) wr := agent.NewWorkerRegisterer(c, serverInfo, registration)
if err := c.SetReadDeadline(wr.Deadline()); err != nil { if err := c.SetReadDeadline(wr.Deadline()); err != nil {
return return
} }
@@ -152,12 +173,17 @@ type workerKey struct {
jobType livekit.JobType jobType livekit.JobType
} }
func NewAgentService(conf *config.Config, func NewAgentService(
conf *config.Config,
currentNode routing.LocalNode, currentNode routing.LocalNode,
bus psrpc.MessageBus, bus psrpc.MessageBus,
keyProvider auth.KeyProvider, keyProvider auth.KeyProvider,
) (*AgentService, error) { ) (*AgentService, error) {
s := &AgentService{} s := &AgentService{
upgrader: AgentSocketUpgrader{
WorkerTokenProvider: pagent.NewWorkerTokenProvider(currentNode.NodeID(), conf.Agents.WorkerToken),
},
}
serverInfo := &livekit.ServerInfo{ serverInfo := &livekit.ServerInfo{
Edition: livekit.ServerInfo_Standard, Edition: livekit.ServerInfo_Standard,
@@ -184,9 +210,9 @@ func NewAgentService(conf *config.Config,
return s, nil return s, nil
} }
func (s *AgentService) ServeHTTP(writer http.ResponseWriter, r *http.Request) { func (s *AgentService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if conn, protocol, ok := s.upgrader.Upgrade(writer, r, nil); ok { if conn, registration, ok := s.upgrader.Upgrade(w, r, nil); ok {
s.HandleConnection(r.Context(), NewWSSignalConnection(conn), protocol) s.HandleConnection(r.Context(), NewWSSignalConnection(conn), registration)
conn.Close() conn.Close()
} }
} }
@@ -214,8 +240,8 @@ func NewAgentHandler(
} }
} }
func (h *AgentHandler) HandleConnection(ctx context.Context, conn agent.SignalConn, protocol agent.WorkerProtocolVersion) { func (h *AgentHandler) HandleConnection(ctx context.Context, conn agent.SignalConn, registration agent.WorkerRegistration) {
registration, ok := HandshakeAgentWorker(conn, h.serverInfo, protocol, h.logger) registration, ok := HandshakeAgentWorker(conn, h.serverInfo, registration, h.logger)
if !ok { if !ok {
return return
} }