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
6 changes: 6 additions & 0 deletions cmd/lk/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -1354,6 +1354,12 @@ func getLogs(ctx context.Context, cmd *cli.Command) error {
return err
}

// Under --user-auth, lk reads a build log from the Public API by the
// agent's version, so it needs no deployment to stream from.
if logType := cmd.String("log-type"); logType == buildLogType && userAuthEnabled(cmd) {
return agentsClient.StreamLogs(ctx, logType, agentID, cmd.String("deployment"), os.Stdout, "")
}

response, err := agentsClient.ListAgents(ctx, &lkproto.ListAgentsRequest{
AgentId: agentID,
})
Expand Down
132 changes: 119 additions & 13 deletions cmd/lk/agent_user_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"io"
"io/fs"
"net/http"
"strings"
"time"

"github.com/urfave/cli/v3"
Expand All @@ -40,9 +41,10 @@ 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 ListAgents, and 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 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.

// agentAPI is what the cloud agent commands call.
type agentAPI interface {
Expand Down Expand Up @@ -174,14 +176,33 @@ func cloudAgentsInfo(info *livekit.AgentInfo) *livekit.AgentInfo {
return info
}

// ListAgentVersions lists the agent's versions through AgentService, which
// a READ member may call. The Public API leaves out the deploy time of a
// version that was never deployed, where cloud agents lists the zero time,
// so ListAgentVersions puts that back and the commands print the same in
// both modes.
func (a *userAuthAgentAPI) ListAgentVersions(ctx context.Context, req *livekit.ListAgentVersionsRequest) (*livekit.ListAgentVersionsResponse, error) {
res, err := a.bridge.ListAgentVersions(ctx, req)
return res, bridgeError(err)
versions, err := a.client.ListAgentVersions(ctx, a.projectID, req.GetAgentId())
if err != nil {
return nil, cloudAPIError(err)
}
for _, v := range versions {
if v.DeployedAt == nil {
v.DeployedAt = timestamppb.New(time.Time{})
}
}
return &livekit.ListAgentVersionsResponse{Versions: versions}, nil
}

// ListAgentSecrets lists the names of the agent's secrets through
// AgentService, which, as the dashboard, lets only a project admin list
// them.
func (a *userAuthAgentAPI) ListAgentSecrets(ctx context.Context, req *livekit.ListAgentSecretsRequest) (*livekit.ListAgentSecretsResponse, error) {
res, err := a.bridge.ListAgentSecrets(ctx, req)
return res, bridgeError(err)
secrets, err := a.client.ListAgentSecrets(ctx, a.projectID, req.GetAgentId())
if err != nil {
return nil, agentServiceError(err, projectAdmin)
}
return &livekit.ListAgentSecretsResponse{Secrets: secrets}, nil
}

func (a *userAuthAgentAPI) UpdateAgentSecrets(ctx context.Context, req *livekit.UpdateAgentSecretsRequest) (*livekit.UpdateAgentSecretsResponse, error) {
Expand Down Expand Up @@ -213,9 +234,11 @@ func (a *userAuthAgentAPI) DeleteAgent(ctx context.Context, req *livekit.DeleteA
return res, bridgeError(err)
}

func (a *userAuthAgentAPI) GetClientSettings(ctx context.Context, req *livekit.ClientSettingsRequest) (*livekit.ClientSettingsResponse, error) {
res, err := a.bridge.GetClientSettings(ctx, req)
return res, bridgeError(err)
// GetClientSettings reads the project's settings for creating and deploying
// an agent through AgentService, which a READ member may call.
func (a *userAuthAgentAPI) GetClientSettings(ctx context.Context, _ *livekit.ClientSettingsRequest) (*livekit.ClientSettingsResponse, error) {
res, err := a.client.GetAgentClientSettings(ctx, a.projectID)
return res, cloudAPIError(err)
}

func (a *userAuthAgentAPI) CreateAgent(ctx context.Context, source fs.FS, secrets []*livekit.AgentSecret, regions []string, attributes map[string]string, excludeFiles []string, buildLog io.Writer) (*livekit.CreateAgentResponse, error) {
Expand Down Expand Up @@ -243,8 +266,67 @@ func (a *userAuthAgentAPI) NewRegistryTransport(attributes map[string]string) ht
return a.bridge.NewRegistryTransport(attributes)
}

// StreamLogs writes the build log of the version that deployment runs
// through AgentService, which a READ member may call, and needs no
// serverRegion. A runtime log goes through the bridge: the Public API serves
// no runtime log stream.
func (a *userAuthAgentAPI) StreamLogs(ctx context.Context, logType, agentID, deployment string, w io.Writer, serverRegion string) error {
return bridgeError(a.bridge.StreamLogs(ctx, logType, agentID, deployment, w, serverRegion))
if logType != buildLogType {
return bridgeError(a.bridge.StreamLogs(ctx, logType, agentID, deployment, w, serverRegion))
}
agent, err := a.client.GetAgent(ctx, a.projectID, agentID)
if err != nil {
return cloudAPIError(err)
}
version := deployedVersion(agent.Cloud, deployment)
if version == "" {
return fmt.Errorf("no version deployed to the %s deployment of agent %s", deploymentName(deployment), agentID)
}
log, err := a.client.GetAgentBuildLog(ctx, a.projectID, agentID, version)
if err != nil {
return cloudAPIError(err)
}
if _, err := io.WriteString(w, log.Text); err != nil {
return err
}
if log.Text != "" && !strings.HasSuffix(log.Text, "\n") {
if _, err := io.WriteString(w, "\n"); err != nil {
return err
}
}
if log.Truncated {
out.Warnf("The build log of version %s is too long to show in full: this is its end.", version)
}
return nil
}

// buildLogType is the log type of a build log, as --log-type names it.
const buildLogType = "build"

// deploymentName is deployment, or productionDeployment for "".
func deploymentName(deployment string) string {
if deployment == "" {
return productionDeployment
}
return deployment
}

// deployedVersion returns the version that deployment ("" for production)
// of the agent info runs, as cloud agents finds the build log it streams
// when lk names no version: the version of the deployment's first region
// that has one, else, for production, the agent's version. It returns ""
// when the deployment runs no version.
func deployedVersion(info *livekit.AgentInfo, deployment string) string {
name := deploymentName(deployment)
for _, d := range info.GetAgentDeployments() {
if deploymentName(d.GetDeployment()) == name && d.GetVersion() != "" {
return d.GetVersion()
}
}
if name == productionDeployment {
return info.GetVersion()
}
return ""
}

func (a *userAuthAgentAPI) CreatePrivateLink(ctx context.Context, req *livekit.CreatePrivateLinkRequest) (*livekit.CreatePrivateLinkResponse, error) {
Expand Down Expand Up @@ -277,6 +359,30 @@ func bridgeError(err error) error {
if !errors.As(err, &refused) || !public.IsPermissionDenied(refused) {
return err
}
return fmt.Errorf("signed in, this command needs a project admin (%w). "+
"A project API key works meanwhile: pass --legacy-auth", refused)
return fmt.Errorf("signed in, this command needs %s (%w). "+
"A project API key works meanwhile: pass --legacy-auth", projectAdmin, 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"

// agentServiceError is err from a call to AgentService, worded as
// cloudAPIError words it, except that the refusal of a member whose role on
// the project is too low says that the command needs who, such as
// projectAdmin, not that the user lacks access to the project. The Public
// API words that refusal "this needs <role or permission> on the project".
// Any other refusal, such as of a suspended project, keeps cloudAPIError's
// words.
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 cloudAPIError(err)
}

// lacksRolePrefix starts the Public API's refusal of a member whose role on
// the project is too low.
const lacksRolePrefix = "this needs "
47 changes: 45 additions & 2 deletions cmd/lk/agent_user_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,11 @@ func TestUserAuthAgentAPIRefusalNeedsAdmin(t *testing.T) {
require.NoError(t, err)
a := &userAuthAgentAPI{client: client, projectID: pc.ProjectId, bridge: bridge}

_, err = a.ListAgentSecrets(context.Background(), &livekit.ListAgentSecretsRequest{AgentId: "CA_1"})
_, err = a.ListPrivateLinks(context.Background(), &livekit.ListPrivateLinksRequest{})
require.EqualError(t, err, wantAdminRefusal)
require.True(t, public.IsPermissionDenied(err), "the Public API's refusal stays the cause")

err = a.StreamLogs(context.Background(), "build", "CA_1", "", io.Discard, "")
err = a.StreamLogs(context.Background(), "deploy", "CA_1", "", io.Discard, "")
require.EqualError(t, err, wantAdminRefusal)

mu.Lock()
Expand Down Expand Up @@ -187,3 +187,46 @@ func TestUserAuthListAgentsCloudOnly(t *testing.T) {
require.Len(t, res.Agents, 1)
require.Equal(t, "CA_1", res.Agents[0].AgentId)
}

// The build log lk reads is the one cloud agents streams when lk names no
// version: that of the version the deployment runs, or for production, the
// agent's version.
func TestDeployedVersion(t *testing.T) {
info := &livekit.AgentInfo{
Version: "v3",
AgentDeployments: []*livekit.AgentDeployment{
{Region: "us-east", Version: "v2"},
{Region: "us-east", Deployment: "staging"},
{Region: "eu-central", Deployment: "staging", Version: "v4"},
{Region: "eu-central", Deployment: "production", Version: "v2"},
},
}
for deployment, want := range map[string]string{
"": "v2",
"production": "v2",
"staging": "v4",
"canary": "",
} {
require.Equal(t, want, deployedVersion(info, deployment), "deployment %q", deployment)
}
require.Equal(t, "v3", deployedVersion(&livekit.AgentInfo{Version: "v3"}, ""), "production falls back to the agent's version")
require.Empty(t, deployedVersion(&livekit.AgentInfo{Version: "v3"}, "staging"))
}

// AgentService's refusal of a member whose role is too low names who the
// command needs. Any other error is worded as cloudAPIError words it.
func TestAgentServiceError(t *testing.T) {
lacksRole := &public.APIError{Status: http.StatusForbidden, Message: "this needs ADMIN on the project"}
err := agentServiceError(lacksRole, projectAdmin)
require.EqualError(t, err, "signed in, this command needs a project admin (this needs ADMIN on the project). "+
"A project API key also works: pass --legacy-auth")
require.ErrorIs(t, err, lacksRole)

suspended := &public.APIError{Status: http.StatusForbidden, Message: "this project is suspended"}
require.Equal(t, cloudAPIError(suspended).Error(), agentServiceError(suspended, projectAdmin).Error())

notFound := &public.APIError{Status: http.StatusNotFound, Message: "agent not found"}
require.Equal(t, notFound, agentServiceError(notFound, projectAdmin))

require.NoError(t, agentServiceError(nil, projectAdmin))
}
4 changes: 4 additions & 0 deletions cmd/lk/script_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,10 @@ var publicAPIRoutes = []struct {
{http.MethodDelete, regexp.MustCompile(`^/v0/projects/[^/]+/phone-numbers/[^/]+$`), func() any { return new(oapi.LivekitPublicapiTelephonyV1PhoneNumbersReleaseResponse) }},
{http.MethodGet, regexp.MustCompile(`^/v0/projects/[^/]+/agents$`), func() any { return new(oapi.LivekitPublicapiAgentsV1AgentsListResponse) }},
{http.MethodGet, regexp.MustCompile(`^/v0/projects/[^/]+/agents/[^/]+$`), func() any { return new(oapi.LivekitPublicapiAgentsV1AgentsGetResponse) }},
{http.MethodGet, regexp.MustCompile(`^/v0/projects/[^/]+/agents/[^/]+/versions$`), func() any { return new(oapi.LivekitPublicapiAgentsV1AgentVersionsListResponse) }},
{http.MethodGet, regexp.MustCompile(`^/v0/projects/[^/]+/agents/[^/]+/versions/[^/]+/build-log$`), func() any { return new(oapi.LivekitPublicapiAgentsV1AgentBuildLogGetResponse) }},
{http.MethodGet, regexp.MustCompile(`^/v0/projects/[^/]+/agents/[^/]+/secrets$`), func() any { return new(oapi.LivekitPublicapiAgentsV1AgentSecretsListResponse) }},
{http.MethodGet, regexp.MustCompile(`^/v0/projects/[^/]+/agent-client-settings$`), func() any { return new(oapi.LivekitPublicapiAgentsV1AgentClientSettingsGetResponse) }},
{http.MethodGet, regexp.MustCompile(`^/v0/users/me$`), func() any { return new(oapi.LivekitPublicapiUsersV1GetCurrentUserResponse) }},
{http.MethodDelete, regexp.MustCompile(`^/v0/users/me/session-token$`), func() any { return new(oapi.LivekitPublicapiUsersV1SessionTokenRevokeResponse) }},
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
# Under --user-auth, an agent command that still goes through the token bridge
# needs the Agent.Admin grant, which the Public API gives only to a project
# admin. A member below it hears that, and that an API key works meanwhile,
# not that they lack access to the project. Nothing reaches cloud agents.
# Under --user-auth, an agent command that needs a project admin says so when
# the signed-in member is below it, and that an API key works too, not that
# they lack access to the project. agent secrets hears it from the Public
# API's AgentService. A command that still goes through the token bridge,
# such as private-link list, needs the Agent.Admin grant, which the Public API
# gives only to a project admin. Nothing reaches cloud agents.
env LK_AGENTS_URL=http://agents.test
respond POST http://publicapi.test/v0/projects/p_1/tokens 403 '{"code":7,"message":"this needs ADMIN on the project"}'
respond GET http://publicapi.test/v0/projects/p_1/agents/CA_1/secrets 403 '{"code":7,"message":"this needs ADMIN on the project"}'

! exec lk --user-auth agent secrets --id CA_1
! stdout .
stderr '^unable to list agent secrets: signed in, this command needs a project admin \(this needs ADMIN on the project\)\. A project API key works meanwhile: pass --legacy-auth$'
stderr '^unable to list agent secrets: signed in, this command needs a project admin \(this needs ADMIN on the project\)\. A project API key also works: pass --legacy-auth$'
! stderr 'access to this project'

! exec lk --user-auth agent restart --id CA_1
! exec lk --user-auth agent private-link list
! stdout .
stderr '^signed in, this command needs a project admin \(this needs ADMIN on the project\)\. A project API key works meanwhile: pass --legacy-auth$'
stderr '^unable to list private link: signed in, this command needs a project admin \(this needs ADMIN on the project\)\. A project API key works meanwhile: pass --legacy-auth$'
! stderr 'access to this project'

requests
cmp stdout want-requests
Expand All @@ -30,5 +34,5 @@ users:
alias: one
url: ws://one.test
-- want-requests --
POST http://publicapi.test/v0/projects/p_1/tokens bearer=st_1 project=p_1
GET http://publicapi.test/v0/projects/p_1/agents/CA_1/secrets bearer=st_1 project=p_1
POST http://publicapi.test/v0/projects/p_1/tokens bearer=st_1 project=p_1
13 changes: 6 additions & 7 deletions cmd/lk/testdata/script/agent-commands-with-user-auth.txtar
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# Under --user-auth, agent list calls the Public API's AgentService. The other
# cloud agent commands call cloud agents with a token the Public API creates
# for the session (the token bridge), not an API key, until the Public API
# serves them.
# Under --user-auth, agent list and agent secrets call the Public API's
# AgentService. The other cloud agent commands, such as private-link list,
# call cloud agents with a token the Public API creates for the session (the
# token bridge), not an API key, until the Public API serves them.
env LK_AGENTS_URL=http://agents.test
mint st_1
respond GET http://publicapi.test/v0/projects/p_1/agents 200 '{"items":[]}'
exec lk --user-auth agent list
stderr 'No agents found'

respond POST http://agents.test/twirp/livekit.CloudAgent/ListAgentSecrets 200 ''
respond GET http://publicapi.test/v0/projects/p_1/agents/CA_1/secrets 200 '{"items":[]}'
exec lk --user-auth agent secrets --id CA_1

respond POST http://agents.test/twirp/livekit.CloudAgent/ListPrivateLinks 200 ''
Expand All @@ -32,7 +32,6 @@ users:
url: ws://one.test
-- want-requests --
GET http://publicapi.test/v0/projects/p_1/agents bearer=st_1 project=p_1
POST http://publicapi.test/v0/projects/p_1/tokens bearer=st_1 project=p_1
POST http://agents.test/twirp/livekit.CloudAgent/ListAgentSecrets apikey=APImint_p_1
GET http://publicapi.test/v0/projects/p_1/agents/CA_1/secrets bearer=st_1 project=p_1
POST http://publicapi.test/v0/projects/p_1/tokens bearer=st_1 project=p_1
POST http://agents.test/twirp/livekit.CloudAgent/ListPrivateLinks apikey=APImint_p_1
Loading
Loading