Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion cmd/lk/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -1258,7 +1258,10 @@ func restartAgent(ctx context.Context, cmd *cli.Command) error {
AgentId: agentID,
})
if err != nil {
return err
if twerr, ok := err.(twirp.Error); ok {
return fmt.Errorf("unable to restart agent: %s", twerr.Msg())
}
return fmt.Errorf("unable to restart agent: %w", err)
}
if !resp.Success {
return fmt.Errorf("failed to restart agent: %s", resp.Message)
Expand Down
220 changes: 198 additions & 22 deletions cmd/lk/agent_user_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import (
"io"
"io/fs"
"net/http"
"regexp"
"strconv"
"strings"
"time"

Expand All @@ -41,10 +43,12 @@ import (
// commands do (see telephony_user_auth.go): the SDK client implements it with
// an API key, and userAuthAgentAPI under --user-auth. userAuthAgentAPI calls
// the Public API's AgentService, which checks the user's role on the project
// itself, for the reads it serves: the agents, their versions, secret names
// and build logs, and the project's client settings. It sends every other
// call through the bridge for now. A method moves to AgentService by calling
// a.client in place of a.bridge.
// itself, for the reads and writes it serves: the agents, their versions,
// secret names and build logs, the project's client settings, and restart,
// rollback, promote, delete and secret updates. It sends every other call,
// such as create, deploy, a runtime log and private links, through the
// bridge for now. A method moves to AgentService by calling a.client in
// place of a.bridge.

// agentAPI is what the cloud agent commands call.
type agentAPI interface {
Expand Down Expand Up @@ -205,33 +209,187 @@ func (a *userAuthAgentAPI) ListAgentSecrets(ctx context.Context, req *livekit.Li
return &livekit.ListAgentSecretsResponse{Secrets: secrets}, nil
}

// UpdateAgentSecrets sets req.Secrets and removes req.Remove through
// AgentService, which lets only a project admin change secrets. AgentService
// only merges, so an update with req.Overwrite, which replaces every secret,
// goes through the bridge, which also needs a project admin.
func (a *userAuthAgentAPI) UpdateAgentSecrets(ctx context.Context, req *livekit.UpdateAgentSecretsRequest) (*livekit.UpdateAgentSecretsResponse, error) {
res, err := a.bridge.UpdateAgentSecrets(ctx, req)
return res, bridgeError(err)
if req.GetOverwrite() {
res, err := a.bridge.UpdateAgentSecrets(ctx, req)
return res, bridgeError(err)
}
if err := a.updateSecrets(ctx, req.GetAgentId(), req.GetSecrets(), req.GetRemove()); err != nil {
return nil, err
}
return &livekit.UpdateAgentSecretsResponse{Success: true}, nil
}

// UpdateAgent merges req.Secrets into the agent's secrets through
// AgentService's UpdateAgentSecrets, which a project admin may call, or,
// with no secrets, restarts the agent through AgentService's RestartAgent,
// which a WRITE member may call. Either rolls the agent, as cloud agents'
// UpdateAgent does with an API key, but neither is that call: cloud agents'
// UpdateAgent also saves the agent and marks its production deployment
// Updating, with secrets or without. lk sends no regions, which cloud agents
// ignores.
func (a *userAuthAgentAPI) UpdateAgent(ctx context.Context, req *livekit.UpdateAgentRequest) (*livekit.UpdateAgentResponse, error) {
res, err := a.bridge.UpdateAgent(ctx, req)
return res, bridgeError(err)
if len(req.GetSecrets()) == 0 {
if _, err := a.RestartAgent(ctx, &livekit.RestartAgentRequest{AgentId: req.GetAgentId()}); err != nil {
return nil, err
}
return &livekit.UpdateAgentResponse{Success: true}, nil
}
if err := a.updateSecrets(ctx, req.GetAgentId(), req.GetSecrets(), nil); err != nil {
return nil, err
}
return &livekit.UpdateAgentResponse{Success: true}, nil
}

func (a *userAuthAgentAPI) updateSecrets(ctx context.Context, agentID string, set []*livekit.AgentSecret, remove []string) error {
err := a.client.UpdateAgentSecrets(ctx, a.projectID, agentID, set, remove)
if violations := public.FieldViolations(err); len(violations) > 0 {
return secretsError(err, violations, set, remove)
}
return agentWriteError(err, agentID, projectAdmin, builderSecrets)
}

// secretsError is err, AgentService's refusal of the secrets in set and
// remove, with a line for each of its violations that names the secret by
// name, not by its index in the request. Violations that read the same, such
// as one for each copy of a secret named twice, get one line.
func secretsError(err error, violations []public.FieldViolation, set []*livekit.AgentSecret, remove []string) error {
var b strings.Builder
b.WriteString("invalid secrets:")
seen := make(map[string]bool, len(violations))
for _, v := range violations {
line := secretViolation(v, set, remove)
if seen[line] {
continue
}
seen[line] = true
b.WriteString("\n ")
b.WriteString(line)
}
return &rewordedError{msg: b.String(), err: err}
}

// rewordedError reads as msg, and unwraps to err, the Public API's refusal.
type rewordedError struct {
msg string
err error
}

func (e *rewordedError) Error() string { return e.msg }
func (e *rewordedError) Unwrap() error { return e.err }

// secretFieldPattern matches a violation's field: set[i] or remove[i], then
// the field of the secret in set, if any.
var secretFieldPattern = regexp.MustCompile(`^(set|remove)\[(\d+)\](?:\.(\w+))?$`)

// secretViolation words v as "secret NAME: FIELD DESCRIPTION", such as
// "secret 1KEY: name must have only letters, ...", or, for a field it
// doesn't know, as the API names it.
func secretViolation(v public.FieldViolation, set []*livekit.AgentSecret, remove []string) string {
asSent := v.Field + ": " + v.Description
m := secretFieldPattern.FindStringSubmatch(v.Field)
if m == nil {
return asSent
}
i, err := strconv.Atoi(m[2])
if err != nil {
return asSent
}
switch {
case m[1] == "set" && m[3] != "" && i < len(set):
return fmt.Sprintf("secret %s: %s %s", set[i].GetName(), m[3], v.Description)
case m[1] == "remove" && m[3] == "" && i < len(remove):
return fmt.Sprintf("secret %s to remove: name %s", remove[i], v.Description)
}
return asSent
}

// RestartAgent restarts the agent through AgentService, which a WRITE member
// may call.
func (a *userAuthAgentAPI) RestartAgent(ctx context.Context, req *livekit.RestartAgentRequest) (*livekit.RestartAgentResponse, error) {
res, err := a.bridge.RestartAgent(ctx, req)
return res, bridgeError(err)
if err := a.client.RestartAgent(ctx, a.projectID, req.GetAgentId()); err != nil {
return nil, agentWriteError(err, req.GetAgentId(), projectWriter, builderRestart)
}
return &livekit.RestartAgentResponse{Success: true}, nil
}

// RollbackAgent rolls the agent's production deployment back to req.Version
// through AgentService, which a WRITE member may call.
func (a *userAuthAgentAPI) RollbackAgent(ctx context.Context, req *livekit.RollbackAgentRequest) (*livekit.RollbackAgentResponse, error) {
res, err := a.bridge.RollbackAgent(ctx, req)
return res, bridgeError(err)
if err := a.client.RollbackAgent(ctx, a.projectID, req.GetAgentId(), req.GetVersion()); err != nil {
return nil, agentWriteError(err, req.GetAgentId(), projectWriter, builderDeployVersion)
}
return &livekit.RollbackAgentResponse{Success: true}, nil
}

// PromoteAgent promotes the version that srcDeployment runs to production
// through AgentService, which a WRITE member may call. AgentService promotes
// only to production, so a promote to another deployment, which lk doesn't
// make, goes through the bridge.
func (a *userAuthAgentAPI) PromoteAgent(ctx context.Context, agentID, srcDeployment, dstDeployment string) error {
return bridgeError(a.bridge.PromoteAgent(ctx, agentID, srcDeployment, dstDeployment))
if deploymentName(dstDeployment) != productionDeployment {
return bridgeError(a.bridge.PromoteAgent(ctx, agentID, srcDeployment, dstDeployment))
}
if _, err := a.client.PromoteAgent(ctx, a.projectID, agentID, srcDeployment); err != nil {
return agentWriteError(err, agentID, projectWriter, builderDeployVersion)
}
Comment on lines +334 to +339

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Meh. Can't we fix the API?

return nil
}

// DeleteAgent deletes the agent, or its deployment req.Deployment, through
// AgentService, which lets only a project admin delete one.
func (a *userAuthAgentAPI) DeleteAgent(ctx context.Context, req *livekit.DeleteAgentRequest) (*livekit.DeleteAgentResponse, error) {
res, err := a.bridge.DeleteAgent(ctx, req)
return res, bridgeError(err)
if err := a.client.DeleteAgent(ctx, a.projectID, req.GetAgentId(), req.GetDeployment()); err != nil {
return nil, agentWriteError(err, req.GetAgentId(), projectAdmin, builderDelete)
Comment on lines +346 to +347

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Whole-agent deletion suggested for deployment

When Agent Builder refuses a deployment-only delete, DeleteAgent recommends deleting the whole agent. Following that advice with session auth and confirming deletes every saved version as well.

Learn more

The deleteAgent command uses --deployment to distinguish deleting one deployment from deleting the whole agent. The Public API delete operation documents a refusal when Agent Builder manages the agent. On that refusal, the CLI uses the same recovery hint for both scopes. The Builder command provided by the companion PR deletes the agent, its versions, and its deployment, as documented by AgentBuilderServiceDeleteAgent.

Example: An admin requests deletion of staging from CA_1. The API refuses because the agent is managed as AB_1. If the admin follows the Builder delete hint with --user-auth and confirms, the operation removes AB_1 and all its versions, not just staging.

Recommended fix: Use a deployment-specific refusal when req.GetDeployment() is nonempty. Do not suggest a whole-agent delete in that case. Add a refusal script that sends --deployment staging and checks that the error does not suggest Builder deletion.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}
return &livekit.DeleteAgentResponse{Success: true}, nil
}

// agentWriteError is agentServiceError, except that AgentService's refusal
// of a write to agentID, an Agent Builder agent, reads as builderError words
// it, with instead.
func agentWriteError(err error, agentID, who string, instead builderWrite) error {
if public.IsAgentBuilderAgent(err) {
return builderError(err, agentID, instead)
}
return agentServiceError(err, who)
}

// builderWrite is what lk says to do instead of a write that AgentService
// refuses for an Agent Builder agent, given its Agent Builder ID: the lk
// agent builder command that makes the write, or that there is none.
type builderWrite func(builderID string) string

func builderDeployVersion(id string) string {
return "; deploy one of its versions with `lk agent builder deploy " + id + " --version VERSION_ID`"
}

func builderDelete(id string) string {
return "; delete it with `lk agent builder delete " + id + "`"
}

func builderSecrets(id string) string {
return "; update its secrets with `lk agent builder update-secrets " + id + "`"
}
Comment on lines +375 to +377

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Missing Agent Builder secrets command

When Agent Builder refuses a secret update, builderSecrets points to lk agent builder update-secrets. The companion Builder CLI does not register that command, so the suggested recovery fails.

Learn more

Both UpdateAgentSecrets and UpdateAgent use the shared secrets write path for a merge. On an Agent Builder refusal, the path prints a Builder subcommand. The dependency branch origin/topherhindman/devx-973-builder-commands has no update-secrets subcommand, even though AgentBuilderServiceUpdateAgentSecrets is available in the REST client. The refusal script asserts only the error text, so it cannot catch the unavailable command.

Example: An admin runs lk --user-auth agent update-secrets --id CA_1 --secrets API_TOKEN=example and receives a hint to run lk agent builder update-secrets AB_1. Even with --user-auth, the companion CLI has no such subcommand.

Recommended fix: Until the Builder secrets command is implemented and included in the merge dependency, give a supported recovery path, such as the Agent Builder dashboard.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.


func builderRestart(string) string {
return ", which the API can't restart"
}

// builderError is err, AgentService's refusal of a write to agentID, an
// Agent Builder agent, worded with the Agent Builder agent's ID, which err
// names, and instead. The Public API's words name its own RPC, which an lk
// user doesn't call, so they stay in the error that it wraps.
func builderError(err error, agentID string, instead builderWrite) error {
id := public.AgentBuilderID(err)
if id == "" {
id = "AGENT_ID"
}
return &rewordedError{msg: fmt.Sprintf("agent %s is Agent Builder agent %s%s", agentID, id, instead(id)), err: err}
}

// GetClientSettings reads the project's settings for creating and deploying
Expand Down Expand Up @@ -359,13 +517,32 @@ func bridgeError(err error) error {
if !errors.As(err, &refused) || !public.IsPermissionDenied(refused) {
return err
}
return fmt.Errorf("signed in, this command needs %s (%w). "+
"A project API key works meanwhile: pass --legacy-auth", projectAdmin, refused)
return needsError(refused, projectAdmin, "A project API key works meanwhile: pass --legacy-auth")
}

// needsError is refused, the Public API's refusal of a member whose role on
// the project is too low, worded as "signed in, this
// command needs <who>", then apiKey. It quotes refused unless refused names
// only the role that who names, such as "this needs ADMIN on the project"
// for projectAdmin; on a server that checks permissions, refused names them.
func needsError(refused *public.APIError, who, apiKey string) error {
msg := "signed in, this command needs " + who
if refused.Error() != lacksRolePrefix+roles[who]+" on the project" {
msg += " (" + refused.Error() + ")"
}
return &rewordedError{msg: msg + ". " + apiKey, err: refused}
}

// projectAdmin is who may make a call that needs the ADMIN role on the
// project, as a refusal names them.
const projectAdmin = "a project admin"
// projectAdmin and projectWriter are who may make a call that needs the
// ADMIN or the WRITE role on the project, as a refusal names them.
const (
projectAdmin = "a project admin"
projectWriter = "write access to the project"
)

// roles maps projectAdmin and projectWriter to the role that the Public API
// names.
var roles = map[string]string{projectAdmin: "ADMIN", projectWriter: "WRITE"}

// agentServiceError is err from a call to AgentService, worded as
// cloudAPIError words it, except that the refusal of a member whose role on
Expand All @@ -377,8 +554,7 @@ const projectAdmin = "a project admin"
func agentServiceError(err error, who string) error {
var refused *public.APIError
if errors.As(err, &refused) && public.IsPermissionDenied(refused) && strings.HasPrefix(refused.Message, lacksRolePrefix) {
return fmt.Errorf("signed in, this command needs %s (%w). "+
"A project API key also works: pass --legacy-auth", who, refused)
return needsError(refused, who, "A project API key also works: pass --legacy-auth")
}
return cloudAPIError(err)
}
Expand Down
Loading
Loading