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
55 changes: 44 additions & 11 deletions cmd/lk/agent_private_link.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"errors"
"fmt"
"strconv"

Expand Down Expand Up @@ -228,19 +229,43 @@ func createPrivateLink(ctx context.Context, cmd *cli.Command) error {
return nil
}

func listPrivateLinks(ctx context.Context, cmd *cli.Command) error {
resp, err := privateLinksClient.ListPrivateLinks(ctx, &lkproto.ListPrivateLinksRequest{})
if err != nil {
return formatPrivateLinkClientError("list", err)
}
// errHealthUnread is the health error of a link that the Public API lists
// without its health.
var errHealthUnread = errors.New("LiveKit could not read its health")

healthByID := make(map[string]*lkproto.PrivateLinkStatus, len(resp.Items))
// privateLinksWithHealth lists the private links, with the health of each,
// or the error that reading it returned. A privateLinkHealthLister lists
// them with their health in one call; with any other privateLinkAPI, lk
// reads the health of each link with its own call.
func privateLinksWithHealth(ctx context.Context, api privateLinkAPI) ([]*lkproto.PrivateLink, map[string]*lkproto.PrivateLinkStatus, map[string]error, error) {
healthByID := make(map[string]*lkproto.PrivateLinkStatus)
healthErrByID := make(map[string]error)
if lister, ok := api.(privateLinkHealthLister); ok {
listed, err := lister.ListPrivateLinksWithHealth(ctx)
if err != nil {
return nil, nil, nil, err
}
links := make([]*lkproto.PrivateLink, 0, len(listed))
for _, l := range listed {
links = append(links, l.Link)
if l.Status != nil {
healthByID[l.Link.GetPrivateLinkId()] = l.Status
} else {
healthErrByID[l.Link.GetPrivateLinkId()] = errHealthUnread
}
}
return links, healthByID, healthErrByID, nil
}

resp, err := api.ListPrivateLinks(ctx, &lkproto.ListPrivateLinksRequest{})
if err != nil {
return nil, nil, nil, err
}
for _, link := range resp.Items {
if link == nil || link.PrivateLinkId == "" {
continue
}
health, healthErr := privateLinksClient.GetPrivateLinkStatus(ctx, &lkproto.GetPrivateLinkStatusRequest{
health, healthErr := api.GetPrivateLinkStatus(ctx, &lkproto.GetPrivateLinkStatusRequest{
PrivateLinkId: link.PrivateLinkId,
})
if healthErr != nil {
Expand All @@ -251,15 +276,23 @@ func listPrivateLinks(ctx context.Context, cmd *cli.Command) error {
healthByID[link.PrivateLinkId] = health.Value
}
}
return resp.Items, healthByID, healthErrByID, nil
}

func listPrivateLinks(ctx context.Context, cmd *cli.Command) error {
links, healthByID, healthErrByID, err := privateLinksWithHealth(ctx, privateLinksClient)
if err != nil {
return formatPrivateLinkClientError("list", err)
}

if cmd.Bool("json") {
type privateLinkWithHealth struct {
PrivateLink *lkproto.PrivateLink `json:"private_link"`
Status *lkproto.PrivateLinkStatus `json:"health"`
HealthError string `json:"health_error,omitempty"`
}
items := make([]privateLinkWithHealth, 0, len(resp.Items))
for _, link := range resp.Items {
items := make([]privateLinkWithHealth, 0, len(links))
for _, link := range links {
if link == nil {
continue
}
Expand All @@ -276,12 +309,12 @@ func listPrivateLinks(ctx context.Context, cmd *cli.Command) error {
return nil
}

if len(resp.Items) == 0 {
if len(links) == 0 {
out.Status("No private links found")
return nil
}

rows := buildPrivateLinkListRows(resp.Items, healthByID, healthErrByID)
rows := buildPrivateLinkListRows(links, healthByID, healthErrByID)
table := util.CreateTable().Headers("ID", "Name", "Region", "Cloud Region", "Port", "Endpoint", "DNS", "Health", "Updated At", "Reason").Rows(rows...)
out.Result(table)
return nil
Expand Down
135 changes: 135 additions & 0 deletions cmd/lk/agent_private_link_user_auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Copyright 2026 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/require"

"github.com/livekit/livekit-cli/v2/pkg/public"
"github.com/livekit/protocol/livekit"
)

// sdkPrivateLinks is a privateLinkAPI that, as the SDK client, lists links
// without their health, and answers each link's health with its own call.
type sdkPrivateLinks struct {
privateLinkAPI
links []*livekit.PrivateLink
health map[string]*livekit.PrivateLinkStatus
calls []string
}

func (s *sdkPrivateLinks) ListPrivateLinks(context.Context, *livekit.ListPrivateLinksRequest) (*livekit.ListPrivateLinksResponse, error) {
s.calls = append(s.calls, "list")
return &livekit.ListPrivateLinksResponse{Items: s.links}, nil
}

func (s *sdkPrivateLinks) GetPrivateLinkStatus(_ context.Context, req *livekit.GetPrivateLinkStatusRequest) (*livekit.GetPrivateLinkStatusResponse, error) {
s.calls = append(s.calls, "status "+req.PrivateLinkId)
if h, ok := s.health[req.PrivateLinkId]; ok {
return &livekit.GetPrivateLinkStatusResponse{Value: h}, nil
}
return nil, errors.New("status unavailable")
}

var healthy = &livekit.PrivateLinkStatus{Status: livekit.PrivateLinkStatus_PRIVATE_LINK_STATUS_HEALTHY}

// With the SDK, lk reads each link's health with its own call, and keeps
// the error of one it can't read. Under --user-auth, the one list call
// brings each link's health, and a link without one has errHealthUnread.
func TestPrivateLinksWithHealth(t *testing.T) {
sdk := &sdkPrivateLinks{
links: []*livekit.PrivateLink{{PrivateLinkId: "PL_1"}, {PrivateLinkId: "PL_2"}},
health: map[string]*livekit.PrivateLinkStatus{"PL_1": healthy},
}
links, health, healthErr, err := privateLinksWithHealth(context.Background(), sdk)
require.NoError(t, err)
require.Len(t, links, 2)
require.Equal(t, map[string]*livekit.PrivateLinkStatus{"PL_1": healthy}, health)
require.EqualError(t, healthErr["PL_2"], "status unavailable")
require.Equal(t, []string{"list", "status PL_1", "status PL_2"}, sdk.calls)

var requests []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests = append(requests, r.Method+" "+r.URL.Path)
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"items":[`+
`{"link":{"privateLinkId":"PL_1"},"status":{"status":"PRIVATE_LINK_STATUS_HEALTHY"}},`+
`{"link":{"privateLinkId":"PL_2"}}]}`)
}))
t.Cleanup(srv.Close)
client, err := public.New(srv.URL, "st_1")
require.NoError(t, err)
a := &userAuthAgentAPI{client: client, projectID: "p_1"}

links, health, healthErr, err = privateLinksWithHealth(context.Background(), a)
require.NoError(t, err)
require.Equal(t, []string{"PL_1", "PL_2"}, []string{links[0].PrivateLinkId, links[1].PrivateLinkId})
require.Equal(t, livekit.PrivateLinkStatus_PRIVATE_LINK_STATUS_HEALTHY, health["PL_1"].Status)
require.NotContains(t, health, "PL_2")
require.Equal(t, map[string]error{"PL_2": errHealthUnread}, healthErr)
require.Equal(t, []string{"GET /v0/projects/p_1/private-links"}, requests, "one call, no status calls")

listed, err := a.ListPrivateLinks(context.Background(), &livekit.ListPrivateLinksRequest{})
require.NoError(t, err)
require.Len(t, listed.Items, 2, "ListPrivateLinks lists the links without their health")
}

// Under --user-auth, the other private link calls answer in the SDK's
// shapes, and a member below WRITE hears that the command needs write
// access.
func TestUserAuthPrivateLinks(t *testing.T) {
var status int
var body string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = io.WriteString(w, body)
}))
t.Cleanup(srv.Close)
client, err := public.New(srv.URL, "st_1")
require.NoError(t, err)
a := &userAuthAgentAPI{client: client, projectID: "p_1"}
ctx := context.Background()

status, body = http.StatusOK, `{"privateLink":{"link":{"privateLinkId":"PL_1","name":"db"}}}`
created, err := a.CreatePrivateLink(ctx, &livekit.CreatePrivateLinkRequest{Name: "db"})
require.NoError(t, err)
require.Equal(t, "PL_1", created.PrivateLink.PrivateLinkId)

status, body = http.StatusOK, `{"status":{"status":"PRIVATE_LINK_STATUS_HEALTHY"}}`
health, err := a.GetPrivateLinkStatus(ctx, &livekit.GetPrivateLinkStatusRequest{PrivateLinkId: "PL_1"})
require.NoError(t, err)
require.Equal(t, livekit.PrivateLinkStatus_PRIVATE_LINK_STATUS_HEALTHY, health.Value.Status)

status, body = http.StatusOK, `{}`
_, err = a.DestroyPrivateLink(ctx, &livekit.DestroyPrivateLinkRequest{PrivateLinkId: "PL_1"})
require.NoError(t, err)

status, body = http.StatusForbidden, `{"code":7,"message":"this needs WRITE on the project"}`
_, err = a.ListPrivateLinks(ctx, &livekit.ListPrivateLinksRequest{})
require.EqualError(t, err, "signed in, this command needs write access to the project. "+
"A project API key also works: pass --legacy-auth")

status, body = http.StatusNotFound, `{"code":5,"message":"private link not found"}`
_, err = a.DestroyPrivateLink(ctx, &livekit.DestroyPrivateLinkRequest{PrivateLinkId: "PL_9"})
require.EqualError(t, err, "private link not found")
}
76 changes: 59 additions & 17 deletions cmd/lk/agent_user_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ import (
// 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, and create and deploy from
// source. It sends every other call, such as a prebuilt image push, 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.
// source, and private links. It sends every other call, a prebuilt image
// push and a runtime log, 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 @@ -81,19 +81,28 @@ type agentAPI interface {
StreamLogs(ctx context.Context, logType, agentID, deployment string, w io.Writer, serverRegion string) error
}

// privateLinkAPI is what the agent private-link commands call.
// privateLinkAPI is what the agent private-link commands call. One that is
// also a privateLinkHealthLister lists the links with their health in one
// call.
type privateLinkAPI interface {
CreatePrivateLink(ctx context.Context, req *livekit.CreatePrivateLinkRequest) (*livekit.CreatePrivateLinkResponse, error)
ListPrivateLinks(ctx context.Context, req *livekit.ListPrivateLinksRequest) (*livekit.ListPrivateLinksResponse, error)
GetPrivateLinkStatus(ctx context.Context, req *livekit.GetPrivateLinkStatusRequest) (*livekit.GetPrivateLinkStatusResponse, error)
DestroyPrivateLink(ctx context.Context, req *livekit.DestroyPrivateLinkRequest) (*livekit.DestroyPrivateLinkResponse, error)
}

// privateLinkHealthLister lists the private links, each with its health, or
// without it when LiveKit couldn't read it.
type privateLinkHealthLister interface {
ListPrivateLinksWithHealth(ctx context.Context) ([]public.PrivateLink, error)
}

var (
_ agentAPI = (*cloudagents.Client)(nil)
_ agentAPI = (*userAuthAgentAPI)(nil)
_ privateLinkAPI = (*cloudagents.Client)(nil)
_ privateLinkAPI = (*userAuthAgentAPI)(nil)
_ agentAPI = (*cloudagents.Client)(nil)
_ agentAPI = (*userAuthAgentAPI)(nil)
_ privateLinkAPI = (*cloudagents.Client)(nil)
_ privateLinkAPI = (*userAuthAgentAPI)(nil)
_ privateLinkHealthLister = (*userAuthAgentAPI)(nil)
)

// newAgentAPI returns the cloud agents API for pc: server-sdk-go's client
Expand Down Expand Up @@ -802,24 +811,57 @@ func deployedVersion(info *livekit.AgentInfo, deployment string) string {
return ""
}

// The private link methods call AgentService, which, as the dashboard, lets
// a WRITE member manage and read the project's private links.

// CreatePrivateLink leaves out the health that AgentService returns with the
// link: cloud agents' CreatePrivateLink returns none, and lk prints the same
// in both modes.
func (a *userAuthAgentAPI) CreatePrivateLink(ctx context.Context, req *livekit.CreatePrivateLinkRequest) (*livekit.CreatePrivateLinkResponse, error) {
res, err := a.bridge.CreatePrivateLink(ctx, req)
return res, bridgeError(err)
link, err := a.client.CreatePrivateLink(ctx, a.projectID, req)
if err != nil {
return nil, agentServiceError(err, projectWriter)
}
return &livekit.CreatePrivateLinkResponse{PrivateLink: link.Link}, nil
}

func (a *userAuthAgentAPI) ListPrivateLinks(ctx context.Context, req *livekit.ListPrivateLinksRequest) (*livekit.ListPrivateLinksResponse, error) {
res, err := a.bridge.ListPrivateLinks(ctx, req)
return res, bridgeError(err)
// ListPrivateLinks lists the private links without their health. The list
// command reads their health from ListPrivateLinksWithHealth instead.
func (a *userAuthAgentAPI) ListPrivateLinks(ctx context.Context, _ *livekit.ListPrivateLinksRequest) (*livekit.ListPrivateLinksResponse, error) {
links, err := a.ListPrivateLinksWithHealth(ctx)
if err != nil {
return nil, err
}
res := &livekit.ListPrivateLinksResponse{Items: make([]*livekit.PrivateLink, 0, len(links))}
for _, link := range links {
res.Items = append(res.Items, link.Link)
}
return res, nil
}

// ListPrivateLinksWithHealth lists the private links, each with its health,
// which AgentService reads for every link itself.
func (a *userAuthAgentAPI) ListPrivateLinksWithHealth(ctx context.Context) ([]public.PrivateLink, error) {
links, err := a.client.ListPrivateLinks(ctx, a.projectID)
if err != nil {
return nil, agentServiceError(err, projectWriter)
}
return links, nil
}

func (a *userAuthAgentAPI) GetPrivateLinkStatus(ctx context.Context, req *livekit.GetPrivateLinkStatusRequest) (*livekit.GetPrivateLinkStatusResponse, error) {
res, err := a.bridge.GetPrivateLinkStatus(ctx, req)
return res, bridgeError(err)
status, err := a.client.GetPrivateLinkStatus(ctx, a.projectID, req.GetPrivateLinkId())
if err != nil {
return nil, agentServiceError(err, projectWriter)
}
return &livekit.GetPrivateLinkStatusResponse{Value: status}, nil
}

func (a *userAuthAgentAPI) DestroyPrivateLink(ctx context.Context, req *livekit.DestroyPrivateLinkRequest) (*livekit.DestroyPrivateLinkResponse, error) {
res, err := a.bridge.DestroyPrivateLink(ctx, req)
return res, bridgeError(err)
if err := a.client.DeletePrivateLink(ctx, a.projectID, req.GetPrivateLinkId()); err != nil {
return nil, agentServiceError(err, projectWriter)
}
return &livekit.DestroyPrivateLinkResponse{}, nil
}

// bridgeError is err from a call through the token bridge, or, when the
Expand Down
2 changes: 1 addition & 1 deletion cmd/lk/agent_user_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func TestUserAuthAgentAPIRefusalNeedsAdmin(t *testing.T) {
require.NoError(t, err)
a := &userAuthAgentAPI{client: client, projectID: pc.ProjectId, bridge: bridge}

_, err = a.ListPrivateLinks(context.Background(), &livekit.ListPrivateLinksRequest{})
_, err = a.RegisterAgent(context.Background(), nil, []string{"us-east"})
require.EqualError(t, err, wantAdminRefusal)
require.True(t, public.IsPermissionDenied(err), "the Public API's refusal stays the cause")

Expand Down
4 changes: 4 additions & 0 deletions cmd/lk/script_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,10 @@ var publicAPIRoutes = []struct {
{http.MethodPost, regexp.MustCompile(`^/v0/projects/[^/]+/agents$`), func() any { return new(oapi.LivekitPublicapiAgentsV1AgentsCreateResponse) }},
{http.MethodPost, regexp.MustCompile(`^/v0/projects/[^/]+/agents/[^/]+:deploy$`), func() any { return new(oapi.LivekitPublicapiAgentsV1AgentsDeployResponse) }},
{http.MethodPost, regexp.MustCompile(`^/v0/projects/[^/]+/agents/[^/]+:startBuild$`), func() any { return new(oapi.LivekitPublicapiAgentsV1AgentBuildsStartResponse) }},
{http.MethodPost, regexp.MustCompile(`^/v0/projects/[^/]+/private-links$`), func() any { return new(oapi.LivekitPublicapiAgentsV1PrivateLinksCreateResponse) }},
{http.MethodGet, regexp.MustCompile(`^/v0/projects/[^/]+/private-links$`), func() any { return new(oapi.LivekitPublicapiAgentsV1PrivateLinksListResponse) }},
{http.MethodDelete, regexp.MustCompile(`^/v0/projects/[^/]+/private-links/[^/]+$`), func() any { return new(oapi.LivekitPublicapiAgentsV1PrivateLinksDeleteResponse) }},
{http.MethodGet, regexp.MustCompile(`^/v0/projects/[^/]+/private-links/[^/]+/status$`), func() any { return new(oapi.LivekitPublicapiAgentsV1PrivateLinksGetStatusResponse) }},
{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
Expand Up @@ -2,8 +2,8 @@
# 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.
# such as update-secrets --overwrite, 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"}'
Expand All @@ -13,9 +13,9 @@ respond GET http://publicapi.test/v0/projects/p_1/agents/CA_1/secrets 403 '{"cod
stderr '^unable to list agent secrets: signed in, this command needs a project admin\. A project API key also works: pass --legacy-auth$'
! stderr 'access to this project'

! exec lk --user-auth agent private-link list
! exec lk --user-auth agent update-secrets --id CA_1 --secrets API_TOKEN=s3cr3t --overwrite --yes
! stdout .
stderr '^unable to list private link: signed in, this command needs a project admin\. A project API key works meanwhile: pass --legacy-auth$'
stderr '^unable to update agent secrets: signed in, this command needs a project admin\. A project API key works meanwhile: pass --legacy-auth$'
! stderr 'access to this project'

requests
Expand Down
Loading
Loading