/
auth_login.go
544 lines (477 loc) · 16.4 KB
/
auth_login.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
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package cmd
import (
"context"
"errors"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/MakeNowJust/heredoc/v2"
"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/internal"
"github.com/azure/azure-dev/cli/azd/pkg/account"
"github.com/azure/azure-dev/cli/azd/pkg/auth"
"github.com/azure/azure-dev/cli/azd/pkg/contracts"
"github.com/azure/azure-dev/cli/azd/pkg/exec"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/oneauth"
"github.com/azure/azure-dev/cli/azd/pkg/output"
"github.com/azure/azure-dev/cli/azd/pkg/tools/github"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// The parent of the login command.
const loginCmdParentAnnotation = "loginCmdParent"
type authLoginFlags struct {
loginFlags
}
func newAuthLoginFlags(cmd *cobra.Command, global *internal.GlobalCommandOptions) *authLoginFlags {
flags := &authLoginFlags{}
flags.Bind(cmd.Flags(), global)
return flags
}
type loginFlags struct {
onlyCheckStatus bool
browser bool
useDeviceCode boolPtr
tenantID string
clientID string
clientSecret stringPtr
clientCertificate string
federatedTokenProvider string
scopes []string
redirectPort int
global *internal.GlobalCommandOptions
}
// stringPtr implements a pflag.Value and allows us to distinguish between a flag value being explicitly set to the empty
// string vs not being present.
type stringPtr struct {
ptr *string
}
func (p *stringPtr) Set(s string) error {
p.ptr = &s
return nil
}
func (p *stringPtr) String() string {
if p.ptr != nil {
return *p.ptr
}
return ""
}
func (p *stringPtr) Type() string {
return "string"
}
// boolPtr implements a pflag.Value and allows us to distinguish between a flag value being explicitly set to
// bool vs not being present.
type boolPtr struct {
ptr *string
}
func (p *boolPtr) Set(s string) error {
p.ptr = &s
return nil
}
func (p *boolPtr) String() string {
if p.ptr != nil {
return *p.ptr
}
return "false"
}
func (p *boolPtr) Type() string {
return ""
}
const (
cClientSecretFlagName = "client-secret"
cClientCertificateFlagName = "client-certificate"
cFederatedCredentialProviderFlagName = "federated-credential-provider"
)
func (lf *loginFlags) Bind(local *pflag.FlagSet, global *internal.GlobalCommandOptions) {
local.BoolVar(&lf.onlyCheckStatus, "check-status", false, "Checks the log-in status instead of logging in.")
f := local.VarPF(
&lf.useDeviceCode,
"use-device-code",
"",
"When true, log in by using a device code instead of a browser.",
)
// ensure the flag behaves as a common boolean flag which is set to true when used without any other arg
f.NoOptDefVal = "true"
local.StringVar(&lf.clientID, "client-id", "", "The client id for the service principal to authenticate with.")
local.Var(
&lf.clientSecret,
cClientSecretFlagName,
"The client secret for the service principal to authenticate with. "+
"Set to the empty string to read the value from the console.")
local.StringVar(
&lf.clientCertificate,
cClientCertificateFlagName,
"",
"The path to the client certificate for the service principal to authenticate with.")
local.StringVar(
&lf.federatedTokenProvider,
cFederatedCredentialProviderFlagName,
"",
"The provider to use to acquire a federated token to authenticate with.")
local.StringVar(
&lf.tenantID,
"tenant-id",
"",
"The tenant id or domain name to authenticate with.")
local.StringArrayVar(
&lf.scopes,
"scope",
nil,
"The scope to acquire during login")
_ = local.MarkHidden("scope")
local.IntVar(
&lf.redirectPort,
"redirect-port",
0,
"Choose the port to be used as part of the redirect URI during interactive login.")
if oneauth.Supported {
local.BoolVar(&lf.browser, "browser", false, "Authenticate in a web browser instead of an integrated dialog.")
}
lf.global = global
}
func newLoginFlags(cmd *cobra.Command, global *internal.GlobalCommandOptions) *loginFlags {
flags := &loginFlags{}
flags.Bind(cmd.Flags(), global)
return flags
}
func newLoginCmd(parent string) *cobra.Command {
return &cobra.Command{
Use: "login",
Short: "Log in to Azure.",
Long: heredoc.Doc(`
Log in to Azure.
When run without any arguments, log in interactively using a browser. To log in using a device code, pass
--use-device-code.
To log in as a service principal, pass --client-id and --tenant-id as well as one of: --client-secret,
--client-certificate, or --federated-credential-provider.
`),
Annotations: map[string]string{
loginCmdParentAnnotation: parent,
},
}
}
type loginAction struct {
formatter output.Formatter
writer io.Writer
console input.Console
authManager *auth.Manager
accountSubManager *account.SubscriptionsManager
flags *loginFlags
annotations CmdAnnotations
commandRunner exec.CommandRunner
}
// it is important to update both newAuthLoginAction and newLoginAction at the same time
// newAuthLoginAction is the action that is bound to `azd auth login`,
// and newLoginAction is the action that is bound to `azd login`
func newAuthLoginAction(
formatter output.Formatter,
writer io.Writer,
authManager *auth.Manager,
accountSubManager *account.SubscriptionsManager,
flags *authLoginFlags,
console input.Console,
annotations CmdAnnotations,
commandRunner exec.CommandRunner,
) actions.Action {
return &loginAction{
formatter: formatter,
writer: writer,
console: console,
authManager: authManager,
accountSubManager: accountSubManager,
flags: &flags.loginFlags,
annotations: annotations,
commandRunner: commandRunner,
}
}
// it is important to update both newAuthLoginAction and newLoginAction at the same time
// newAuthLoginAction is the action that is bound to `azd auth login`,
// and newLoginAction is the action that is bound to `azd login`
func newLoginAction(
formatter output.Formatter,
writer io.Writer,
authManager *auth.Manager,
accountSubManager *account.SubscriptionsManager,
flags *loginFlags,
console input.Console,
annotations CmdAnnotations,
commandRunner exec.CommandRunner,
) actions.Action {
return &loginAction{
formatter: formatter,
writer: writer,
console: console,
authManager: authManager,
accountSubManager: accountSubManager,
flags: flags,
annotations: annotations,
commandRunner: commandRunner,
}
}
const cLoginSuccessMessage = "Logged in to Azure."
func (la *loginAction) Run(ctx context.Context) (*actions.ActionResult, error) {
if len(la.flags.scopes) == 0 {
la.flags.scopes = la.authManager.LoginScopes()
}
if la.annotations[loginCmdParentAnnotation] == "" {
fmt.Fprintln(
la.console.Handles().Stderr,
output.WithWarningFormat(
"WARNING: `azd login` is deprecated and will be removed in a future release."))
fmt.Fprintln(
la.console.Handles().Stderr,
"Next time use `azd auth login`.")
}
if la.flags.onlyCheckStatus {
// In check status mode, we always print the final status to stdout.
// We print any non-setup related errors to stderr.
// We always return a zero exit code.
token, err := la.verifyLoggedIn(ctx)
var loginExpiryError *auth.ReLoginRequiredError
if err != nil &&
!errors.Is(err, auth.ErrNoCurrentUser) &&
!errors.As(err, &loginExpiryError) {
fmt.Fprintln(la.console.Handles().Stderr, err.Error())
}
res := contracts.LoginResult{}
if err != nil {
res.Status = contracts.LoginStatusUnauthenticated
} else {
res.Status = contracts.LoginStatusSuccess
res.ExpiresOn = &token.ExpiresOn
}
if la.formatter.Kind() != output.NoneFormat {
return nil, la.formatter.Format(res, la.writer, nil)
} else {
var msg string
switch res.Status {
case contracts.LoginStatusSuccess:
msg = cLoginSuccessMessage
case contracts.LoginStatusUnauthenticated:
msg = "Not logged in, run `azd auth login` to login to Azure."
default:
panic("Unhandled login status")
}
fmt.Fprintln(la.console.Handles().Stdout, msg)
return nil, nil
}
}
if err := la.accountSubManager.ClearSubscriptions(ctx); err != nil {
log.Printf("failed clearing subscriptions: %v", err)
}
if err := la.login(ctx); err != nil {
return nil, err
}
if _, err := la.verifyLoggedIn(ctx); err != nil {
return nil, err
}
// Rehydrate or clear the account's subscriptions cache.
// The caching is done here to increase responsiveness of listing subscriptions (during azd init).
// It also allows an implicit command for the user to refresh cached subscriptions.
if la.flags.clientID == "" {
// Deleting subscriptions on file is very unlikely to fail, unless there are serious filesystem issues.
// If this does fail, we want the user to be aware of this. Like other stored azd account data,
// stored subscriptions are currently tied to the OS user, and not the individual account being logged in,
// this means cross-contamination is possible.
if err := la.accountSubManager.ClearSubscriptions(ctx); err != nil {
return nil, err
}
err := la.accountSubManager.RefreshSubscriptions(ctx)
if err != nil {
// If this fails, the subscriptions will still be loaded on-demand.
// erroring out when the user interacts with subscriptions is much more user-friendly.
log.Printf("failed retrieving subscriptions: %v", err)
}
} else {
// Service principals do not typically require subscription caching (running in CI scenarios)
// We simply clear the cache, which is much faster than rehydrating.
err := la.accountSubManager.ClearSubscriptions(ctx)
if err != nil {
log.Printf("failed clearing subscriptions: %v", err)
}
}
la.console.Message(ctx, cLoginSuccessMessage)
return nil, nil
}
// Verifies that the user has credentials stored,
// and that the credentials stored is accepted by the identity server (can be exchanged for access token).
func (la *loginAction) verifyLoggedIn(ctx context.Context) (*azcore.AccessToken, error) {
credOptions := auth.CredentialForCurrentUserOptions{
TenantID: la.flags.tenantID,
}
cred, err := la.authManager.CredentialForCurrentUser(ctx, &credOptions)
if err != nil {
return nil, err
}
// Ensure credential is valid, and can be exchanged for an access token
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: la.flags.scopes,
})
if err != nil {
return nil, err
}
return &token, nil
}
func countTrue(elms ...bool) int {
i := 0
for _, elm := range elms {
if elm {
i++
}
}
return i
}
// runningOnCodespacesBrowser use `code --status` which returns:
//
// > The --status argument is not yet supported in browsers.
//
// to detect when vscode is within a WebBrowser environment.
func runningOnCodespacesBrowser(ctx context.Context, commandRunner exec.CommandRunner) bool {
runArgs := exec.NewRunArgs("code", "--status")
result, err := commandRunner.Run(ctx, runArgs)
if err != nil {
// An error here means VSCode is not installed or found, or something else.
// At any case, we know VSCode is not within a webBrowser
log.Printf("error running code --status: %s", err.Error())
return false
}
return strings.Contains(result.Stdout, "The --status argument is not yet supported in browsers")
}
func (la *loginAction) login(ctx context.Context) error {
if la.flags.clientID != "" {
if la.flags.tenantID == "" {
return errors.New("must set both `client-id` and `tenant-id` for service principal login")
}
if countTrue(
la.flags.clientSecret.ptr != nil,
la.flags.clientCertificate != "",
la.flags.federatedTokenProvider != "",
) != 1 {
return fmt.Errorf(
"must set exactly one of %s for service principal", strings.Join([]string{
cClientSecretFlagName,
cClientCertificateFlagName,
cFederatedCredentialProviderFlagName,
}, ", "))
}
switch {
case la.flags.clientSecret.ptr != nil:
if *la.flags.clientSecret.ptr == "" {
v, err := la.console.Prompt(ctx, input.ConsoleOptions{
Message: "Enter your client secret",
})
if err != nil {
return fmt.Errorf("prompting for client secret: %w", err)
}
la.flags.clientSecret.ptr = &v
}
if _, err := la.authManager.LoginWithServicePrincipalSecret(
ctx, la.flags.tenantID, la.flags.clientID, *la.flags.clientSecret.ptr,
); err != nil {
return fmt.Errorf("logging in: %w", err)
}
case la.flags.clientCertificate != "":
certFile, err := os.Open(la.flags.clientCertificate)
if err != nil {
return fmt.Errorf("reading certificate: %w", err)
}
defer certFile.Close()
cert, err := io.ReadAll(certFile)
if err != nil {
return fmt.Errorf("reading certificate: %w", err)
}
if _, err := la.authManager.LoginWithServicePrincipalCertificate(
ctx, la.flags.tenantID, la.flags.clientID, cert,
); err != nil {
return fmt.Errorf("logging in: %w", err)
}
case la.flags.federatedTokenProvider != "":
if _, err := la.authManager.LoginWithServicePrincipalFederatedTokenProvider(
ctx, la.flags.tenantID, la.flags.clientID, la.flags.federatedTokenProvider,
); err != nil {
return fmt.Errorf("logging in: %w", err)
}
}
return nil
}
if la.authManager.UseExternalAuth() {
// Request a token and assume the external auth system will prompt the user to log in.
//
// TODO(ellismg): We may want instead to call some explicit `/login` endpoint on the external auth system instead
// of abusing the token request in this manner. This would allow the other end to provide a more tailored experience.
_, err := la.verifyLoggedIn(ctx)
return err
}
useDevCode, err := parseUseDeviceCode(ctx, la.flags.useDeviceCode, la.commandRunner)
if err != nil {
return err
}
if useDevCode {
_, err = la.authManager.LoginWithDeviceCode(ctx, la.flags.tenantID, la.flags.scopes, func(url string) error {
if !la.flags.global.NoPrompt {
la.console.Message(ctx, "Then press enter and continue to log in from your browser...")
la.console.WaitForEnter()
openWithDefaultBrowser(ctx, la.console, url)
return nil
}
// For no-prompt, Just provide instructions without trying to open the browser
// If manual browsing is enabled, we don't want to open the browser automatically
la.console.Message(ctx, fmt.Sprintf("Then, go to: %s", url))
return nil
})
return err
}
if oneauth.Supported && !la.flags.browser {
err = la.authManager.LoginWithOneAuth(ctx, la.flags.tenantID, la.flags.scopes)
} else {
_, err = la.authManager.LoginInteractive(ctx, la.flags.scopes,
&auth.LoginInteractiveOptions{
TenantID: la.flags.tenantID,
RedirectPort: la.flags.redirectPort,
WithOpenUrl: func(url string) error {
openWithDefaultBrowser(ctx, la.console, url)
return nil
},
})
}
if err != nil {
err = fmt.Errorf("logging in: %w", err)
}
return err
}
func parseUseDeviceCode(ctx context.Context, flag boolPtr, commandRunner exec.CommandRunner) (bool, error) {
var useDevCode bool
useDevCodeFlag := flag.ptr != nil
if useDevCodeFlag {
userInput, err := strconv.ParseBool(*flag.ptr)
if err != nil {
return false, fmt.Errorf("unexpected boolean input for '--use-device-code': %w", err)
}
// honor the value from the user input. No override.
return userInput, err
}
// Detect cases where the browser isn't available for interactive auth, and we instead want to set `useDeviceCode`
// to be true by default
if github.RunningOnCodespaces() {
// For VSCode online (in web Browser), like GitHub Codespaces or VSCode online attached to any server,
// interactive browser login will 404 when attempting to redirect to localhost
// (since azd launches a localhost server running remotely and the login response is accepted locally).
// Hence, we override login to device-code. See https://github.com/Azure/azure-dev/issues/1006
useDevCode = runningOnCodespacesBrowser(ctx, commandRunner)
}
if auth.ShouldUseCloudShellAuth() {
// Following az CLI behavior in Cloud Shell, use device code authentication when the user is trying to
// authenticate. The normal interactive authentication flow will not work in Cloud Shell because the browser
// cannot be opened or (if it could) cannot be redirected back to a port on the Cloud Shell instance.
return true, nil
}
return useDevCode, nil
}