-
Notifications
You must be signed in to change notification settings - Fork 55
/
login.go
411 lines (319 loc) · 8.75 KB
/
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
package cmd
import (
"context"
"crypto/x509"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"
survey "github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/cli/browser"
"github.com/goware/urlx"
"github.com/muesli/termenv"
"golang.org/x/term"
"github.com/infrahq/infra/internal/api"
"github.com/infrahq/infra/internal/generate"
"github.com/infrahq/infra/internal/logging"
"github.com/infrahq/infra/uid"
)
const cliLoginRedirectURL = "http://localhost:8301"
func relogin() error {
// TODO (https://github.com/infrahq/infra/issues/488): support non-interactive login
if !isInteractiveMode() {
return errors.New("Non-interactive login is not supported")
}
currentConfig, err := currentHostConfig()
if err != nil {
return err
}
client, err := apiClient(currentConfig.Host, "", currentConfig.SkipTLSVerify)
if err != nil {
return err
}
if currentConfig.ProviderID == 0 {
return errors.New("can not renew login without provider")
}
provider, err := client.GetProvider(currentConfig.ProviderID)
if err != nil {
return err
}
code, err := oidcflow(provider.URL, provider.ClientID)
if err != nil {
return err
}
loginReq := &api.LoginRequest{
OIDC: &api.LoginRequestOIDC{
ProviderID: provider.ID,
RedirectURL: cliLoginRedirectURL,
Code: code,
},
}
loginRes, err := client.Login(loginReq)
if err != nil {
return err
}
return finishLogin(currentConfig.Host, loginRes.PolymorphicID, loginRes.Name, loginRes.AccessKey, currentConfig.SkipTLSVerify, 0)
}
func isInteractiveMode() bool {
if nonInteractiveMode {
// user explicitly asked for a non-interactive terminal
return false
}
if os.Stdin == nil {
return false
}
return term.IsTerminal(int(os.Stdin.Fd()))
}
func login(host string) error {
// TODO (https://github.com/infrahq/infra/issues/488): support non-interactive login
if !isInteractiveMode() {
return errors.New("Non-interactive login is not supported")
}
config, err := readConfig()
if err != nil && !errors.Is(err, ErrConfigNotFound) {
return err
}
if config == nil {
config = NewClientConfig()
}
if host == "" {
var hosts []string
for _, h := range config.Hosts {
hosts = append(hosts, h.Host)
}
host, err = promptHost(hosts)
if err != nil {
return err
}
}
u, err := urlx.Parse(host)
if err != nil {
return err
}
host = u.Host
fmt.Fprintf(os.Stderr, " Logging in to %s\n", termenv.String(host).Bold().String())
skipTLSVerify, proceed, err := promptShouldSkipTLSVerify(host)
if err != nil {
return err
}
if !proceed {
//lint:ignore ST1005, user facing error
return fmt.Errorf("Could not verify TLS connection")
}
client, err := apiClient(host, "", skipTLSVerify)
if err != nil {
return err
}
setupRequired, err := client.SetupRequired()
if err != nil {
return err
}
var accessKey string
if setupRequired.Required {
setup, err := client.Setup()
if err != nil {
return err
}
fmt.Println()
fmt.Printf(" Congratulations, Infra has been successfully installed.\n\n")
fmt.Printf(" Access Key: %s\n", setup.AccessKey)
fmt.Printf(fmt.Sprintf(" %s", termenv.String("IMPORTANT: Store in a safe place. You will not see it again.\n\n").Bold().String()))
accessKey = setup.AccessKey
}
providers, err := client.ListProviders("")
if err != nil {
return err
}
var options []string
for _, p := range providers {
options = append(options, fmt.Sprintf("%s (%s)", p.Name, p.URL))
}
options = append(options, "Login with Access Key")
var option int
if len(options) > 1 {
option, err = promptProvider(options)
if err != nil {
return err
}
}
var providerID uid.ID
var loginReq api.LoginRequest
if option == len(options)-1 {
if accessKey == "" {
err = survey.AskOne(&survey.Password{Message: "Access Key:"}, &accessKey, survey.WithStdio(os.Stdin, os.Stderr, os.Stderr))
if err != nil {
return err
}
}
loginReq.AccessKey = accessKey
} else {
provider := providers[option]
providerID = provider.ID
fmt.Fprintf(os.Stderr, " Logging in with %s...\n", termenv.String(provider.Name).Bold().String())
code, err := oidcflow(provider.URL, provider.ClientID)
if err != nil {
return err
}
loginReq.OIDC = &api.LoginRequestOIDC{
ProviderID: provider.ID,
RedirectURL: cliLoginRedirectURL,
Code: code,
}
}
loginRes, err := client.Login(&loginReq)
if err != nil {
return err
}
return finishLogin(host, loginRes.PolymorphicID, loginRes.Name, loginRes.AccessKey, skipTLSVerify, providerID)
}
func finishLogin(host string, polymorphicID uid.PolymorphicID, name string, accessKey string, skipTLSVerify bool, providerID uid.ID) error {
fmt.Fprintf(os.Stderr, " Logged in as %s\n", termenv.String(name).Bold().String())
config, err := readConfig()
if err != nil && !errors.Is(err, ErrConfigNotFound) {
return err
}
if config == nil {
config = NewClientConfig()
}
var hostConfig ClientHostConfig
id, err := polymorphicID.ID()
if err != nil {
return err
}
hostConfig.ID = id
hostConfig.PolymorphicID = polymorphicID
hostConfig.Current = true
hostConfig.Host = host
hostConfig.Name = name
hostConfig.ProviderID = providerID
hostConfig.AccessKey = accessKey
hostConfig.SkipTLSVerify = skipTLSVerify
var found bool
for i, c := range config.Hosts {
if c.Host == host {
config.Hosts[i] = hostConfig
found = true
continue
}
config.Hosts[i].Current = false
}
if !found {
config.Hosts = append(config.Hosts, hostConfig)
}
err = writeConfig(config)
if err != nil {
return err
}
client, err := apiClient(host, accessKey, skipTLSVerify)
if err != nil {
return err
}
return updateKubeconfig(client, polymorphicID)
}
func oidcflow(host string, clientId string) (string, error) {
state, err := generate.CryptoRandom(12)
if err != nil {
return "", err
}
authorizeURL := fmt.Sprintf("https://%s/oauth2/v1/authorize?redirect_uri=http://localhost:8301&client_id=%s&response_type=code&scope=openid+email+groups+offline_access&state=%s", host, clientId, state)
ls, err := newLocalServer()
if err != nil {
return "", err
}
err = browser.OpenURL(authorizeURL)
if err != nil {
return "", err
}
code, recvstate, err := ls.wait(time.Minute * 5)
if err != nil {
return "", err
}
if state != recvstate {
//lint:ignore ST1005, user facing error
return "", errors.New("Login aborted, provider state did not match the expected state")
}
return code, nil
}
func promptProvider(providers []string) (int, error) {
var option int
prompt := &survey.Select{
Message: "Select a login method:",
Options: providers,
}
err := survey.AskOne(prompt, &option, survey.WithStdio(os.Stdin, os.Stderr, os.Stderr))
if errors.Is(err, terminal.InterruptErr) {
return 0, err
}
return option, nil
}
type hostchoice struct {
Host string
Auto bool
}
func promptHost(hosts []string) (string, error) {
var option int
const defaultOpt string = "Connect to a different host"
hosts = append(hosts, defaultOpt)
if len(hosts) > 0 {
prompt := &survey.Select{
Message: "Select an Infra host:",
Options: hosts,
}
filter := func(filterValue string, optValue string, optIndex int) bool {
return strings.Contains(optValue, filterValue) || strings.EqualFold(optValue, defaultOpt)
}
err := survey.AskOne(prompt, &option, survey.WithFilter(filter), survey.WithStdio(os.Stdin, os.Stderr, os.Stderr))
if err != nil {
return "", err
}
}
if option != len(hosts)-1 {
return hosts[option], nil
}
var host string
err := survey.AskOne(&survey.Input{Message: "Host:"}, &host, survey.WithStdio(os.Stdin, os.Stderr, os.Stderr))
if err != nil {
return "", err
}
if host == "" {
return "", errors.New("Host is required")
}
return host, nil
}
func promptShouldSkipTLSVerify(host string) (shouldSkipTLSVerify bool, proceed bool, err error) {
url, err := urlx.Parse(host)
if err != nil {
return false, false, fmt.Errorf("parsing host: %w", err)
}
url.Scheme = "https"
urlString := url.String()
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, urlString, nil)
if err != nil {
return false, false, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
if !errors.As(err, &x509.UnknownAuthorityError{}) && !errors.As(err, &x509.HostnameError{}) && !strings.Contains(err.Error(), "certificate is not trusted") {
return false, false, err
}
logging.S.Debug(err)
fmt.Printf(" The authenticity of host '%s' can't be established.\n", host)
prompt := &survey.Confirm{
Message: "Are you sure you want to continue?",
}
proceed := false
err := survey.AskOne(prompt, &proceed, survey.WithStdio(os.Stdin, os.Stderr, os.Stderr))
if err != nil {
return false, false, err
}
if !proceed {
return false, false, nil
}
return true, true, nil
}
defer res.Body.Close()
return false, true, nil
}