-
Notifications
You must be signed in to change notification settings - Fork 4
/
root.go
283 lines (244 loc) · 8.93 KB
/
root.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
package cmd
import (
"errors"
"fmt"
"github.com/opentdf/otdfctl/pkg/auth"
"github.com/opentdf/otdfctl/pkg/cli"
"github.com/opentdf/otdfctl/pkg/config"
"github.com/opentdf/otdfctl/pkg/handlers"
"github.com/opentdf/otdfctl/pkg/man"
"github.com/opentdf/otdfctl/pkg/profiles"
"github.com/spf13/cobra"
)
var (
cfgKey string
OtdfctlCfg config.Config
clientCredsFile string
clientCredsJSON string
configFlagOverrides = config.ConfigFlagOverrides{}
profile *profiles.Profile
RootCmd = &man.Docs.GetDoc("<root>").Command
)
type version struct {
AppName string `json:"app_name"`
Version string `json:"version"`
CommitSha string `json:"commit_sha"`
BuildTime string `json:"build_time"`
}
// InitProfile initializes the profile store and loads the profile specified in the flags
// if onlyNew is set to true, a new profile will be created and returned
// returns the profile and the current profile store
func InitProfile(c *cli.Cli, onlyNew bool) (*profiles.Profile, *profiles.ProfileStore) {
var err error
profileName := c.FlagHelper.GetOptionalString("profile")
profile, err = profiles.New()
if err != nil || profile == nil {
c.ExitWithError("Failed to initialize profile store", err)
}
// short circuit if onlyNew is set to enable creating a new profile
if onlyNew && profileName == "" {
return profile, nil
}
// check if there exists a default profile and warn if not with steps to create one
if profile.GetGlobalConfig().GetDefaultProfile() == "" {
c.ExitWithWarning(fmt.Sprintf("No default profile set. Use `%s profile create <profile> <endpoint>` to create a default profile.", config.AppName))
}
if profileName == "" {
profileName = profile.GetGlobalConfig().GetDefaultProfile()
}
c.Printf("Using profile [%s]\n", profileName)
// load profile
cp, err := profile.UseProfile(profileName)
if err != nil {
c.ExitWithError(fmt.Sprintf("Failed to load profile: %s", profileName), err)
}
return profile, cp
}
// instantiates a new handler with authentication via client credentials
// TODO make this a preRun hook
//
//nolint:nestif // separate refactor [https://github.com/opentdf/otdfctl/issues/383]
func NewHandler(c *cli.Cli) handlers.Handler {
// if global flags are set then validate and create a temporary profile in memory
var cp *profiles.ProfileStore
// Non-profile flags
host := c.FlagHelper.GetOptionalString("host")
tlsNoVerify := c.FlagHelper.GetOptionalBool("tls-no-verify")
withClientCreds := c.FlagHelper.GetOptionalString("with-client-creds")
withClientCredsFile := c.FlagHelper.GetOptionalString("with-client-creds-file")
withAccessToken := c.FlagHelper.GetOptionalString("with-access-token")
var inMemoryProfile bool
authFlags := []string{"--with-access-token", "--with-client-creds", "--with-client-creds-file"}
nonProfileFlags := append([]string{"--host", "--tls-no-verify"}, authFlags...)
hasNonProfileFlags := host != "" || tlsNoVerify || withClientCreds != "" || withClientCredsFile != "" || withAccessToken != ""
//nolint:nestif // nested if statements are necessary for validation
if hasNonProfileFlags {
err := fmt.Errorf("when using global flags %s, profiles will not be used and all required flags must be set", cli.PrettyList(nonProfileFlags))
// host must be set
if host == "" {
cli.ExitWithError("Host must be set", err)
}
authFlagsCounter := 0
if withAccessToken != "" {
authFlagsCounter++
}
if withClientCreds != "" {
authFlagsCounter++
}
if withClientCredsFile != "" {
authFlagsCounter++
}
if authFlagsCounter == 0 {
cli.ExitWithError(fmt.Sprintf("One of %s must be set", cli.PrettyList(authFlags)), err)
} else if authFlagsCounter > 1 {
cli.ExitWithError(fmt.Sprintf("Only one of %s must be set", cli.PrettyList(authFlags)), err)
}
inMemoryProfile = true
profile, err = profiles.New(profiles.WithInMemoryStore())
if err != nil || profile == nil {
cli.ExitWithError("Failed to initialize in-memory profile", err)
}
if err := profile.AddProfile("temp", host, tlsNoVerify, true); err != nil {
cli.ExitWithError("Failed to create in-memory profile", err)
}
// add credentials to the temporary profile
cp, err = profile.UseProfile("temp")
if err != nil {
cli.ExitWithError("Failed to load in-memory profile", err)
}
// get credentials from flags
if withAccessToken != "" {
claims, err := auth.ParseClaimsJWT(withAccessToken)
if err != nil {
cli.ExitWithError("Failed to get access token", err)
}
if err := cp.SetAuthCredentials(profiles.AuthCredentials{
AuthType: profiles.PROFILE_AUTH_TYPE_ACCESS_TOKEN,
AccessToken: profiles.AuthCredentialsAccessToken{
AccessToken: withAccessToken,
Expiration: claims.Expiration,
},
}); err != nil {
cli.ExitWithError("Failed to set access token", err)
}
} else {
var cc auth.ClientCredentials
if withClientCreds != "" {
cc, err = auth.GetClientCredsFromJSON([]byte(withClientCreds))
} else if withClientCredsFile != "" {
cc, err = auth.GetClientCredsFromFile(withClientCredsFile)
}
if err != nil {
cli.ExitWithError("Failed to get client credentials", err)
}
// add credentials to the temporary profile
if err := cp.SetAuthCredentials(profiles.AuthCredentials{
AuthType: profiles.PROFILE_AUTH_TYPE_CLIENT_CREDENTIALS,
ClientId: cc.ClientId,
ClientSecret: cc.ClientSecret,
}); err != nil {
cli.ExitWithError("Failed to set client credentials", err)
}
}
if err := cp.Save(); err != nil {
cli.ExitWithError("Failed to save profile", err)
}
} else {
profile, cp = InitProfile(c, false)
}
if err := auth.ValidateProfileAuthCredentials(c.Context(), cp); err != nil {
if errors.Is(err, auth.ErrPlatformConfigNotFound) {
cli.ExitWithError(fmt.Sprintf("Failed to get platform configuration. Is the platform accepting connections at '%s'?", cp.GetEndpoint()), nil)
}
if inMemoryProfile {
cli.ExitWithError("Failed to authenticate with flag-provided client credentials.", err)
}
if errors.Is(err, auth.ErrProfileCredentialsNotFound) {
cli.ExitWithWarning("Profile missing credentials. Please login or add client credentials.")
}
if errors.Is(err, auth.ErrAccessTokenExpired) {
cli.ExitWithWarning("Access token expired. Please login or add flag-provided credentials.")
}
if errors.Is(err, auth.ErrAccessTokenNotFound) {
cli.ExitWithWarning("No access token found. Please login or add flag-provided credentials.")
}
cli.ExitWithError("Failed to get access token.", err)
}
h, err := handlers.New(handlers.WithProfile(cp))
if err != nil {
cli.ExitWithError("Unexpected error", err)
}
return h
}
func init() {
rootCmd := man.Docs.GetCommand("<root>", man.WithRun(func(cmd *cobra.Command, args []string) {
c := cli.New(cmd, args)
if c.Flags.GetOptionalBool("version") {
v := version{
AppName: config.AppName,
Version: config.Version,
CommitSha: config.CommitSha,
BuildTime: config.BuildTime,
}
c.Println(fmt.Sprintf("%s version %s (%s) %s", config.AppName, config.Version, config.BuildTime, config.CommitSha))
c.ExitWithJSON(v)
return
}
//nolint:errcheck // error does not need to be checked
cmd.Help()
}))
RootCmd = &rootCmd.Command
RootCmd.Flags().Bool(
rootCmd.GetDocFlag("version").Name,
rootCmd.GetDocFlag("version").DefaultAsBool(),
rootCmd.GetDocFlag("version").Description,
)
RootCmd.PersistentFlags().Bool(
rootCmd.GetDocFlag("debug").Name,
rootCmd.GetDocFlag("debug").DefaultAsBool(),
rootCmd.GetDocFlag("debug").Description,
)
RootCmd.PersistentFlags().Bool(
rootCmd.GetDocFlag("json").Name,
rootCmd.GetDocFlag("json").DefaultAsBool(),
rootCmd.GetDocFlag("json").Description,
)
RootCmd.PersistentFlags().String(
rootCmd.GetDocFlag("profile").Name,
rootCmd.GetDocFlag("profile").Default,
rootCmd.GetDocFlag("profile").Description,
)
RootCmd.PersistentFlags().String(
rootCmd.GetDocFlag("host").Name,
rootCmd.GetDocFlag("host").Default,
rootCmd.GetDocFlag("host").Description,
)
RootCmd.PersistentFlags().Bool(
rootCmd.GetDocFlag("tls-no-verify").Name,
rootCmd.GetDocFlag("tls-no-verify").DefaultAsBool(),
rootCmd.GetDocFlag("tls-no-verify").Description,
)
RootCmd.PersistentFlags().String(
rootCmd.GetDocFlag("log-level").Name,
rootCmd.GetDocFlag("log-level").Default,
rootCmd.GetDocFlag("log-level").Description,
)
RootCmd.PersistentFlags().StringVar(
&clientCredsFile,
rootCmd.GetDocFlag("with-client-creds-file").Name,
rootCmd.GetDocFlag("with-client-creds-file").Default,
rootCmd.GetDocFlag("with-client-creds-file").Description,
)
RootCmd.PersistentFlags().StringVar(
&clientCredsJSON,
rootCmd.GetDocFlag("with-client-creds").Name,
rootCmd.GetDocFlag("with-client-creds").Default,
rootCmd.GetDocFlag("with-client-creds").Description,
)
RootCmd.PersistentFlags().String(
rootCmd.GetDocFlag("with-access-token").Name,
rootCmd.GetDocFlag("with-access-token").Default,
rootCmd.GetDocFlag("with-access-token").Description,
)
RootCmd.AddGroup(&cobra.Group{ID: TDF})
}