-
Notifications
You must be signed in to change notification settings - Fork 55
/
cmd.go
452 lines (361 loc) · 10.4 KB
/
cmd.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
package cmd
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/goware/urlx"
"github.com/infrahq/infra/internal"
"github.com/infrahq/infra/internal/api"
"github.com/infrahq/infra/internal/engine"
"github.com/infrahq/infra/internal/logging"
"github.com/infrahq/infra/internal/registry"
"github.com/muesli/termenv"
"github.com/spf13/cobra"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
func blue(s string) string {
return termenv.String(s).Bold().Foreground(termenv.ColorProfile().Color("#0057FF")).String()
}
// errWithResponseContext appends the response message to a returned error
func errWithResponseContext(err error, res *http.Response) error {
var apiErr api.Error
if decodeErr := json.NewDecoder(res.Body).Decode(&apiErr); decodeErr != nil {
// ignore this decoding error and return the original error
return err
}
return fmt.Errorf("%w (Message: %s)", err, apiErr.Message)
}
func NewAPIContext(token string) context.Context {
return context.WithValue(context.Background(), api.ContextAccessToken, token)
}
func NewAPIClient(host string, skipTLSVerify bool) (*api.APIClient, error) {
u, err := urlx.Parse(host)
if err != nil {
return nil, fmt.Errorf("parsing host: %w", err)
}
config := api.NewConfiguration()
config.Host = u.Host
config.Scheme = "https"
if skipTLSVerify {
config.HTTPClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
//nolint:gosec // We may purposely set insecureskipverify via a flag
InsecureSkipVerify: true,
},
},
}
}
return api.NewAPIClient(config), nil
}
func infraHomeDir() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
infraDir := filepath.Join(homeDir, ".infra")
err = os.MkdirAll(infraDir, os.ModePerm)
if err != nil {
return "", err
}
return infraDir, nil
}
func apiContextFromConfig(host string) (context.Context, error) {
config, err := readHostConfig(host)
if err != nil {
return nil, err
}
if config == nil {
return nil, ErrConfigNotFound
}
return NewAPIContext(config.Token), nil
}
func apiClientFromConfig(host string) (*api.APIClient, error) {
config, err := readHostConfig(host)
if err != nil {
return nil, err
}
if config == nil {
return nil, ErrConfigNotFound
}
return NewAPIClient(config.Host, config.SkipTLSVerify)
}
func clientConfig() clientcmd.ClientConfig {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRules.WarnIfAllMissing = false
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
}
func updateKubeconfig(user api.User) error {
defaultConfig := clientConfig()
kubeConfig, err := defaultConfig.RawConfig()
if err != nil {
return err
}
// deduplicate roles
roles := make(map[string]api.Role)
for _, r := range user.Roles {
roles[r.Id] = r
}
for _, g := range user.Groups {
for _, r := range g.Roles {
roles[r.Id] = r
}
}
for _, r := range roles {
var contextName string
if r.Namespace != "" {
contextName = fmt.Sprintf("infra:%s:%s", r.Destination.Name, r.Namespace)
} else {
contextName = fmt.Sprintf("infra:%s", r.Destination.Name)
}
kubeConfig.Clusters[contextName] = &clientcmdapi.Cluster{
Server: fmt.Sprintf("https://%s/proxy", r.Destination.Kubernetes.Endpoint),
CertificateAuthorityData: []byte(r.Destination.Kubernetes.Ca),
}
kubeConfig.Contexts[contextName] = &clientcmdapi.Context{
Cluster: contextName,
AuthInfo: contextName,
Namespace: r.Namespace,
}
executable, err := os.Executable()
if err != nil {
return err
}
kubeConfig.AuthInfos[contextName] = &clientcmdapi.AuthInfo{
Exec: &clientcmdapi.ExecConfig{
Command: executable,
Args: []string{"tokens", "create", r.Destination.Name},
APIVersion: "client.authentication.k8s.io/v1beta1",
InteractiveMode: clientcmdapi.IfAvailableExecInteractiveMode,
},
}
}
for contextName := range kubeConfig.Contexts {
parts := strings.Split(contextName, ":")
// shouldn't be possible but we don't actually care
if len(parts) < 1 {
continue
}
if parts[0] != "infra" {
continue
}
destinationName := parts[1]
found := false
for _, r := range roles {
if destinationName == r.Destination.Name {
found = true
}
}
if !found {
delete(kubeConfig.Clusters, contextName)
delete(kubeConfig.Contexts, contextName)
delete(kubeConfig.AuthInfos, contextName)
}
}
kubeConfigFilename := defaultConfig.ConfigAccess().GetDefaultFilename()
if err := clientcmd.WriteToFile(kubeConfig, kubeConfigFilename); err != nil {
return err
}
return nil
}
func newLoginCmd() (*cobra.Command, error) {
cmd := &cobra.Command{
Use: "login [HOST]",
Short: "Login to Infra",
Args: cobra.MaximumNArgs(1),
Example: "$ infra login infra.example.com",
RunE: func(cmd *cobra.Command, args []string) error {
var options LoginOptions
if err := internal.ParseOptions(cmd, &options); err != nil {
return err
}
if len(args) == 1 {
options.Host = args[0]
}
return login(&options)
},
}
cmd.Flags().DurationP("timeout", "t", defaultTimeout, "login timeout")
return cmd, nil
}
func newLogoutCmd() (*cobra.Command, error) {
cmd := &cobra.Command{
Use: "logout",
Short: "Logout Infra",
Args: cobra.MaximumNArgs(1),
Example: "$ infra logout",
RunE: func(cmd *cobra.Command, args []string) error {
var options LogoutOptions
if err := internal.ParseOptions(cmd, &options); err != nil {
return err
}
if len(args) == 1 {
options.Host = args[0]
}
return logout(&options)
},
}
return cmd, nil
}
func newListCmd() (*cobra.Command, error) {
cmd := &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: "List destinations",
RunE: func(cmd *cobra.Command, args []string) error {
var options ListOptions
if err := internal.ParseOptions(cmd, &options); err != nil {
return err
}
return list(&options)
},
}
return cmd, nil
}
func newStartCmd() (*cobra.Command, error) {
cmd := &cobra.Command{
Use: "start",
Short: "Start Infra",
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
var options registry.Options
if err := internal.ParseOptions(cmd, &options); err != nil {
return err
}
return registry.Run(options)
},
}
cmd.Flags().StringP("config-path", "c", "", "Infra config file")
cmd.Flags().String("root-api-key", "", "root API key")
cmd.Flags().String("engine-api-key", "", "engine registration API key")
cmd.Flags().String("tls-cache", "", "path to cache self-signed and Let's Encrypt TLS certificates")
cmd.Flags().String("db-file", "", "path to database file")
cmd.Flags().String("ui-proxy", "", "proxy UI requests to this host")
cmd.Flags().Bool("enable-ui", false, "enable UI")
cmd.Flags().Duration("providers-sync-interval", registry.DefaultProvidersSyncInterval, "the interval at which Infra will poll identity providers for users and groups")
cmd.Flags().Duration("destinations-sync-interval", registry.DefaultDestinationsSyncInterval, "the interval at which Infra will poll destinations")
cmd.Flags().Bool("enable-telemetry", true, "enable telemetry")
cmd.Flags().Bool("enable-crash-reporting", true, "enable crash reporting")
return cmd, nil
}
func newEngineCmd() (*cobra.Command, error) {
cmd := &cobra.Command{
Use: "engine",
Short: "Start Infra Engine",
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
var options engine.Options
if err := internal.ParseOptions(cmd, &options); err != nil {
return err
}
return engine.Run(&options)
},
}
cmd.Flags().StringP("name", "n", "", "cluster name")
cmd.Flags().String("api-key", "", "engine registry API key")
cmd.Flags().String("tls-cache", "", "path to cache self-signed and Let's Encrypt TLS certificates")
cmd.Flags().Bool("skip-tls-verify", true, "skip TLS verification")
return cmd, nil
}
func newVersionCmd() (*cobra.Command, error) {
cmd := &cobra.Command{
Use: "version",
Short: "Display the Infra build version",
RunE: func(cmd *cobra.Command, args []string) error {
var options VersionOptions
if err := internal.ParseOptions(cmd, &options); err != nil {
return err
}
return version(&options)
},
}
cmd.Flags().Bool("client", false, "Display client version only")
cmd.Flags().Bool("server", false, "Display server version only")
return cmd, nil
}
func newTokensCmd() (*cobra.Command, error) {
cmd := &cobra.Command{
Use: "tokens",
Short: "Token subcommands",
}
tokenCreateCmd, err := newTokenCreateCmd()
if err != nil {
return nil, err
}
cmd.AddCommand(tokenCreateCmd)
return cmd, nil
}
func NewRootCmd() (*cobra.Command, error) {
cobra.EnableCommandSorting = false
loginCmd, err := newLoginCmd()
if err != nil {
return nil, err
}
logoutCmd, err := newLogoutCmd()
if err != nil {
return nil, err
}
listCmd, err := newListCmd()
if err != nil {
return nil, err
}
tokensCmd, err := newTokensCmd()
if err != nil {
return nil, err
}
versionCmd, err := newVersionCmd()
if err != nil {
return nil, err
}
startCmd, err := newStartCmd()
if err != nil {
return nil, err
}
engineCmd, err := newEngineCmd()
if err != nil {
return nil, err
}
rootCmd := &cobra.Command{
Use: "infra",
Short: "Infrastructure Identity & Access Management (IAM)",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
var options internal.Options
if err := internal.ParseOptions(cmd, &options); err != nil {
return err
}
logger, err := logging.Initialize(options.LogLevel)
if err != nil {
logging.L.Warn(err.Error())
} else {
logging.L = logger
logging.S = logger.Sugar()
}
return nil
},
}
rootCmd.AddCommand(loginCmd)
rootCmd.AddCommand(logoutCmd)
rootCmd.AddCommand(listCmd)
rootCmd.AddCommand(tokensCmd)
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(startCmd)
rootCmd.AddCommand(engineCmd)
rootCmd.PersistentFlags().StringP("config-file", "f", "", "Infra configuration file path")
rootCmd.PersistentFlags().StringP("host", "H", "", "Infra host")
rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level")
return rootCmd, nil
}
func Run() error {
cmd, err := NewRootCmd()
if err != nil {
return err
}
return cmd.Execute()
}