-
Notifications
You must be signed in to change notification settings - Fork 927
/
login_command.go
632 lines (539 loc) · 17.8 KB
/
login_command.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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
package v6
import (
"errors"
"fmt"
"io"
"net/url"
"strings"
"code.cloudfoundry.org/cli/api/uaa"
"code.cloudfoundry.org/cli/util/ui"
"code.cloudfoundry.org/cli/actor/v2action"
"code.cloudfoundry.org/cli/actor/v3action"
"code.cloudfoundry.org/cli/api/uaa/constant"
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/translatableerror"
"code.cloudfoundry.org/cli/command/v6/shared"
)
//go:generate counterfeiter . LoginActor
const maxLoginTries = 3
type LoginActor interface {
Authenticate(credentials map[string]string, origin string, grantType constant.GrantType) error
GetLoginPrompts() map[string]coreconfig.AuthPrompt
GetOrganizationByName(orgName string) (v3action.Organization, v3action.Warnings, error)
GetOrganizationSpaces(orgName string) ([]v3action.Space, v3action.Warnings, error)
GetSpaceByNameAndOrganization(spaceName string, orgGUID string) (v3action.Space, v3action.Warnings, error)
GetOrganizations() ([]v3action.Organization, v3action.Warnings, error)
SetTarget(settings v3action.TargetSettings) (v3action.Warnings, error)
}
//go:generate counterfeiter . V2LoginActor
type V2LoginActor interface {
MinCLIVersion() string
CloudControllerAPIVersion() string
AuthorizationEndpoint() string
}
//go:generate counterfeiter . ActorMaker
type ActorMaker interface {
NewActor(command.Config, command.UI, bool, string) (LoginActor, error)
}
//go:generate counterfeiter . V2ActorMaker
type V2ActorMaker interface {
NewV2Actor(command.Config, command.UI, bool) (V2LoginActor, error)
}
type ActorMakerFunc func(command.Config, command.UI, bool, string) (LoginActor, error)
type V2ActorMakerFunc func(command.Config, command.UI, bool) (V2LoginActor, error)
func (a ActorMakerFunc) NewActor(config command.Config, ui command.UI, targetCF bool, authorizationEndpoint string) (LoginActor, error) {
return a(config, ui, targetCF, authorizationEndpoint)
}
func (a V2ActorMakerFunc) NewV2Actor(config command.Config, ui command.UI, targetCF bool) (V2LoginActor, error) {
return a(config, ui, targetCF)
}
var actorMaker ActorMakerFunc = func(config command.Config, ui command.UI, targetCF bool, authorizationEndpoint string) (LoginActor, error) {
client, uaa, err := shared.NewV3BasedClientsWithAuthorizationEndpoint(config, ui, targetCF, authorizationEndpoint)
if err != nil {
return nil, err
}
v3Actor := v3action.NewActor(client, config, nil, uaa)
return v3Actor, nil
}
var v2ActorMaker V2ActorMakerFunc = func(config command.Config, ui command.UI, targetCF bool) (V2LoginActor, error) {
client, uaa, err := shared.GetNewClientsAndConnectToCF(config, ui)
if err != nil {
return nil, err
}
v2Actor := v2action.NewActor(client, uaa, config)
return v2Actor, nil
}
type LoginCommand struct {
APIEndpoint string `short:"a" description:"API endpoint (e.g. https://api.example.com)"`
Organization string `short:"o" description:"Org"`
Password string `short:"p" description:"Password"`
Space string `short:"s" description:"Space"`
SkipSSLValidation bool `long:"skip-ssl-validation" description:"Skip verification of the API endpoint. Not recommended!"`
SSO bool `long:"sso" description:"Prompt for a one-time passcode to login"`
SSOPasscode string `long:"sso-passcode" description:"One-time passcode"`
Username string `short:"u" description:"Username"`
Origin string `long:"origin" description:"Indicates the identity provider to be used for login"`
usage interface{} `usage:"CF_NAME login [-a API_URL] [-u USERNAME] [-p PASSWORD] [-o ORG] [-s SPACE] [--sso | --sso-passcode PASSCODE] [--origin ORIGIN]\n\nWARNING:\n Providing your password as a command line option is highly discouraged\n Your password may be visible to others and may be recorded in your shell history\n\nEXAMPLES:\n CF_NAME login (omit username and password to login interactively -- CF_NAME will prompt for both)\n CF_NAME login -u name@example.com -p pa55woRD (specify username and password as arguments)\n CF_NAME login -u name@example.com -p \"my password\" (use quotes for passwords with a space)\n CF_NAME login -u name@example.com -p \"\\\"password\\\"\" (escape quotes if used in password)\n CF_NAME login --sso (CF_NAME will provide a url to obtain a one-time passcode to login)\n CF_NAME login --origin ldap"`
relatedCommands interface{} `related_commands:"api, auth, target"`
UI command.UI
Actor LoginActor
ActorMaker ActorMaker
V2Actor V2LoginActor
V2ActorMaker V2ActorMaker
Config command.Config
}
func (cmd *LoginCommand) Setup(config command.Config, ui command.UI) error {
cmd.ActorMaker = actorMaker
actor, err := cmd.ActorMaker.NewActor(config, ui, false, "")
if err != nil {
return err
}
cmd.V2ActorMaker = v2ActorMaker
cmd.Actor = actor
cmd.UI = ui
cmd.Config = config
return nil
}
func (cmd *LoginCommand) Execute(args []string) error {
err := cmd.validateFlags()
if err != nil {
return err
}
endpoint, err := cmd.determineAPIEndpoint()
if err != nil {
return err
}
cmd.UI.DisplayNewline()
err = cmd.targetAPI(endpoint)
if err != nil {
te := translatableerror.ConvertToTranslatableError(err)
if ise, ok := te.(translatableerror.InvalidSSLCertError); ok {
ise.SuggestedCommand = "login"
return ise
}
return err
}
err = cmd.checkMinCLIVersion()
if err != nil {
return err
}
defer cmd.showStatus()
if cmd.Config.UAAGrantType() == string(constant.GrantTypeClientCredentials) {
return translatableerror.PasswordGrantTypeLogoutRequiredError{}
} else if cmd.Config.UAAOAuthClient() != "cf" || cmd.Config.UAAOAuthClientSecret() != "" {
cmd.UI.DisplayWarning("Deprecation warning: Manually writing your client credentials to the config.json is deprecated and will be removed in the future. For similar functionality, please use the `cf auth --client-credentials` command instead.")
}
var authErr error
if cmd.SSO || cmd.SSOPasscode != "" {
authErr = cmd.authenticateSSO()
} else {
authErr = cmd.authenticate()
}
if authErr != nil {
return errors.New("Unable to authenticate.")
}
err = cmd.Config.WriteConfig()
if err != nil {
return fmt.Errorf("Error writing config: %s", err.Error())
}
if cmd.Organization != "" {
org, warnings, err := cmd.Actor.GetOrganizationByName(cmd.Organization)
cmd.UI.DisplayWarnings(warnings)
if err != nil {
return err
}
cmd.Config.SetOrganizationInformation(org.GUID, org.Name)
} else {
orgs, warnings, err := cmd.Actor.GetOrganizations()
cmd.UI.DisplayWarnings(warnings)
if err != nil {
return err
}
if len(orgs) == 1 {
cmd.Config.SetOrganizationInformation(orgs[0].GUID, orgs[0].Name)
} else if len(orgs) > 1 {
var emptyOrg v3action.Organization
chosenOrg, err := cmd.promptChosenOrg(orgs)
if err != nil {
return err
}
if chosenOrg != emptyOrg {
cmd.Config.SetOrganizationInformation(chosenOrg.GUID, chosenOrg.Name)
}
}
}
targetedOrg := cmd.Config.TargetedOrganization()
if targetedOrg.GUID != "" {
cmd.UI.DisplayTextWithFlavor("Targeted org {{.Organization}}", map[string]interface{}{
"Organization": cmd.Config.TargetedOrganizationName(),
})
cmd.UI.DisplayNewline()
if cmd.Space != "" {
space, warnings, err := cmd.Actor.GetSpaceByNameAndOrganization(cmd.Space, targetedOrg.GUID)
cmd.UI.DisplayWarnings(warnings)
if err != nil {
return err
}
cmd.targetSpace(space)
} else {
spaces, warnings, err := cmd.Actor.GetOrganizationSpaces(targetedOrg.GUID)
cmd.UI.DisplayWarnings(warnings)
if err != nil {
return err
}
if len(spaces) == 1 {
cmd.targetSpace(spaces[0])
} else if len(spaces) > 1 {
var emptySpace v3action.Space
chosenSpace, err := cmd.promptChosenSpace(spaces)
if err != nil {
return err
}
if chosenSpace != emptySpace {
cmd.targetSpace(chosenSpace)
}
}
}
}
cmd.UI.DisplayNewline()
cmd.UI.DisplayNewline()
cmd.UI.DisplayNewline()
return nil
}
func (cmd *LoginCommand) targetSpace(space v3action.Space) {
cmd.Config.SetSpaceInformation(space.GUID, space.Name, true)
cmd.UI.DisplayTextWithFlavor("Targeted space {{.Space}}", map[string]interface{}{
"Space": space.Name,
})
}
func (cmd *LoginCommand) determineAPIEndpoint() (v3action.TargetSettings, error) {
var (
endpoint string
skipSSLValidation bool
)
if cmd.APIEndpoint != "" {
endpoint = cmd.APIEndpoint
skipSSLValidation = cmd.SkipSSLValidation
} else if cmd.Config.Target() != "" {
endpoint = cmd.Config.Target()
skipSSLValidation = cmd.Config.SkipSSLValidation() || cmd.SkipSSLValidation
} else {
endpoint = ""
skipSSLValidation = cmd.SkipSSLValidation
}
if len(endpoint) > 0 {
cmd.UI.DisplayTextWithFlavor("API endpoint: {{.APIEndpoint}}", map[string]interface{}{
"APIEndpoint": endpoint,
})
} else {
var err error
endpoint, err = cmd.UI.DisplayTextPrompt("API endpoint")
if err != nil {
return v3action.TargetSettings{}, err
}
}
strippedEndpoint := strings.TrimRight(endpoint, "/")
u, _ := url.Parse(strippedEndpoint)
if u.Scheme == "" {
u.Scheme = "https"
}
return v3action.TargetSettings{
URL: u.String(),
SkipSSLValidation: skipSSLValidation,
}, nil
}
func (cmd *LoginCommand) targetAPI(settings v3action.TargetSettings) error {
warnings, err := cmd.Actor.SetTarget(settings)
cmd.UI.DisplayWarnings(warnings)
if err != nil {
return err
}
if strings.HasPrefix(settings.URL, "http:") {
cmd.UI.DisplayWarning("Warning: Insecure http API endpoint detected: secure https API endpoints are recommended")
}
return cmd.reloadActors()
}
func (cmd *LoginCommand) authenticate() error {
prompts := cmd.Actor.GetLoginPrompts()
credentials := make(map[string]string)
if value, ok := prompts["username"]; ok {
if prompts["username"].Type == coreconfig.AuthPromptTypeText && cmd.Username != "" {
credentials["username"] = cmd.Username
} else {
var err error
credentials["username"], err = cmd.UI.DisplayTextPrompt(value.DisplayName)
if err != nil {
return err
}
cmd.UI.DisplayNewline()
}
}
passwordKeys := []string{}
for key, prompt := range prompts {
if prompt.Type == coreconfig.AuthPromptTypePassword {
if key == "passcode" || key == "password" {
continue
}
passwordKeys = append(passwordKeys, key)
} else if key == "username" {
continue
} else {
var err error
credentials[key], err = cmd.UI.DisplayTextPrompt(prompt.DisplayName)
if err != nil {
return err
}
cmd.UI.DisplayNewline()
}
}
var err error
for i := 0; i < maxLoginTries; i++ {
var promptedCredentials map[string]string
promptedCredentials, err = cmd.passwordPrompts(prompts, credentials, passwordKeys)
if err != nil {
return err
}
cmd.UI.DisplayText("Authenticating...")
err = cmd.Actor.Authenticate(promptedCredentials, cmd.Origin, constant.GrantTypePassword)
if err != nil {
cmd.UI.DisplayWarning(translatableerror.ConvertToTranslatableError(err).Error())
cmd.UI.DisplayNewline()
if _, ok := err.(uaa.AccountLockedError); ok {
break
}
}
if err == nil {
cmd.UI.DisplayOK()
break
}
}
if err != nil {
return err
}
return nil
}
func (cmd *LoginCommand) authenticateSSO() error {
prompts := cmd.Actor.GetLoginPrompts()
credentials := make(map[string]string)
var err error
for i := 0; i < maxLoginTries; i++ {
if len(cmd.SSOPasscode) > 0 {
credentials["passcode"] = cmd.SSOPasscode
cmd.SSOPasscode = ""
} else {
credentials["passcode"], err = cmd.UI.DisplayPasswordPrompt(prompts["passcode"].DisplayName)
if err != nil {
return err
}
}
credentialsCopy := make(map[string]string, len(credentials))
for k, v := range credentials {
credentialsCopy[k] = v
}
cmd.UI.DisplayText("Authenticating...")
err = cmd.Actor.Authenticate(credentialsCopy, "", constant.GrantTypePassword)
if err != nil {
cmd.UI.DisplayWarning(translatableerror.ConvertToTranslatableError(err).Error())
cmd.UI.DisplayNewline()
}
if err == nil {
cmd.UI.DisplayOK()
cmd.UI.DisplayNewline()
break
}
}
if err != nil {
return err
}
return nil
}
func (cmd *LoginCommand) checkMinCLIVersion() error {
cmd.Config.SetMinCLIVersion(cmd.V2Actor.MinCLIVersion())
return command.WarnIfCLIVersionBelowAPIDefinedMinimum(cmd.Config, cmd.V2Actor.CloudControllerAPIVersion(), cmd.UI)
}
func (cmd *LoginCommand) passwordPrompts(prompts map[string]coreconfig.AuthPrompt, credentials map[string]string, passwordKeys []string) (map[string]string, error) {
// ensure that password gets prompted before other codes (eg. mfa code)
var err error
if passPrompt, ok := prompts["password"]; ok {
if cmd.Password != "" {
credentials["password"] = cmd.Password
cmd.Password = ""
} else {
credentials["password"], err = cmd.UI.DisplayPasswordPrompt(passPrompt.DisplayName)
if err != nil {
return nil, err
}
}
}
for _, key := range passwordKeys {
cmd.UI.DisplayNewline()
credentials[key], err = cmd.UI.DisplayPasswordPrompt(prompts[key].DisplayName)
if err != nil {
return nil, err
}
}
credentialsCopy := make(map[string]string, len(credentials))
for k, v := range credentials {
credentialsCopy[k] = v
}
return credentialsCopy, nil
}
func (cmd *LoginCommand) reloadActors() error {
newV2Actor, err := cmd.V2ActorMaker.NewV2Actor(cmd.Config, cmd.UI, true)
if err != nil {
return err
}
cmd.V2Actor = newV2Actor
newActor, err := cmd.ActorMaker.NewActor(cmd.Config, cmd.UI, true, cmd.V2Actor.AuthorizationEndpoint())
if err != nil {
return err
}
cmd.Actor = newActor
return nil
}
func (cmd *LoginCommand) showStatus() {
tableContent := [][]string{
{
cmd.UI.TranslateText("API endpoint:"),
cmd.UI.TranslateText("{{.APIEndpoint}} (API version: {{.APIVersion}})",
map[string]interface{}{
"APIEndpoint": strings.TrimRight(cmd.Config.Target(), "/"),
"APIVersion": cmd.Config.APIVersion(),
}),
},
}
user, err := cmd.Config.CurrentUserName()
if user == "" || err != nil {
cmd.UI.DisplayKeyValueTable("", tableContent, 3)
command.DisplayNotLoggedInText(cmd.Config.BinaryName(), cmd.UI)
return
}
tableContent = append(tableContent, []string{cmd.UI.TranslateText("User:"), user})
orgName := cmd.Config.TargetedOrganizationName()
if orgName == "" {
cmd.UI.DisplayKeyValueTable("", tableContent, 3)
cmd.displayNotTargetted()
return
}
tableContent = append(tableContent, []string{cmd.UI.TranslateText("Org:"), orgName})
spaceName := cmd.Config.TargetedSpace().Name
if spaceName == "" {
tableContent = append(tableContent, []string{cmd.UI.TranslateText("Space:"),
cmd.UI.TranslateText("No space targeted, use '{{.Command}}'", map[string]interface{}{
"Command": fmt.Sprintf("%s target -s SPACE", cmd.Config.BinaryName()),
})})
} else {
tableContent = append(tableContent, []string{cmd.UI.TranslateText("Space:"), spaceName})
}
cmd.UI.DisplayKeyValueTable("", tableContent, 3)
}
func (cmd *LoginCommand) displayNotTargetted() {
cmd.UI.DisplayText("No org or space targeted, use '{{.CFTargetCommand}} -o ORG -s SPACE'",
map[string]interface{}{
"CFTargetCommand": fmt.Sprintf("%s target", cmd.Config.BinaryName()),
},
)
}
func (cmd *LoginCommand) promptChosenOrg(orgs []v3action.Organization) (v3action.Organization, error) {
orgNames := make([]string, len(orgs))
for i, org := range orgs {
orgNames[i] = org.Name
}
chosenOrgName, err := cmd.promptMenu(orgNames, "Select an org:", "Org")
if err != nil {
if invalidChoice, ok := err.(ui.InvalidChoiceError); ok {
return v3action.Organization{}, translatableerror.OrganizationNotFoundError{Name: invalidChoice.Choice}
} else if err == io.EOF {
return v3action.Organization{}, nil
} else {
return v3action.Organization{}, err
}
}
for _, org := range orgs {
if org.Name == chosenOrgName {
return org, nil
}
}
return v3action.Organization{}, nil
}
func (cmd *LoginCommand) promptChosenSpace(spaces []v3action.Space) (v3action.Space, error) {
spaceNames := make([]string, len(spaces))
for i, space := range spaces {
spaceNames[i] = space.Name
}
chosenSpaceName, err := cmd.promptMenu(spaceNames, "Select a space:", "Space")
if err != nil {
if invalidChoice, ok := err.(ui.InvalidChoiceError); ok {
return v3action.Space{}, translatableerror.SpaceNotFoundError{Name: invalidChoice.Choice}
} else if err == io.EOF {
return v3action.Space{}, nil
} else {
return v3action.Space{}, err
}
}
for _, space := range spaces {
if space.Name == chosenSpaceName {
return space, nil
}
}
return v3action.Space{}, nil
}
func (cmd *LoginCommand) promptMenu(choices []string, text string, prompt string) (string, error) {
var (
choice string
err error
)
if len(choices) < 50 {
for {
cmd.UI.DisplayText(text)
choice, err = cmd.UI.DisplayTextMenu(choices, prompt)
if err == ui.ErrInvalidIndex {
continue
} else {
break
}
}
} else {
cmd.UI.DisplayText(text)
cmd.UI.DisplayText("There are too many options to display; please type in the name.")
cmd.UI.DisplayNewline()
defaultChoice := "enter to skip"
choice, err = cmd.UI.DisplayOptionalTextPrompt(defaultChoice, prompt)
switch {
case choice == defaultChoice:
return "", nil
case !contains(choices, choice):
return "", ui.InvalidChoiceError{Choice: choice}
}
}
return choice, err
}
func (cmd *LoginCommand) validateFlags() error {
if cmd.Origin != "" {
if cmd.SSO {
return translatableerror.ArgumentCombinationError{
Args: []string{"--sso", "--origin"},
}
}
if cmd.SSOPasscode != "" {
return translatableerror.ArgumentCombinationError{
Args: []string{"--sso-passcode", "--origin"},
}
}
}
if cmd.SSO && cmd.SSOPasscode != "" {
return translatableerror.ArgumentCombinationError{
Args: []string{"--sso-passcode", "--sso"},
}
}
return nil
}
func contains(s []string, v string) bool {
for _, x := range s {
if x == v {
return true
}
}
return false
}