summaryrefslogtreecommitdiff
path: root/vendor/github.com/authzed/zed/internal/cmd/context.go
blob: d5a0eec44e60613dba766540b226af1e99f56752 (plain)
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
package cmd

import (
	"fmt"
	"os"

	"github.com/jzelinskie/cobrautil/v2"
	"github.com/jzelinskie/stringz"
	"github.com/spf13/cobra"

	"github.com/authzed/zed/internal/client"
	"github.com/authzed/zed/internal/commands"
	"github.com/authzed/zed/internal/console"
	"github.com/authzed/zed/internal/printers"
	"github.com/authzed/zed/internal/storage"
)

func registerContextCmd(rootCmd *cobra.Command) {
	rootCmd.AddCommand(contextCmd)

	contextCmd.AddCommand(contextListCmd)
	contextListCmd.Flags().Bool("reveal-tokens", false, "display secrets in results")

	contextCmd.AddCommand(contextSetCmd)
	contextCmd.AddCommand(contextRemoveCmd)
	contextCmd.AddCommand(contextUseCmd)
}

var contextCmd = &cobra.Command{
	Use:     "context <subcommand>",
	Short:   "Manage configurations for connecting to SpiceDB deployments",
	Aliases: []string{"ctx"},
}

var contextListCmd = &cobra.Command{
	Use:               "list",
	Short:             "Lists all available contexts",
	Aliases:           []string{"ls"},
	Args:              commands.ValidationWrapper(cobra.ExactArgs(0)),
	ValidArgsFunction: cobra.NoFileCompletions,
	RunE:              contextListCmdFunc,
}

var contextSetCmd = &cobra.Command{
	Use:               "set <name> <endpoint> <api-token>",
	Short:             "Creates or overwrite a context",
	Args:              commands.ValidationWrapper(cobra.ExactArgs(3)),
	ValidArgsFunction: cobra.NoFileCompletions,
	RunE:              contextSetCmdFunc,
}

var contextRemoveCmd = &cobra.Command{
	Use:               "remove <system>",
	Short:             "Removes a context",
	Aliases:           []string{"rm"},
	Args:              commands.ValidationWrapper(cobra.ExactArgs(1)),
	ValidArgsFunction: ContextGet,
	RunE:              contextRemoveCmdFunc,
}

var contextUseCmd = &cobra.Command{
	Use:               "use <system>",
	Short:             "Sets a context as the current context",
	Args:              commands.ValidationWrapper(cobra.MaximumNArgs(1)),
	ValidArgsFunction: ContextGet,
	RunE:              contextUseCmdFunc,
}

func ContextGet(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
	_, secretStore := client.DefaultStorage()
	secrets, err := secretStore.Get()
	if err != nil {
		return nil, cobra.ShellCompDirectiveError
	}

	names := make([]string, 0, len(secrets.Tokens))
	for _, token := range secrets.Tokens {
		names = append(names, token.Name)
	}

	return names, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveKeepOrder
}

func contextListCmdFunc(cmd *cobra.Command, _ []string) error {
	cfgStore, secretStore := client.DefaultStorage()
	secrets, err := secretStore.Get()
	if err != nil {
		return err
	}

	cfg, err := cfgStore.Get()
	if err != nil {
		return err
	}

	rows := make([][]string, 0, len(secrets.Tokens))
	for _, token := range secrets.Tokens {
		current := ""
		if token.Name == cfg.CurrentToken {
			current = "   ✓   "
		}
		secret := token.APIToken
		if !cobrautil.MustGetBool(cmd, "reveal-tokens") {
			secret = token.Redacted()
		}

		var certStr string
		if token.IsInsecure() {
			certStr = "insecure"
		} else if token.HasNoVerifyCA() {
			certStr = "no-verify-ca"
		} else if _, ok := token.Certificate(); ok {
			certStr = "custom"
		} else {
			certStr = "system"
		}

		rows = append(rows, []string{
			current,
			token.Name,
			token.Endpoint,
			secret,
			certStr,
		})
	}

	printers.PrintTable(os.Stdout, []string{"current", "name", "endpoint", "token", "tls cert"}, rows)

	return nil
}

func contextSetCmdFunc(cmd *cobra.Command, args []string) error {
	var name, endpoint, apiToken string
	err := stringz.Unpack(args, &name, &endpoint, &apiToken)
	if err != nil {
		return err
	}

	certPath := cobrautil.MustGetStringExpanded(cmd, "certificate-path")
	var certBytes []byte
	if certPath != "" {
		certBytes, err = os.ReadFile(certPath)
		if err != nil {
			return fmt.Errorf("failed to read ceritficate: %w", err)
		}
	}

	insecure := cobrautil.MustGetBool(cmd, "insecure")
	noVerifyCA := cobrautil.MustGetBool(cmd, "no-verify-ca")
	cfgStore, secretStore := client.DefaultStorage()
	err = storage.PutToken(storage.Token{
		Name:       name,
		Endpoint:   stringz.DefaultEmpty(endpoint, "grpc.authzed.com:443"),
		APIToken:   apiToken,
		Insecure:   &insecure,
		NoVerifyCA: &noVerifyCA,
		CACert:     certBytes,
	}, secretStore)
	if err != nil {
		return err
	}

	return storage.SetCurrentToken(name, cfgStore, secretStore)
}

func contextRemoveCmdFunc(_ *cobra.Command, args []string) error {
	// If the token is what's currently being used, remove it from the config.
	cfgStore, secretStore := client.DefaultStorage()
	cfg, err := cfgStore.Get()
	if err != nil {
		return err
	}

	if cfg.CurrentToken == args[0] {
		cfg.CurrentToken = ""
	}

	err = cfgStore.Put(cfg)
	if err != nil {
		return err
	}

	return storage.RemoveToken(args[0], secretStore)
}

func contextUseCmdFunc(_ *cobra.Command, args []string) error {
	cfgStore, secretStore := client.DefaultStorage()
	switch len(args) {
	case 0:
		cfg, err := cfgStore.Get()
		if err != nil {
			return err
		}
		console.Println(cfg.CurrentToken)
	case 1:
		return storage.SetCurrentToken(args[0], cfgStore, secretStore)
	default:
		panic("cobra command did not enforce valid number of args")
	}

	return nil
}