-
Notifications
You must be signed in to change notification settings - Fork 55
/
login.go
355 lines (275 loc) · 7.4 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
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/uid"
)
func relogin() error {
// TODO (https://github.com/infrahq/infra/issues/488): support non-interactive login
if !term.IsTerminal(int(os.Stdin.Fd())) {
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{
ProviderID: provider.ID,
Code: code,
}
loginRes, err := client.Login(loginReq)
if err != nil {
return err
}
return finishLogin(currentConfig.Host, loginRes.ID, loginRes.Name, loginRes.Token, currentConfig.SkipTLSVerify, 0)
}
func login(host string) error {
// TODO (https://github.com/infrahq/infra/issues/488): support non-interactive login
if !term.IsTerminal(int(os.Stdin.Fd())) {
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
}
}
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
}
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 API Token")
option, err := promptProvider(options)
if err != nil {
return err
}
// api token
if option == len(options)-1 {
var token string
err = survey.AskOne(&survey.Password{Message: "Your API Token:"}, &token, survey.WithStdio(os.Stdin, os.Stderr, os.Stderr))
if err != nil {
return err
}
return finishLogin(host, 0, "system", token, skipTLSVerify, 0)
}
provider := providers[option]
code, err := oidcflow(provider.URL, provider.ClientID)
if err != nil {
return err
}
loginReq := &api.LoginRequest{
ProviderID: provider.ID,
Code: code,
}
loginRes, err := client.Login(loginReq)
if err != nil {
return err
}
return finishLogin(host, loginRes.ID, loginRes.Name, loginRes.Token, skipTLSVerify, provider.ID)
}
func finishLogin(host string, id uid.ID, name string, token string, skipTLSVerify bool, providerID uid.ID) error {
client, err := apiClient(host, token, skipTLSVerify)
if err != nil {
return err
}
_, err = client.ListUsers(api.ListUsersRequest{Email: name})
if err != nil {
return err
}
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
hostConfig.ID = id
hostConfig.Current = true
hostConfig.Host = host
hostConfig.Name = name
hostConfig.ProviderID = providerID
hostConfig.Token = token
hostConfig.SkipTLSVerify = skipTLSVerify
var found bool
for i, c := range config.Hosts {
if c.Host == host {
config.Hosts[i] = hostConfig
found = true
}
}
if !found {
config.Hosts = append(config.Hosts, hostConfig)
}
err = writeConfig(config)
if err != nil {
return err
}
if id != 0 {
return updateKubeconfig()
}
return nil
}
func oidcflow(url string, clientId string) (string, error) {
state, err := generate.CryptoRandom(12)
if err != nil {
return "", err
}
u, err := urlx.Parse(url)
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", u.Host, clientId, state)
fmt.Fprintf(os.Stderr, " Logging in with %s...\n", termenv.String("Okta").Bold().String())
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
hosts = append(hosts, "Connect to a different host")
if len(hosts) > 0 {
prompt := &survey.Select{
Message: "Select an Infra host:",
Options: hosts,
}
err := survey.AskOne(prompt, &option, 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
}
proceed := false
fmt.Fprintf(os.Stderr, "Could not verify certificate for host %q: %s\n", host, err)
prompt := &survey.Confirm{
Message: "Are you sure you want to continue?",
}
err := survey.AskOne(prompt, &proceed, survey.WithStdio(os.Stdin, os.Stderr, os.Stderr))
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return false, false, err
}
if !proceed {
return false, false, nil
}
return true, true, nil
}
defer res.Body.Close()
return false, true, nil
}