-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathcloud.go
More file actions
423 lines (374 loc) · 9.96 KB
/
cloud.go
File metadata and controls
423 lines (374 loc) · 9.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright 2024 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"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"time"
"github.com/charmbracelet/huh"
"github.com/pkg/browser"
"github.com/urfave/cli/v3"
authutil "github.com/livekit/livekit-cli/v2/pkg/auth"
"github.com/livekit/livekit-cli/v2/pkg/config"
"github.com/livekit/livekit-cli/v2/pkg/util"
"github.com/livekit/protocol/auth"
)
type ClaimAccessKeyResponse struct {
Key string
Secret string
ProjectId string
ProjectName string
OwnerId string
Description string
URL string
}
const (
cloudAPIServerURL = "https://cloud-api.livekit.io"
cloudDashboardURL = "https://cloud.livekit.io"
createTokenEndpoint = "/cli/auth"
claimKeyEndpoint = "/cli/claim"
confirmAuthEndpoint = "/cli/confirm-auth"
revokeKeyEndpoint = "/cli/revoke"
)
var (
revoke bool
timeout int = 60 * 15
interval int = 4
serverURL string = cloudAPIServerURL
dashboardURL string = cloudDashboardURL
authClient AuthClient
CloudCommands = []*cli.Command{
{
Name: "cloud",
Usage: "Interact with LiveKit Cloud services",
Commands: []*cli.Command{
{
Name: "auth",
Usage: "Authenticate LiveKit Cloud account to link your projects",
Before: initAuth,
Action: handleAuth,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "id",
Usage: "Project `ID` to authenticate. If not provided, you can choose from your existing projects in the browser",
Required: false,
},
&cli.BoolFlag{
Name: "revoke",
Aliases: []string{"R"},
Destination: &revoke,
},
&cli.IntFlag{
Name: "timeout",
Aliases: []string{"t"},
Usage: "Number of `SECONDS` to attempt authentication before giving up",
Destination: &timeout,
Value: 60 * 15,
},
&cli.IntFlag{
Name: "poll-interval",
Aliases: []string{"i"},
Usage: "Number of `SECONDS` between poll requests to verify authentication",
Destination: &interval,
Value: 4,
},
&cli.StringFlag{
Name: "server-url",
Value: cloudAPIServerURL,
Destination: &serverURL,
Hidden: true,
},
&cli.StringFlag{
Name: "dashboard-url",
Value: cloudDashboardURL,
Destination: &dashboardURL,
Hidden: true,
},
},
},
},
},
}
)
type VerificationToken struct {
Identifier string
Token string
Expires int64
DeviceName string
}
type AuthClient struct {
client *http.Client
baseURL string
verificationToken VerificationToken
}
func (a *AuthClient) GetVerificationToken(deviceName string) (*VerificationToken, error) {
reqURL, err := url.Parse(a.baseURL + createTokenEndpoint)
if err != nil {
return nil, err
}
params := url.Values{}
params.Add("device_name", deviceName)
reqURL.RawQuery = params.Encode()
resp, err := a.client.Post(reqURL.String(), "application/json", nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(&a.verificationToken)
if err != nil {
return nil, err
}
return &a.verificationToken, nil
}
func (a *AuthClient) ClaimCliKey(ctx context.Context) (*ClaimAccessKeyResponse, error) {
if a.verificationToken.Token == "" || time.Now().Unix() > a.verificationToken.Expires {
return nil, errors.New("session expired")
}
reqURL, err := url.Parse(a.baseURL + claimKeyEndpoint)
if err != nil {
return nil, err
}
params := url.Values{}
params.Add("t", a.verificationToken.Token)
reqURL.RawQuery = params.Encode()
req, err := http.NewRequestWithContext(ctx, "POST", reqURL.String(), nil)
if err != nil {
return nil, err
}
resp, err := a.client.Do(req)
if resp != nil && resp.StatusCode == 404 {
return nil, errors.New("access denied")
}
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusUnauthorized {
// Not yet approved
return nil, nil
}
ak := &ClaimAccessKeyResponse{}
err = json.NewDecoder(resp.Body).Decode(&ak)
if err != nil {
return nil, err
}
return ak, nil
}
func (a *AuthClient) Deauthenticate(ctx context.Context, projectName, token string) error {
reqURL, err := url.Parse(a.baseURL + revokeKeyEndpoint)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "DELETE", reqURL.String(), nil)
req.Header = authutil.NewHeaderWithToken(token)
if err != nil {
return err
}
resp, err := a.client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New("access denied")
}
return cliConfig.RemoveProject(projectName)
}
func NewAuthClient(client *http.Client, baseURL string) *AuthClient {
a := &AuthClient{
client: client,
baseURL: baseURL,
}
return a
}
func initAuth(ctx context.Context, cmd *cli.Command) (context.Context, error) {
authClient = *NewAuthClient(&http.Client{}, serverURL)
return nil, nil
}
func handleAuth(ctx context.Context, cmd *cli.Command) error {
if revoke {
if _, err := loadProjectConfig(ctx, cmd); err != nil {
return err
}
token, err := requireToken(ctx, cmd)
if err != nil {
return err
}
return authClient.Deauthenticate(ctx, project.Name, token)
}
return tryAuthIfNeeded(ctx, cmd)
}
func requireToken(_ context.Context, cmd *cli.Command) (string, error) {
if project == nil {
var err error
project, err = loadProjectDetails(cmd)
if err != nil {
return "", err
}
}
// construct a token from the chosen project, using the hashed secret as the identity
// as a means of preventing any old token generated with this key/secret pair from
// deleting it
hash, err := util.HashString(project.APISecret)
if err != nil {
return "", err
}
at := auth.NewAccessToken(project.APIKey, project.APISecret).SetIdentity(hash)
token, err := at.ToJWT()
if err != nil {
return "", err
}
return token, nil
}
func tryAuthIfNeeded(ctx context.Context, cmd *cli.Command) error {
if _, err := loadProjectConfig(ctx, cmd); err != nil {
return err
}
// get devicename
if err := huh.NewInput().
Title("What is the name of this device?").
Description("A short name you can use to find and manage generated API keys on the LiveKit Cloud dashboard").
Value(&cliConfig.DeviceName).
WithTheme(util.Theme).
Run(); err != nil {
return err
}
// remember device name for next time
if err := cliConfig.PersistIfNeeded(); err != nil {
return err
}
fmt.Println("Device:", cliConfig.DeviceName)
// request token
fmt.Println("Requesting verification token...")
token, err := authClient.GetVerificationToken(cliConfig.DeviceName)
if err != nil {
return err
}
projectId := cmd.String("id")
if projectId == "" && cmd.Args().Present() {
projectId = cmd.Args().First()
}
authURL, err := generateConfirmURL(token.Token, projectId)
if err != nil {
return err
}
// poll for keys
fmt.Printf("Please confirm access by visiting:\n\n %s\n\n", authURL.String())
_ = browser.OpenURL(authURL.String()) // discard result; this will fail in headless environments
var ak *ClaimAccessKeyResponse
err = util.Await(
"Awaiting confirmation...",
ctx,
func(ctx context.Context) error {
var pollErr error
ak, pollErr = pollClaim(ctx, cmd)
return pollErr
},
)
if err != nil {
return err
}
if ak == nil {
return errors.New("operation cancelled")
}
var isDefault bool
if err := huh.NewConfirm().
Title("Make this project default?").
Value(&isDefault).
Inline(true).
WithTheme(util.Theme).
Run(); err != nil {
return err
}
// make sure name is unique
name, err := util.URLSafeName(ak.URL)
if err != nil {
return err
}
if cliConfig.ProjectExists(name) {
if err := huh.NewInput().
Title("Choose a different alias").
Description(fmt.Sprintf("You've already configured a project with the alias %q.", name)).
Value(&name).
Validate(func(s string) error {
if cliConfig.ProjectExists(s) {
return errors.New("project name already exists")
}
return nil
}).
WithTheme(util.Theme).
Run(); err != nil {
return err
}
}
// persist to config file
cliConfig.Projects = append(cliConfig.Projects, config.ProjectConfig{
Name: name,
ProjectId: ak.ProjectId,
APIKey: ak.Key,
APISecret: ak.Secret,
URL: ak.URL,
})
if isDefault {
cliConfig.DefaultProject = name
}
if err = cliConfig.PersistIfNeeded(); err != nil {
return err
}
return err
}
func generateConfirmURL(token, projectId string) (*url.URL, error) {
base, err := url.Parse(dashboardURL + confirmAuthEndpoint)
if err != nil {
return nil, err
}
params := url.Values{}
params.Add("t", token)
if projectId != "" {
params.Add("project_id", projectId)
}
base.RawQuery = params.Encode()
return base, nil
}
func pollClaim(ctx context.Context, _ *cli.Command) (*ClaimAccessKeyResponse, error) {
claim := make(chan *ClaimAccessKeyResponse)
cancel := make(chan error)
// every <interval> seconds, poll
go func() {
for {
time.Sleep(time.Duration(interval) * time.Second)
ak, err := authClient.ClaimCliKey(ctx)
if err != nil {
cancel <- err
return
}
if ak != nil {
claim <- ak
}
}
}()
select {
case <-time.After(time.Duration(timeout) * time.Second):
return nil, errors.New("session claim timed out")
case err := <-cancel:
return nil, err
case accessKey := <-claim:
return accessKey, nil
}
}