-
Notifications
You must be signed in to change notification settings - Fork 55
/
cli.go
454 lines (372 loc) · 10.5 KB
/
cli.go
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package cli
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/auth0/auth0-cli/internal/ansi"
"github.com/auth0/auth0-cli/internal/auth"
"github.com/auth0/auth0-cli/internal/auth0"
"github.com/auth0/auth0-cli/internal/buildinfo"
"github.com/auth0/auth0-cli/internal/display"
"github.com/lestrrat-go/jwx/jwt"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"gopkg.in/auth0.v5/management"
)
const (
userAgent = "Auth0 CLI"
accessTokenExpThreshold = 5 * time.Minute
)
// config defines the exact set of tenants, access tokens, which only exists
// for a particular user's machine.
type config struct {
DefaultTenant string `json:"default_tenant"`
Tenants map[string]tenant `json:"tenants"`
}
// tenant is the cli's concept of an auth0 tenant. The fields are tailor fit
// specifically for interacting with the management API.
type tenant struct {
Name string `json:"name"`
Domain string `json:"domain"`
AccessToken string `json:"access_token,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
Apps map[string]app `json:"apps,omitempty"`
DefaultAppID string `json:"default_app_id,omitempty"`
}
type app struct {
FirstRuns map[string]bool `json:"first_runs"`
}
var errUnauthenticated = errors.New("Not logged in. Try 'auth0 login'.")
// cli provides all the foundational things for all the commands in the CLI,
// specifically:
//
// 1. A management API instance (e.g. go-auth0/auth0)
// 2. A renderer (which provides ansi, coloring, etc).
//
// In addition, it stores a reference to all the flags passed, e.g.:
//
// 1. --format
// 2. --tenant
// 3. --debug
//
type cli struct {
// core primitives exposed to command builders.
api *auth0.API
renderer *display.Renderer
// set of flags which are user specified.
debug bool
tenant string
format string
force bool
noInput bool
// config state management.
initOnce sync.Once
errOnce error
path string
config config
}
// isLoggedIn encodes the domain logic for determining whether or not we're
// logged in. This might check our config storage, or just in memory.
func (c *cli) isLoggedIn() bool {
// No need to check errors for initializing context.
_ = c.init()
if c.tenant == "" {
return false
}
// Parse the access token for the tenant.
t, err := jwt.ParseString(c.config.Tenants[c.tenant].AccessToken)
if err != nil {
return false
}
// Check if token is valid.
if err = jwt.Validate(t, jwt.WithIssuer("https://auth0.auth0.com/")); err != nil {
return false
}
return true
}
// setup will try to initialize the config context, as well as figure out if
// there's a readily available tenant. A management API SDK instance is initialized IFF:
//
// 1. A tenant is found.
// 2. The tenant has an access token.
func (c *cli) setup(ctx context.Context) error {
if err := c.init(); err != nil {
return err
}
t, err := c.getTenant()
if err != nil {
return err
}
if t.AccessToken == "" {
return errUnauthenticated
}
// check if the stored access token is expired:
if isExpired(t.ExpiresAt, accessTokenExpThreshold) {
// use the refresh token to get a new access token:
tr := &auth.TokenRetriever{
Secrets: &auth.Keyring{},
Client: http.DefaultClient,
}
res, err := tr.Refresh(ctx, t.Name)
if err != nil {
// ask and guide the user through the login process:
c.renderer.Errorf("failed to renew access token, %s", err)
err = RunLogin(ctx, c, true)
if err != nil {
return err
}
} else {
// persist the updated tenant with renewed access token
t.AccessToken = res.AccessToken
t.ExpiresAt = time.Now().Add(
time.Duration(res.ExpiresIn) * time.Second,
)
err = c.addTenant(t)
if err != nil {
return err
}
}
}
// continue with the command setup:
if t.AccessToken != "" {
m, err := management.New(t.Domain,
management.WithStaticToken(t.AccessToken),
management.WithUserAgent(fmt.Sprintf("%v/%v", userAgent, strings.TrimPrefix(buildinfo.Version, "v"))))
if err != nil {
return err
}
c.api = auth0.NewAPI(m)
}
return err
}
// isExpired is true if now() + a threshold is after the given date
func isExpired(t time.Time, threshold time.Duration) bool {
return time.Now().Add(threshold).After(t)
}
// getTenant fetches the default tenant configured (or the tenant specified via
// the --tenant flag).
func (c *cli) getTenant() (tenant, error) {
if err := c.init(); err != nil {
return tenant{}, err
}
t, ok := c.config.Tenants[c.tenant]
if !ok {
return tenant{}, fmt.Errorf("Unable to find tenant: %s; run 'auth0 tenants use' to see your configured tenants or run 'auth0 login' to configure a new tenant", c.tenant)
}
if t.Apps == nil {
t.Apps = map[string]app{}
}
return t, nil
}
// listTenants fetches all of the configured tenants
func (c *cli) listTenants() ([]tenant, error) {
if err := c.init(); err != nil {
return []tenant{}, err
}
tenants := make([]tenant, 0, len(c.config.Tenants))
for _, t := range c.config.Tenants {
tenants = append(tenants, t)
}
return tenants, nil
}
// addTenant assigns an existing, or new tenant. This is expected to be called
// after a login has completed.
func (c *cli) addTenant(ten tenant) error {
// init will fail here with a `no tenant found` error if we're logging
// in for the first time and that's expected.
_ = c.init()
// If there's no existing DefaultTenant yet, might as well set the
// first successfully logged in tenant during onboarding.
if c.config.DefaultTenant == "" {
c.config.DefaultTenant = ten.Domain
}
// If we're dealing with an empty file, we'll need to initialize this
// map.
if c.config.Tenants == nil {
c.config.Tenants = map[string]tenant{}
}
c.config.Tenants[ten.Domain] = ten
if err := c.persistConfig(); err != nil {
return fmt.Errorf("unexpected error persisting config: %w", err)
}
return nil
}
func (c *cli) removeTenant(ten string) error {
// init will fail here with a `no tenant found` error if we're logging
// in for the first time and that's expected.
_ = c.init()
// If we're dealing with an empty file, we'll need to initialize this
// map.
if c.config.Tenants == nil {
c.config.Tenants = map[string]tenant{}
}
delete(c.config.Tenants, ten)
// If the default tenant is being removed, we'll pick the first tenant
// that's not the one being removed, and make that the new default.
if c.config.DefaultTenant == ten {
if len(c.config.Tenants) == 0 {
c.config.DefaultTenant = ""
} else {
Loop:
for t := range c.config.Tenants {
if t != ten {
c.config.DefaultTenant = t
break Loop
}
}
}
}
if err := c.persistConfig(); err != nil {
return fmt.Errorf("Unexpected error persisting config: %w", err)
}
tr := &auth.TokenRetriever{Secrets: &auth.Keyring{}}
if err := tr.Delete(ten); err != nil {
return fmt.Errorf("Unexpected error clearing tenant information: %w", err)
}
return nil
}
func (c *cli) isFirstCommandRun(clientID string, command string) (bool, error) {
tenant, err := c.getTenant()
if err != nil {
return false, err
}
if a, found := tenant.Apps[clientID]; found {
if a.FirstRuns[command] {
return false, nil
}
}
return true, nil
}
func (c *cli) setDefaultAppID(id string) error {
tenant, err := c.getTenant()
if err != nil {
return err
}
tenant.DefaultAppID = id
c.config.Tenants[tenant.Domain] = tenant
if err := c.persistConfig(); err != nil {
return fmt.Errorf("Unexpected error persisting config: %w", err)
}
return nil
}
func (c *cli) setFirstCommandRun(clientID string, command string) error {
tenant, err := c.getTenant()
if err != nil {
return err
}
if a, found := tenant.Apps[clientID]; found {
if a.FirstRuns == nil {
a.FirstRuns = map[string]bool{}
}
a.FirstRuns[command] = true
tenant.Apps[clientID] = a
} else {
tenant.Apps[clientID] = app{
FirstRuns: map[string]bool{
command: true,
},
}
}
c.config.Tenants[tenant.Domain] = tenant
if err := c.persistConfig(); err != nil {
return fmt.Errorf("Unexpected error persisting config: %w", err)
}
return nil
}
func (c *cli) persistConfig() error {
dir := filepath.Dir(c.path)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0700); err != nil {
return err
}
}
buf, err := json.MarshalIndent(c.config, "", " ")
if err != nil {
return err
}
if err := ioutil.WriteFile(c.path, buf, 0600); err != nil {
return err
}
return nil
}
func (c *cli) init() error {
c.initOnce.Do(func() {
// Initialize the context -- e.g. the configuration
// information, tenants, etc.
if c.errOnce = c.initContext(); c.errOnce != nil {
return
}
c.renderer.Tenant = c.tenant
cobra.EnableCommandSorting = false
})
// Determine what the desired output format is.
//
// NOTE(cyx): Since this isn't expensive to do, we don't need to put it
// inside initOnce.
format := strings.ToLower(c.format)
if format != "" && format != string(display.OutputFormatJSON) {
return fmt.Errorf("Invalid format. Use `--format=json` or omit this option to use the default format.")
}
c.renderer.Format = display.OutputFormat(format)
c.renderer.Tenant = c.tenant
// Once initialized, we'll keep returning the same err that was
// originally encountered.
return c.errOnce
}
func (c *cli) initContext() (err error) {
if c.path == "" {
c.path = path.Join(os.Getenv("HOME"), ".config", "auth0", "config.json")
}
if _, err := os.Stat(c.path); os.IsNotExist(err) {
return errUnauthenticated
}
var buf []byte
if buf, err = ioutil.ReadFile(c.path); err != nil {
return err
}
if err := json.Unmarshal(buf, &c.config); err != nil {
return err
}
if c.tenant == "" && c.config.DefaultTenant == "" {
return errUnauthenticated
}
if c.tenant == "" {
c.tenant = c.config.DefaultTenant
}
return nil
}
func canPrompt(cmd *cobra.Command) bool {
noInput, err := cmd.Root().Flags().GetBool("no-input")
if err != nil {
return false
}
return ansi.IsTerminal() && !noInput
}
func shouldPrompt(cmd *cobra.Command, flag string) bool {
return canPrompt(cmd) && !cmd.Flags().Changed(flag)
}
func shouldPromptWhenFlagless(cmd *cobra.Command, flag string) bool {
isSet := false
cmd.LocalFlags().VisitAll(func(f *pflag.Flag) {
if f.Changed {
isSet = true
}
})
return canPrompt(cmd) && !isSet
}
func prepareInteractivity(cmd *cobra.Command) {
if canPrompt(cmd) {
cmd.Flags().VisitAll(func(flag *pflag.Flag) {
_ = cmd.Flags().SetAnnotation(flag.Name, cobra.BashCompOneRequiredFlag, []string{"false"})
})
}
}