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)",
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",
+1 -1
View File
@@ -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
+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/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=
+2 -2
View File
@@ -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
}
+14 -12
View File
@@ -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{
+9
View File
@@ -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")
}
+42 -16
View File
@@ -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
}