-
Notifications
You must be signed in to change notification settings - Fork 72
/
reset_credentials.go
262 lines (214 loc) · 8.91 KB
/
reset_credentials.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
package resetcredentials
import (
"context"
"fmt"
"net/http"
"os"
kafkamgmtclient "github.com/redhat-developer/app-services-sdk-go/kafkamgmt/apiv1/client"
"github.com/redhat-developer/app-services-cli/pkg/color"
"github.com/redhat-developer/app-services-cli/pkg/connection"
"github.com/redhat-developer/app-services-cli/pkg/icon"
"github.com/redhat-developer/app-services-cli/pkg/localize"
"github.com/AlecAivazis/survey/v2"
flagutil "github.com/redhat-developer/app-services-cli/pkg/cmdutil/flags"
"github.com/redhat-developer/app-services-cli/pkg/iostreams"
"github.com/redhat-developer/app-services-cli/pkg/serviceaccount/credentials"
"github.com/redhat-developer/app-services-cli/pkg/serviceaccount/validation"
"github.com/redhat-developer/app-services-cli/internal/config"
"github.com/redhat-developer/app-services-cli/pkg/cmd/factory"
"github.com/redhat-developer/app-services-cli/pkg/cmd/flag"
"github.com/redhat-developer/app-services-cli/pkg/logging"
"github.com/spf13/cobra"
)
type options struct {
IO *iostreams.IOStreams
Config config.IConfig
Connection factory.ConnectionFunc
Logger logging.Logger
localizer localize.Localizer
Context context.Context
id string
fileFormat string
overwrite bool
filename string
interactive bool
force bool
}
// NewResetCredentialsCommand creates a new command to delete a service account
func NewResetCredentialsCommand(f *factory.Factory) *cobra.Command {
opts := &options{
IO: f.IOStreams,
Config: f.Config,
Connection: f.Connection,
Logger: f.Logger,
localizer: f.Localizer,
Context: f.Context,
}
cmd := &cobra.Command{
Use: "reset-credentials",
Short: opts.localizer.MustLocalize("serviceAccount.resetCredentials.cmd.shortDescription"),
Long: opts.localizer.MustLocalize("serviceAccount.resetCredentials.cmd.longDescription"),
Example: opts.localizer.MustLocalize("serviceAccount.resetCredentials.cmd.example"),
RunE: func(cmd *cobra.Command, _ []string) error {
if !opts.IO.CanPrompt() && opts.id == "" {
return opts.localizer.MustLocalizeError("flag.error.requiredWhenNonInteractive", localize.NewEntry("Flag", "id"))
} else if opts.id == "" {
opts.interactive = true
}
if !opts.interactive && opts.fileFormat == "" {
return opts.localizer.MustLocalizeError("flag.error.requiredWhenNonInteractive", localize.NewEntry("Flag", "file-format"))
}
validOutput := flagutil.IsValidInput(opts.fileFormat, flagutil.CredentialsOutputFormats...)
if !validOutput && opts.fileFormat != "" {
return flag.InvalidValueError("file-format", opts.fileFormat, flagutil.CredentialsOutputFormats...)
}
if !opts.interactive {
validator := &validation.Validator{
Localizer: opts.localizer,
}
validID := validator.ValidateUUID(opts.id)
if validID != nil {
return validID
}
}
return runResetCredentials(opts)
},
}
cmd.Flags().StringVar(&opts.id, "id", "", opts.localizer.MustLocalize("serviceAccount.resetCredentials.flag.id.description"))
cmd.Flags().BoolVar(&opts.overwrite, "overwrite", false, opts.localizer.MustLocalize("serviceAccount.common.flag.overwrite.description"))
cmd.Flags().StringVar(&opts.filename, "output-file", "", opts.localizer.MustLocalize("serviceAccount.common.flag.fileLocation.description"))
cmd.Flags().StringVar(&opts.fileFormat, "file-format", "", opts.localizer.MustLocalize("serviceAccount.common.flag.fileFormat.description"))
cmd.Flags().BoolVarP(&opts.force, "yes", "y", false, opts.localizer.MustLocalize("serviceAccount.resetCredentials.flag.yes.description"))
flagutil.EnableStaticFlagCompletion(cmd, "file-format", flagutil.CredentialsOutputFormats)
return cmd
}
// nolint:funlen
func runResetCredentials(opts *options) (err error) {
conn, err := opts.Connection(connection.DefaultConfigSkipMasAuth)
if err != nil {
return err
}
api := conn.API()
_, httpRes, err := api.ServiceAccount().GetServiceAccountById(opts.Context, opts.id).Execute()
if httpRes != nil {
defer httpRes.Body.Close()
}
if err != nil {
return err
}
if opts.interactive {
err = runInteractivePrompt(opts)
if err != nil {
return err
}
} else if opts.filename == "" {
// obtain the default absolute path to where credentials will be saved
opts.filename = credentials.GetDefaultPath(opts.fileFormat)
}
// If the credentials file already exists, and the --overwrite flag is not set then return an error
// indicating that the user should explicitly request overwriting of the file
if _, err = os.Stat(opts.filename); err == nil && !opts.overwrite {
return opts.localizer.MustLocalizeError("serviceAccount.common.error.credentialsFileAlreadyExists", localize.NewEntry("FilePath", color.CodeSnippet(opts.filename)))
}
if !opts.force {
// prompt the user to confirm their wish to proceed with this action
var confirmReset bool
opts.localizer.MustLocalize("serviceAccount.resetCredentials.input.confirmReset.message", localize.NewEntry("ID", opts.id))
promptConfirmDelete := &survey.Confirm{
Message: opts.localizer.MustLocalize("serviceAccount.resetCredentials.input.confirmReset.message", localize.NewEntry("ID", opts.id)),
}
if err = survey.AskOne(promptConfirmDelete, &confirmReset); err != nil {
return err
}
if !confirmReset {
opts.Logger.Debug(opts.localizer.MustLocalize("serviceAccount.resetCredentials.log.debug.cancelledReset"))
return nil
}
}
updatedServiceAccount, err := resetCredentials(opts)
if err != nil {
return fmt.Errorf("%v: %w", opts.localizer.MustLocalize("serviceAccount.resetCredentials.error.resetError", localize.NewEntry("ID", opts.id)), err)
}
opts.Logger.Info(icon.SuccessPrefix(), opts.localizer.MustLocalize("serviceAccount.resetCredentials.log.info.resetSuccess", localize.NewEntry("ID", updatedServiceAccount.GetId())))
cfg, err := opts.Config.Load()
if err != nil {
return err
}
creds := &credentials.Credentials{
ClientID: updatedServiceAccount.GetClientId(),
ClientSecret: updatedServiceAccount.GetClientSecret(),
TokenURL: cfg.MasAuthURL + "/protocol/openid-connect/token",
}
// save the credentials to a file
err = credentials.Write(opts.fileFormat, opts.filename, creds)
if err != nil {
return err
}
opts.Logger.Info(icon.SuccessPrefix(), opts.localizer.MustLocalize("serviceAccount.common.log.info.credentialsSaved", localize.NewEntry("FilePath", opts.filename)))
return nil
}
func resetCredentials(opts *options) (*kafkamgmtclient.ServiceAccount, error) {
conn, err := opts.Connection(connection.DefaultConfigSkipMasAuth)
if err != nil {
return nil, err
}
// check if the service account exists
api := conn.API()
opts.Logger.Debug(opts.localizer.MustLocalize("serviceAccount.resetCredentials.log.debug.resettingCredentials", localize.NewEntry("ID", opts.id)))
serviceacct, httpRes, err := api.ServiceAccount().ResetServiceAccountCreds(opts.Context, opts.id).Execute()
if httpRes != nil {
defer httpRes.Body.Close()
}
if err != nil {
if httpRes == nil {
return nil, err
}
switch httpRes.StatusCode {
case http.StatusForbidden:
opts.localizer.MustLocalize("serviceAccount.common.error.forbidden", localize.NewEntry("Operation", "update"))
return nil, fmt.Errorf("%v: %w", opts.localizer.MustLocalize("serviceAccount.common.error.forbidden", localize.NewEntry("Operation", "update")), err)
case http.StatusInternalServerError:
return nil, opts.localizer.MustLocalizeError("serviceAccount.common.error.internalServerError")
default:
return nil, err
}
}
return &serviceacct, nil
}
func runInteractivePrompt(opts *options) (err error) {
_, err = opts.Connection(connection.DefaultConfigSkipMasAuth)
if err != nil {
return err
}
opts.Logger.Debug(opts.localizer.MustLocalize("common.log.debug.startingInteractivePrompt"))
promptID := &survey.Input{
Message: opts.localizer.MustLocalize("serviceAccount.resetCredentials.input.id.message"),
Help: opts.localizer.MustLocalize("serviceAccount.resetCredentials.input.id.help"),
}
validator := &validation.Validator{
Localizer: opts.localizer,
}
err = survey.AskOne(promptID, &opts.id, survey.WithValidator(survey.Required), survey.WithValidator(validator.ValidateUUID))
if err != nil {
return err
}
// if the --output flag was not used, ask in the prompt
if opts.fileFormat == "" {
opts.Logger.Debug(opts.localizer.MustLocalize("serviceAccount.common.log.debug.interactive.fileFormatNotSet"))
fileFormatPrompt := &survey.Select{
Message: opts.localizer.MustLocalize("serviceAccount.resetCredentials.input.fileFormat.message"),
Help: opts.localizer.MustLocalize("serviceAccount.resetCredentials.input.fileFormat.help"),
Options: flagutil.CredentialsOutputFormats,
Default: credentials.EnvFormat,
}
err = survey.AskOne(fileFormatPrompt, &opts.fileFormat)
if err != nil {
return err
}
}
opts.filename, opts.overwrite, err = credentials.ChooseFileLocation(opts.fileFormat, opts.filename, opts.overwrite)
if err != nil {
return err
}
return err
}