-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathlogin.go
More file actions
489 lines (418 loc) · 16.8 KB
/
Copy pathlogin.go
File metadata and controls
489 lines (418 loc) · 16.8 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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
package cli
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"github.com/pkg/browser"
"github.com/spf13/cobra"
"github.com/auth0/auth0-cli/internal/ansi"
"github.com/auth0/auth0-cli/internal/auth"
"github.com/auth0/auth0-cli/internal/config"
"github.com/auth0/auth0-cli/internal/keyring"
"github.com/auth0/auth0-cli/internal/prompt"
)
var (
loginTenantDomain = Flag{
Name: "Tenant Domain",
LongForm: "domain",
Help: "Tenant domain of the application when authenticating via client credentials.",
IsRequired: false,
AlwaysPrompt: false,
}
loginClientID = Flag{
Name: "Client ID",
LongForm: "client-id",
Help: "Client ID of the application when authenticating via client credentials.",
IsRequired: false,
AlwaysPrompt: false,
}
loginClientSecret = Flag{
Name: "Client Secret",
LongForm: "client-secret",
Help: "Client secret of the application when authenticating via client credentials.",
IsRequired: false,
AlwaysPrompt: false,
}
loginClientAssertionPrivateKey = Flag{
Name: "Client Assertion Private Key",
LongForm: "client-assertion-private-key",
Help: "Client Assertion Private key with either a file path or direct content when authenticating via Private key JWT.",
IsRequired: false,
AlwaysPrompt: false,
}
loginClientAssertionSigningAlg = Flag{
Name: "Client Assertion Signing Algorithm",
LongForm: "client-assertion-signing-alg",
Help: "Client Assertion Signing Algorithm when authenticating via Private key JWT. Supported algorithms: RS256, RS384, PS256.",
IsRequired: false,
AlwaysPrompt: false,
}
loginAdditionalScopes = Flag{
Name: "Additional Scopes",
LongForm: "scopes",
Help: "Additional scopes to request when authenticating via device code flow. By default, only scopes for first-class functions are requested. Primarily useful when using the api command to execute arbitrary Management API requests.",
IsRequired: false,
AlwaysPrompt: false,
}
)
type LoginInputs struct {
Domain string
ClientID string
ClientSecret string
ClientAssertionPrivateKey string
ClientAssertionSigningAlg string
AdditionalScopes []string
}
func (i *LoginInputs) isLoggingInWithAdditionalScopes() bool {
return len(i.AdditionalScopes) > 0
}
func loginCmd(cli *cli) *cobra.Command {
var inputs LoginInputs
cmd := &cobra.Command{
Use: "login",
Args: cobra.NoArgs,
Short: "Authenticate the Auth0 CLI",
Long: "Authenticates the Auth0 CLI using either personal credentials (user login) or client credentials (machine login)." +
"\n\nUse user login on personal machines or interactive environments (not supported for Private Cloud users).\n" +
"Use machine login for servers, CI, or any non-interactive environments — " +
"this is the recommended method for Private Cloud users.\n\n",
Example: ` auth0 login
auth0 login --domain <tenant-domain> --client-id <client-id> --client-secret <client-secret>
auth0 login --domain <tenant-domain> --client-id <client-id> --client-assertion-signing-alg RS256 --client-assertion-private-key <path-to-private-key>
auth0 login --domain <tenant-domain> --client-id <client-id> --client-assertion-signing-alg RS256 --client-assertion-private-key <client-assertion-private-key>
auth0 login --scopes "read:client_grants,create:client_grants"`,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
const (
loginAsUser = "As a user"
loginAsMachine = "As a machine"
clientSecret = "Client Secret"
clientJWT = "Client Assertion"
)
var (
shouldLoginAsUser = false
shouldLoginAsMachineJWT = false
shouldLoginAsMachineSecret = false
shouldLoginAsMachine = false
selectedLoginType = ""
)
/*
Based on the initial inputs we'd like to determine if
it's a machine login or a user login
If we successfully determine it, we don't need to prompt the user.
The --no-input flag add strict restriction that we shall not take any further input after
initial command.
Hence, the flow diverges into two based on no-input flag's value.
*/
if cli.noInput {
switch {
case inputs.Domain != "" && inputs.ClientID != "" && inputs.ClientSecret != "":
shouldLoginAsMachineSecret = true
case inputs.Domain != "" && inputs.ClientID != "" && inputs.ClientAssertionSigningAlg != "" && inputs.ClientAssertionPrivateKey != "":
shouldLoginAsMachineJWT = true
case inputs.Domain != "" &&
inputs.ClientID == "" && inputs.ClientSecret == "" &&
inputs.ClientAssertionSigningAlg == "" && inputs.ClientAssertionPrivateKey == "":
shouldLoginAsUser = true
case inputs.Domain != "" || inputs.ClientID != "" || inputs.ClientSecret != "" || inputs.ClientAssertionSigningAlg != "" || inputs.ClientAssertionPrivateKey != "":
return fmt.Errorf("for machine login, provide domain with either (client-id, client-secret) or (client-id, client-assertion-signing-alg, client-assertion-private-key)")
default:
/*
If no flags are passed along with --no-input, it is defaulted to user login flow.
*/
shouldLoginAsUser = true
}
} else {
if inputs.ClientAssertionSigningAlg != "" || inputs.ClientAssertionPrivateKey != "" {
shouldLoginAsMachineJWT = true
}
if inputs.ClientSecret != "" {
shouldLoginAsMachineSecret = true
}
if inputs.ClientID != "" {
shouldLoginAsMachine = true
}
}
// If additional scopes are passed we mark shouldLoginAsUser flag to be true.
if inputs.isLoggingInWithAdditionalScopes() {
shouldLoginAsUser = true
}
/*
If we are unable to determine if it's a user login or a machine login
based on all the evaluation above, we go on to prompt the user and
determine if it's LoginAsUser or LoginAsMachine
*/
if !shouldLoginAsUser && !shouldLoginAsMachineSecret && !shouldLoginAsMachineJWT && !shouldLoginAsMachine {
cli.renderer.Output(
fmt.Sprintf(
"%s\n\n%s\n%s\n\n%s\n%s\n%s\n%s\n\n",
ansi.Bold("✪ Welcome to the Auth0 CLI 🎊"),
"An Auth0 tenant is required to operate this CLI.",
"To create one, visit: https://auth0.com/signup.",
"You may authenticate to your tenant either as a user with personal",
"credentials or as a machine via client credentials. For more",
"information about authenticating the CLI to your tenant, visit",
"the docs: https://auth0.github.io/auth0-cli/auth0_login.html",
),
)
promptText := prompt.SelectInput(
"", "How would you like to authenticate?",
"Authenticating as a user is recommended for local use.\nMachine auth is recommended for CI/CD.",
[]string{loginAsUser, loginAsMachine}, loginAsUser, true,
)
if err := prompt.AskOne(promptText, &selectedLoginType); err != nil {
return handleInputError(err)
}
}
switch {
case shouldLoginAsUser || selectedLoginType == loginAsUser:
if _, err := RunLoginAsUser(ctx, cli, inputs.AdditionalScopes, inputs.Domain); err != nil {
return fmt.Errorf("failed to start user login: %w", err)
}
default:
if err := loginTenantDomain.Ask(cmd, &inputs.Domain, nil); err != nil {
return err
}
// Prompt client credentials method if not clear yet.
if !shouldLoginAsMachineSecret && !shouldLoginAsMachineJWT {
promptText := prompt.SelectInput(
"", "How would you like to provide client credentials?",
"", []string{clientSecret, clientJWT}, clientSecret, true,
)
if err := prompt.AskOne(promptText, &selectedLoginType); err != nil {
return handleInputError(err)
}
if selectedLoginType == clientJWT {
shouldLoginAsMachineJWT = true
} else {
shouldLoginAsMachineSecret = true
}
}
if shouldLoginAsMachineJWT {
if err := RunLoginAsMachineJWT(ctx, inputs, cli, cmd); err != nil {
return fmt.Errorf("failed to start JWT machine login: %w", err)
}
} else if shouldLoginAsMachineSecret {
if err := RunLoginAsMachineSecret(ctx, inputs, cli, cmd); err != nil {
return fmt.Errorf("failed to start secret machine login: %w", err)
}
}
}
cli.tracker.TrackCommandRun(cmd, cli.Config.InstallID)
if len(cli.Config.Tenants) > 1 {
cli.renderer.Infof("%s Switch between authenticated tenants with `auth0 tenants use <tenant>`",
ansi.Faint("Hint:"),
)
}
return nil
},
}
loginTenantDomain.RegisterString(cmd, &inputs.Domain, "")
loginClientID.RegisterString(cmd, &inputs.ClientID, "")
loginClientSecret.RegisterString(cmd, &inputs.ClientSecret, "")
loginClientAssertionSigningAlg.RegisterString(cmd, &inputs.ClientAssertionSigningAlg, "")
loginClientAssertionPrivateKey.RegisterString(cmd, &inputs.ClientAssertionPrivateKey, "")
loginAdditionalScopes.RegisterStringSlice(cmd, &inputs.AdditionalScopes, []string{})
cmd.MarkFlagsMutuallyExclusive("client-id", "scopes")
cmd.MarkFlagsMutuallyExclusive("client-secret", "scopes")
cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
_ = cmd.Flags().MarkHidden("tenant")
cmd.Parent().HelpFunc()(cmd, args)
})
return cmd
}
func ensureAuth0URL(input string) (string, error) {
if input == "" {
return "https://*.auth0.com/api/v2/", nil
}
input = strings.TrimPrefix(input, "http://")
input = strings.TrimPrefix(input, "https://")
input = strings.TrimSuffix(input, "/api/v2")
// Check if the input ends with auth0.com .
if !strings.HasSuffix(input, "auth0.com") {
return "", fmt.Errorf("not a valid auth0.com domain")
}
// Extract the domain part without any path.
domainParts := strings.Split(input, "/")
domain := domainParts[0]
// Return the formatted URL.
return fmt.Sprintf("https://%s/api/v2/", domain), nil
}
// RunLoginAsUser runs the login flow guiding the user through the process
// by showing the login instructions, opening the browser.
func RunLoginAsUser(ctx context.Context, cli *cli, additionalScopes []string, domain string) (config.Tenant, error) {
domain, err := ensureAuth0URL(domain)
if err != nil {
return config.Tenant{}, err
}
state, err := auth.GetDeviceCode(ctx, http.DefaultClient, additionalScopes, domain)
if err != nil {
return config.Tenant{}, fmt.Errorf("failed to get the device code: %w", err)
}
message := fmt.Sprintf("\n%s\n\n",
"Verify "+ansi.Bold(state.UserCode)+" code in opened browser window to complete authentication.",
)
cli.renderer.Output(message)
if cli.noInput {
message = "Open the following URL in a browser: %s\n"
cli.renderer.Infof(message, ansi.Green(state.VerificationURI))
} else {
message = "%s to open the browser to log in or %s to quit..."
cli.renderer.Infof(message, ansi.Green("Press Enter"), ansi.Red("^C"))
if _, err = fmt.Scanln(); err != nil {
return config.Tenant{}, err
}
if err = browser.OpenURL(state.VerificationURI); err != nil {
message = "Couldn't open the URL, please do it manually: %s."
cli.renderer.Warnf(message, state.VerificationURI)
}
}
var result auth.Result
err = ansi.Spinner("Waiting for the login to complete in the browser", func() error {
result, err = auth.WaitUntilUserLogsIn(ctx, http.DefaultClient, state)
return err
})
if err != nil {
return config.Tenant{}, fmt.Errorf("login error: %w", err)
}
cli.renderer.Newline()
cli.renderer.Infof("Successfully logged in.")
cli.renderer.Infof("Tenant: %s", result.Domain)
cli.renderer.Newline()
tenant := config.Tenant{
Name: result.Tenant,
Domain: result.Domain,
ExpiresAt: result.ExpiresAt,
Scopes: append(auth.RequiredScopes, additionalScopes...),
}
if err := keyring.StoreAccessToken(result.Domain, result.AccessToken); err != nil {
// In case we don't have a keyring, we want the
// access token to be saved in the config file.
tenant.AccessToken = result.AccessToken
}
err = cli.Config.AddTenant(tenant)
if err != nil {
return config.Tenant{}, fmt.Errorf("failed to add the tenant to the config: %w", err)
}
cli.tracker.TrackFirstLogin(cli.Config.InstallID, "As-User")
if cli.Config.DefaultTenant != result.Domain {
message = fmt.Sprintf(
"Your default tenant is %s. Do you want to change it to %s?",
cli.Config.DefaultTenant,
result.Domain,
)
if confirmed := prompt.Confirm(message); !confirmed {
return config.Tenant{}, nil
}
if err := cli.Config.SetDefaultTenant(result.Domain); err != nil {
message = "Failed to set the default tenant, please try 'auth0 tenants use %s' instead: %w"
cli.renderer.Warnf(message, result.Domain, err)
}
}
return tenant, nil
}
// RunLoginAsMachineSecret facilitates the authentication process using client credentials (client ID, client secret).
func RunLoginAsMachineSecret(ctx context.Context, inputs LoginInputs, cli *cli, cmd *cobra.Command) error {
if err := loginClientID.Ask(cmd, &inputs.ClientID, nil); err != nil {
return err
}
if err := loginClientSecret.AskPassword(cmd, &inputs.ClientSecret); err != nil {
return err
}
token, err := auth.GetAccessTokenFromClientCreds(
ctx,
auth.ClientCredentials{
ClientID: inputs.ClientID,
ClientSecret: inputs.ClientSecret,
Domain: inputs.Domain,
},
)
if err != nil {
return fmt.Errorf("failed to fetch access token using client credentials. \n\nEnsure that the provided client-id, client-secret and domain are correct. \n\nerror: %w", err)
}
if err = keyring.StoreClientSecret(inputs.Domain, inputs.ClientSecret); err != nil {
cli.renderer.Warnf("Could not store the client secret and the access token to the keyring: %s", err)
cli.renderer.Warnf("Expect to login again when your access token expires.")
}
tenant := config.Tenant{
Name: strings.Split(inputs.Domain, ".")[0],
Domain: inputs.Domain,
ExpiresAt: token.ExpiresAt,
ClientID: inputs.ClientID,
}
if err := keyring.StoreAccessToken(inputs.Domain, token.AccessToken); err != nil {
// In case we don't have a keyring, we want the
// access token to be saved in the config file.
tenant.AccessToken = token.AccessToken
}
if err = cli.Config.AddTenant(tenant); err != nil {
return fmt.Errorf("failed to save tenant data: %w", err)
}
cli.renderer.Newline()
cli.renderer.Infof("Successfully logged in.")
cli.renderer.Infof("Tenant: %s", inputs.Domain)
cli.tracker.TrackFirstLogin(cli.Config.InstallID, "As-Machine")
return nil
}
// RunLoginAsMachineJWT facilitates the authentication process using the client credentials
// with Private Key JWT authentication flow. (client ID, client Assertion Private key, client Assertion Signing Algorithm).
func RunLoginAsMachineJWT(ctx context.Context, inputs LoginInputs, cli *cli, cmd *cobra.Command) error {
if err := loginClientID.Ask(cmd, &inputs.ClientID, nil); err != nil {
return err
}
if err := loginClientAssertionSigningAlg.Select(cmd, &inputs.ClientAssertionSigningAlg, []string{"RS256", "RS384", "PS256"}, nil); err != nil {
return err
}
if err := loginClientAssertionPrivateKey.Ask(cmd, &inputs.ClientAssertionPrivateKey, nil); err != nil {
return err
}
domain := "https://" + inputs.Domain
if !strings.HasPrefix(inputs.ClientAssertionPrivateKey, "-----BEGIN ") {
inputs.ClientAssertionPrivateKey = readPrivateKey(inputs.ClientAssertionPrivateKey)
}
token, err := auth.GetAccessTokenFromClientPrivateJWT(
auth.PrivateKeyJwtTokenSource{
Ctx: ctx,
ClientID: inputs.ClientID,
ClientAssertionSigningAlg: inputs.ClientAssertionSigningAlg,
URI: domain,
Audience: domain + "/api/v2/",
ClientAssertionPrivateKey: inputs.ClientAssertionPrivateKey,
},
)
if err != nil {
return fmt.Errorf("failed to fetch access token using client credentials with Private Key. \n\nEnsure that the provided client-id, client-assertion-private-key, client-assertion-signing-alg and domain are correct. \n\nerror: %w", err)
}
tenant := config.Tenant{
Name: strings.Split(inputs.Domain, ".")[0],
Domain: inputs.Domain,
ExpiresAt: token.ExpiresAt,
ClientID: inputs.ClientID,
}
if err := keyring.StoreAccessToken(inputs.Domain, token.AccessToken); err != nil {
// In case we don't have a keyring, we want the
// access token to be saved in the config file.
tenant.AccessToken = token.AccessToken
}
if err = cli.Config.AddTenant(tenant); err != nil {
return fmt.Errorf("failed to save tenant data: %w", err)
}
cli.renderer.Newline()
cli.renderer.Infof("Successfully logged in.")
cli.renderer.Infof("Tenant: %s", inputs.Domain)
cli.tracker.TrackFirstLogin(cli.Config.InstallID, "As-Machine")
return nil
}
func readPrivateKey(path string) string {
// Read the content of the file.
content, err := os.ReadFile(path)
if err != nil {
// Handle the error appropriately, e.g., log it or return an empty string with an error.
fmt.Println("Error reading private key file:", err)
return ""
}
// Return the content.
return string(content)
}