-
Notifications
You must be signed in to change notification settings - Fork 786
/
create_token_addon.go
214 lines (198 loc) · 6 KB
/
create_token_addon.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
package cmd
import (
"fmt"
"io"
"github.com/jenkins-x/jx/pkg/addon"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1/terminal"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
createTokenAddonLong = templates.LongDesc(`
Creates a new User Token for an Addon service
`)
createTokenAddonExample = templates.Examples(`
# Add a new User Token for an addonservice
jx create token addon -n anchore someUserName
# As above with the password being passed in
jx create token addon -n anchore -p somePassword someUserName
`)
)
// CreateTokenAddonOptions the command line options for the command
type CreateTokenAddonOptions struct {
CreateOptions
ServerFlags ServerFlags
Username string
Password string
ApiToken string
Timeout string
Kind string
}
// NewCmdCreateTokenAddon creates a command
func NewCmdCreateTokenAddon(f Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) *cobra.Command {
options := &CreateTokenAddonOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
In: in,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "addon [username]",
Short: "Adds a new token/login for a user for a given addon",
Aliases: []string{"login"},
Long: createTokenAddonLong,
Example: createTokenAddonExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
options.addCommonFlags(cmd)
options.ServerFlags.addGitServerFlags(cmd)
cmd.Flags().StringVarP(&options.Password, "password", "p", "", "The password for the user")
cmd.Flags().StringVarP(&options.ApiToken, "api-token", "t", "", "The API Token for the user")
cmd.Flags().StringVarP(&options.Timeout, "timeout", "", "", "The timeout if using browser automation to generate the API token (by passing username and password)")
cmd.Flags().StringVarP(&options.Kind, "kind", "k", "", "The kind of addon. Defaults to the addon name if not specified")
return cmd
}
// Run implements the command
func (o *CreateTokenAddonOptions) Run() error {
args := o.Args
if len(args) > 0 {
o.Username = args[0]
}
if len(args) > 1 {
o.ApiToken = args[1]
}
authConfigSvc, err := o.createAddonAuthConfigService()
if err != nil {
return err
}
config := authConfigSvc.Config()
kind := o.Kind
if kind == "" {
kind = o.ServerFlags.ServerName
}
if kind == "" {
kind = "addon"
}
var server *auth.AuthServer
server, err = o.findAddonServer(config, &o.ServerFlags, kind)
if err != nil {
return err
}
if o.Username == "" {
return fmt.Errorf("No Username specified")
}
userAuth := config.GetOrCreateUserAuth(server.URL, o.Username)
if o.ApiToken != "" {
userAuth.ApiToken = o.ApiToken
}
if o.Password != "" {
userAuth.Password = o.Password
} else {
tokenUrl := addon.ProviderAccessTokenURL(server.Kind, server.URL)
if userAuth.IsInvalid() {
f := func(username string) error {
log.Infof("Please generate an API Token for %s server %s\n", server.Kind, server.Label())
if tokenUrl != "" {
log.Infof("Click this URL %s\n\n", util.ColorInfo(tokenUrl))
}
log.Info("Then COPY the token and enter in into the form below:\n\n")
return nil
}
err = config.EditUserAuth(server.Label(), userAuth, o.Username, false, o.BatchMode, f, o.In, o.Out, o.Err)
if err != nil {
return err
}
if userAuth.IsInvalid() {
return fmt.Errorf("You did not properly define the user authentication!")
}
}
}
config.CurrentServer = server.URL
err = authConfigSvc.SaveConfig()
if err != nil {
return err
}
err = o.updateAddonCredentialsSecret(server, userAuth)
if err != nil {
log.Warnf("Failed to update addon credentials secret: %v\n", err)
}
log.Infof("Created user %s API Token for addon server %s at %s\n",
util.ColorInfo(o.Username), util.ColorInfo(server.Name), util.ColorInfo(server.URL))
return nil
}
func (o *CreateTokenAddonOptions) updateAddonCredentialsSecret(server *auth.AuthServer, userAuth *auth.UserAuth) error {
client, curNs, err := o.KubeClientAndNamespace()
if err != nil {
return err
}
ns, _, err := kube.GetDevNamespace(client, curNs)
if err != nil {
return err
}
options := metav1.GetOptions{}
name := kube.ToValidName(kube.SecretJenkinsPipelineAddonCredentials + server.Kind + "-" + server.Name)
secrets := client.CoreV1().Secrets(ns)
secret, err := secrets.Get(name, options)
create := false
operation := "update"
labels := map[string]string{
kube.LabelCredentialsType: kube.ValueCredentialTypeUsernamePassword,
kube.LabelCreatedBy: kube.ValueCreatedByJX,
kube.LabelKind: kube.ValueKindAddon,
kube.LabelServiceKind: server.Kind,
}
annotations := map[string]string{
kube.AnnotationCredentialsDescription: fmt.Sprintf("API Token for acccessing %s addon inside pipelines", server.URL),
kube.AnnotationURL: server.URL,
kube.AnnotationName: server.Name,
}
if err != nil {
// lets create a new secret
create = true
operation = "create"
secret = &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Annotations: annotations,
Labels: labels,
},
Data: map[string][]byte{},
}
} else {
secret.Annotations = util.MergeMaps(secret.Annotations, annotations)
secret.Labels = util.MergeMaps(secret.Labels, labels)
}
if userAuth.Username != "" {
secret.Data["username"] = []byte(userAuth.Username)
}
if userAuth.Password != "" {
secret.Data["password"] = []byte(userAuth.Password)
}
if userAuth.ApiToken != "" {
secret.Data["password"] = []byte(userAuth.ApiToken)
}
if create {
_, err = secrets.Create(secret)
} else {
_, err = secrets.Update(secret)
}
if err != nil {
return fmt.Errorf("Failed to %s secret %s due to %s", operation, secret.Name, err)
}
return nil
}