From c9385edd1e05fda096187187a3a0e966ff2c2c42 Mon Sep 17 00:00:00 2001 From: Paul Wells Date: Thu, 15 May 2025 08:23:10 -0700 Subject: [PATCH] handle agent worker jwt (#3668) * handle agent worker jwt * test * tidy * tidy * deps --- cmd/server/main.go | 5 +++ go.mod | 2 +- go.sum | 4 +-- pkg/agent/testutils/server.go | 4 +-- pkg/agent/worker.go | 26 ++++++++-------- pkg/config/config.go | 9 ++++++ pkg/service/agentservice.go | 58 +++++++++++++++++++++++++---------- 7 files changed, 75 insertions(+), 33 deletions(-) diff --git a/cmd/server/main.go b/cmd/server/main.go index 6cdfba63..af91d47f 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -60,6 +60,11 @@ var baseFlags = []cli.Flag{ Usage: "api keys (key: secret\\n)", 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{ Name: "region", Usage: "region of the current node. Used by regionaware node selector", diff --git a/go.mod b/go.mod index c1546151..df11d9f0 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,7 @@ require ( github.com/jxskiss/base62 v1.1.0 github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 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/mackerelio/go-osstat v0.2.5 github.com/magefile/mage v1.15.0 diff --git a/go.sum b/go.sum index dcd079d9..665ea9f3 100644 --- a/go.sum +++ b/go.sum @@ -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/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/protocol v1.38.1-0.20250514122219-5cd901715645 h1:gI5FY86fVTwnf7r/CC72ASFLdBBHGhTTaUWyOwmaLx0= -github.com/livekit/protocol v1.38.1-0.20250514122219-5cd901715645/go.mod h1:F5GLzgMUFFFgm7ajoYLIEXxlZVnRNusV5Qlnok4dtlc= +github.com/livekit/protocol v1.38.1-0.20250515151618-2b00a15c76e2 h1:hLZzPe2zP677A7au2x4W28BpvufFzBv58i3MrIRo+sA= +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/go.mod h1:kmD+AZPkWu0MaXIMv57jhNlbiSZZ/Jx4bzlxBDVmJes= github.com/mackerelio/go-osstat v0.2.5 h1:+MqTbZUhoIt4m8qzkVoXUJg1EuifwlAJSk4Yl2GXh+o= diff --git a/pkg/agent/testutils/server.go b/pkg/agent/testutils/server.go index 04de89f6..c695afb4 100644 --- a/pkg/agent/testutils/server.go +++ b/pkg/agent/testutils/server.go @@ -27,7 +27,7 @@ import ( ) type AgentService interface { - HandleConnection(context.Context, agent.SignalConn, agent.WorkerProtocolVersion) + HandleConnection(context.Context, agent.SignalConn, agent.WorkerRegistration) DrainConnections(time.Duration) } @@ -126,7 +126,7 @@ func (h *TestServer) SimulateAgentWorker(opts ...SimulatedWorkerOption) *AgentWo } ctx := service.WithAPIKey(o.Context, &auth.ClaimGrants{}, "test") - go h.HandleConnection(ctx, w, agent.CurrentProtocol) + go h.HandleConnection(ctx, w, agent.MakeWorkerRegistration()) return w } diff --git a/pkg/agent/worker.go b/pkg/agent/worker.go index fefbe54d..8c689528 100644 --- a/pkg/agent/worker.go +++ b/pkg/agent/worker.go @@ -147,23 +147,29 @@ type WorkerRegistration struct { Permissions *livekit.ParticipantPermission } +func MakeWorkerRegistration() WorkerRegistration { + return WorkerRegistration{ + ID: guid.New(guid.AgentWorkerPrefix), + Protocol: CurrentProtocol, + } +} + var _ WorkerSignalHandler = (*WorkerRegisterer)(nil) type WorkerRegisterer struct { WorkerPingHandler serverInfo *livekit.ServerInfo - protocol WorkerProtocolVersion deadline time.Time registration WorkerRegistration registered bool } -func NewWorkerRegisterer(conn SignalConn, serverInfo *livekit.ServerInfo, protocol WorkerProtocolVersion) *WorkerRegisterer { +func NewWorkerRegisterer(conn SignalConn, serverInfo *livekit.ServerInfo, base WorkerRegistration) *WorkerRegisterer { return &WorkerRegisterer{ WorkerPingHandler: WorkerPingHandler{conn: conn}, serverInfo: serverInfo, - protocol: protocol, + registration: base, deadline: time.Now().Add(RegisterTimeout), } } @@ -195,15 +201,11 @@ func (h *WorkerRegisterer) HandleRegister(req *livekit.RegisterWorkerRequest) er } } - h.registration = WorkerRegistration{ - Protocol: h.protocol, - ID: guid.New(guid.AgentWorkerPrefix), - Version: req.Version, - AgentName: req.AgentName, - Namespace: req.GetNamespace(), - JobType: req.GetType(), - Permissions: permissions, - } + h.registration.Version = req.Version + h.registration.AgentName = req.AgentName + h.registration.Namespace = req.GetNamespace() + h.registration.JobType = req.GetType() + h.registration.Permissions = permissions h.registered = true _, err := h.conn.WriteServerMessage(&livekit.ServerMessage{ diff --git a/pkg/config/config.go b/pkg/config/config.go index b3779b14..2268ac72 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -34,6 +34,7 @@ import ( "github.com/livekit/livekit-server/pkg/sfu/pacer" "github.com/livekit/livekit-server/pkg/sfu/streamallocator" "github.com/livekit/mediatransportutil/pkg/rtcconfig" + "github.com/livekit/protocol/agent" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" redisLiveKit "github.com/livekit/protocol/redis" @@ -64,6 +65,7 @@ type Config struct { TURN TURNConfig `yaml:"turn,omitempty"` Ingress IngressConfig `yaml:"ingress,omitempty"` SIP SIPConfig `yaml:"sip,omitempty"` + Agents AgentsConfig `yaml:"agents,omitempty"` WebHook webhook.WebHookConfig `yaml:"webhook,omitempty"` NodeSelector NodeSelectorConfig `yaml:"node_selector,omitempty"` KeyFile string `yaml:"key_file,omitempty"` @@ -273,6 +275,10 @@ type IngressConfig struct { type SIPConfig struct{} +type AgentsConfig struct { + WorkerToken agent.WorkerTokenConfig `yaml:"worker_token,omitempty"` +} + type APIConfig struct { // amount of time to wait for API to execute, default 2s 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") } } + if c.String("agents-jwt-keys") != "" { + conf.Agents.WorkerToken.Keys = c.String("agents-jwt-keys") + } if c.IsSet("region") { conf.Region = c.String("region") } diff --git a/pkg/service/agentservice.go b/pkg/service/agentservice.go index 414d1d7b..2d99354e 100644 --- a/pkg/service/agentservice.go +++ b/pkg/service/agentservice.go @@ -34,6 +34,7 @@ import ( "github.com/livekit/livekit-server/pkg/rtc" "github.com/livekit/livekit-server/pkg/rtc/types" "github.com/livekit/livekit-server/version" + pagent "github.com/livekit/protocol/agent" "github.com/livekit/protocol/auth" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" @@ -44,9 +45,18 @@ import ( type AgentSocketUpgrader struct { 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 { // allow connections from any origin, since script may be hosted anywhere // 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 if !websocket.IsWebSocketUpgrade(r) { w.WriteHeader(404) - return nil, 0, false + return } // require a claim claims := GetGrants(r.Context()) if claims == nil || claims.Video == nil || !claims.Video.Agent { 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 conn, err := u.Upgrader.Upgrade(w, r, responseHeader) if err != nil { 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 { - 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 { @@ -102,8 +123,8 @@ func DispatchAgentWorkerSignal(c agent.SignalConn, h agent.WorkerSignalHandler, return true } -func HandshakeAgentWorker(c agent.SignalConn, serverInfo *livekit.ServerInfo, protocol agent.WorkerProtocolVersion, l logger.Logger) (r agent.WorkerRegistration, ok bool) { - wr := agent.NewWorkerRegisterer(c, serverInfo, protocol) +func HandshakeAgentWorker(c agent.SignalConn, serverInfo *livekit.ServerInfo, registration agent.WorkerRegistration, l logger.Logger) (r agent.WorkerRegistration, ok bool) { + wr := agent.NewWorkerRegisterer(c, serverInfo, registration) if err := c.SetReadDeadline(wr.Deadline()); err != nil { return } @@ -152,12 +173,17 @@ type workerKey struct { jobType livekit.JobType } -func NewAgentService(conf *config.Config, +func NewAgentService( + conf *config.Config, currentNode routing.LocalNode, bus psrpc.MessageBus, keyProvider auth.KeyProvider, ) (*AgentService, error) { - s := &AgentService{} + s := &AgentService{ + upgrader: AgentSocketUpgrader{ + WorkerTokenProvider: pagent.NewWorkerTokenProvider(currentNode.NodeID(), conf.Agents.WorkerToken), + }, + } serverInfo := &livekit.ServerInfo{ Edition: livekit.ServerInfo_Standard, @@ -184,9 +210,9 @@ func NewAgentService(conf *config.Config, return s, nil } -func (s *AgentService) ServeHTTP(writer http.ResponseWriter, r *http.Request) { - if conn, protocol, ok := s.upgrader.Upgrade(writer, r, nil); ok { - s.HandleConnection(r.Context(), NewWSSignalConnection(conn), protocol) +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) conn.Close() } } @@ -214,8 +240,8 @@ func NewAgentHandler( } } -func (h *AgentHandler) HandleConnection(ctx context.Context, conn agent.SignalConn, protocol agent.WorkerProtocolVersion) { - registration, ok := HandshakeAgentWorker(conn, h.serverInfo, protocol, h.logger) +func (h *AgentHandler) HandleConnection(ctx context.Context, conn agent.SignalConn, registration agent.WorkerRegistration) { + registration, ok := HandshakeAgentWorker(conn, h.serverInfo, registration, h.logger) if !ok { return }