forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_jenkins_token.go
339 lines (297 loc) · 9.17 KB
/
create_jenkins_token.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
package cmd
import (
"bufio"
"context"
"fmt"
"io"
"io/ioutil"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/chromedp"
"github.com/chromedp/chromedp/runner"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/jenkins"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
cmdutil "github.com/jenkins-x/jx/pkg/jx/cmd/util"
"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"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
create_jenkins_user_long = templates.LongDesc(`
Creates a new user and API Token for the current Jenkins Server
`)
create_jenkins_user_example = templates.Examples(`
# Add a new API Token for a user for the current Jenkins server
# prompting the user to find and enter the API Token
jx create jenkins token someUserName
# Add a new API Token for a user for the current Jenkins server
# using browser automation to login to the git server
# with the username an password to find the API Token
jx create jenkins token -p somePassword someUserName
`)
)
// CreateJenkinsUserOptions the command line options for the command
type CreateJenkinsUserOptions struct {
CreateOptions
ServerFlags ServerFlags
Username string
Password string
ApiToken string
Timeout string
UseBrowser bool
}
// NewCmdCreateJenkinsUser creates a command
func NewCmdCreateJenkinsUser(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command {
options := &CreateJenkinsUserOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "token [username]",
Short: "Adds a new username and api token for a Jenkins server",
Aliases: []string{"api-token"},
Long: create_jenkins_user_long,
Example: create_jenkins_user_example,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
cmdutil.CheckErr(err)
},
}
options.addCommonFlags(cmd)
options.ServerFlags.addGitServerFlags(cmd)
cmd.Flags().StringVarP(&options.ApiToken, "api-token", "t", "", "The API Token for the user")
cmd.Flags().StringVarP(&options.Password, "password", "p", "", "The User password to try automatically create a new API Token")
cmd.Flags().StringVarP(&options.Timeout, "timeout", "", "", "The timeout if using browser automation to generate the API token (by passing username and password)")
cmd.Flags().BoolVarP(&options.UseBrowser, "browser", "", false, "Use a Chrome browser to automatically find the API token if the user and password are known")
return cmd
}
// Run implements the command
func (o *CreateJenkinsUserOptions) Run() error {
args := o.Args
if len(args) > 0 {
o.Username = args[0]
}
if len(args) > 1 {
o.ApiToken = args[1]
}
kubeClient, ns, err := o.KubeClient()
if err != nil {
return fmt.Errorf("error connecting to kubernetes cluster: %v", err)
}
authConfigSvc, err := o.Factory.CreateJenkinsAuthConfigService(kubeClient, ns)
if err != nil {
return err
}
config := authConfigSvc.Config()
var server *auth.AuthServer
if o.ServerFlags.IsEmpty() {
url := ""
url, err = o.findService(kube.ServiceJenkins)
if err != nil {
return err
}
server = config.GetOrCreateServer(url)
} else {
server, err = o.findServer(config, &o.ServerFlags, "jenkins server", "Try installing one via: jx create team", false)
if err != nil {
return err
}
}
// TODO add the API thingy...
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
}
tokenUrl := jenkins.JenkinsTokenURL(server.URL)
if o.Verbose {
log.Infof("using url %s\n", tokenUrl)
}
if userAuth.IsInvalid() && o.Password != "" && o.UseBrowser {
err := o.tryFindAPITokenFromBrowser(tokenUrl, userAuth)
if err != nil {
log.Warnf("unable to automatically find API token with chromedp using URL %s\n", tokenUrl)
}
}
if userAuth.IsInvalid() {
f := func(username string) error {
jenkins.PrintGetTokenFromURL(o.Out, tokenUrl)
log.Infof("Then COPY the token and enter in into the form below:\n\n")
return nil
}
err = config.EditUserAuth("Jenkins", userAuth, o.Username, false, o.BatchMode, f)
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
}
// now lets create a secret for it so we can perform incluster interactions with Jenkins
s, err := o.kubeClient.CoreV1().Secrets(o.currentNamespace).Get(kube.SecretJenkins, metav1.GetOptions{})
if err != nil {
return err
}
s.Data[kube.JenkinsAdminApiToken] = []byte(userAuth.ApiToken)
_, err = o.kubeClient.CoreV1().Secrets(o.currentNamespace).Update(s)
if err != nil {
return err
}
log.Infof("Created user %s API Token for Jenkins server %s at %s\n",
util.ColorInfo(o.Username), util.ColorInfo(server.Name), util.ColorInfo(server.URL))
return nil
}
// lets try use the users browser to find the API token
func (o *CreateJenkinsUserOptions) tryFindAPITokenFromBrowser(tokenUrl string, userAuth *auth.UserAuth) error {
var ctxt context.Context
var cancel context.CancelFunc
if o.Timeout != "" {
duration, err := time.ParseDuration(o.Timeout)
if err != nil {
return err
}
ctxt, cancel = context.WithTimeout(context.Background(), duration)
} else {
ctxt, cancel = context.WithCancel(context.Background())
}
defer cancel()
c, err := o.createChromeClient(ctxt)
if err != nil {
return err
}
err = c.Run(ctxt, chromedp.Tasks{
chromedp.Navigate(tokenUrl),
})
if err != nil {
return err
}
nodeSlice := []*cdp.Node{}
err = c.Run(ctxt, chromedp.Nodes("//input", &nodeSlice))
if err != nil {
return err
}
login := false
userNameInputName := "j_username"
passwordInputSelector := "//input[@name='j_password']"
for _, node := range nodeSlice {
name := node.AttributeValue("name")
if name == userNameInputName {
login = true
}
}
if login {
// disable screenshots to try and reduce errors when running headless
//o.captureScreenshot(ctxt, c, "screenshot-jenkins-login.png", "main-panel", chromedp.ByID)
log.Infoln("logging in")
err = c.Run(ctxt, chromedp.Tasks{
chromedp.WaitVisible(userNameInputName, chromedp.ByID),
chromedp.SendKeys(userNameInputName, userAuth.Username, chromedp.ByID),
chromedp.SendKeys(passwordInputSelector, o.Password+"\n"),
})
if err != nil {
return err
}
}
// disable screenshots to try and reduce errors when running headless
//o.captureScreenshot(ctxt, c, "screenshot-jenkins-api-token.png", "main-panel", chromedp.ByID)
getAPITokenButtonSelector := "//button[normalize-space(text())='Show API Token...']"
nodeSlice = []*cdp.Node{}
log.Infoln("Getting the API Token...")
err = c.Run(ctxt, chromedp.Tasks{
chromedp.Sleep(2 * time.Second),
chromedp.WaitVisible(getAPITokenButtonSelector),
chromedp.Click(getAPITokenButtonSelector),
//chromedp.WaitVisible("apiToken", chromedp.ByID),
chromedp.Nodes("apiToken", &nodeSlice, chromedp.ByID),
})
if err != nil {
return err
}
token := ""
for _, node := range nodeSlice {
text := node.AttributeValue("value")
if text != "" && token == "" {
token = text
break
}
}
log.Infoln("Found API Token")
if token != "" {
userAuth.ApiToken = token
}
err = c.Shutdown(ctxt)
if err != nil {
return err
}
return nil
}
// lets try use the users browser to find the API token
func (o *CommonOptions) createChromeClient(ctxt context.Context) (*chromedp.CDP, error) {
if o.Headless {
options := func(m map[string]interface{}) error {
m["remote-debugging-port"] = 9222
m["no-sandbox"] = true
m["headless"] = true
return nil
}
return chromedp.New(ctxt, chromedp.WithRunnerOptions(runner.CommandLineOption(options)))
}
return chromedp.New(ctxt)
}
func (o *CommonOptions) captureScreenshot(ctxt context.Context, c *chromedp.CDP, screenshotFile string, selector interface{}, options ...chromedp.QueryOption) error {
log.Infoln("Creating a screenshot...")
var picture []byte
err := c.Run(ctxt, chromedp.Tasks{
chromedp.Sleep(2 * time.Second),
chromedp.Screenshot(selector, &picture, options...),
})
if err != nil {
return err
}
log.Infoln("Saving a screenshot...")
err = ioutil.WriteFile(screenshotFile, picture, util.DefaultWritePermissions)
if err != nil {
log.Fatal(err.Error())
}
log.Infof("Saved screenshot: %s\n", util.ColorInfo(screenshotFile))
return err
}
func (o *CommonOptions) createChromeDPLogger() (chromedp.LogFunc, error) {
var logger chromedp.LogFunc
if o.Verbose {
logger = func(message string, args ...interface{}) {
log.Infof(message+"\n", args...)
}
} else {
file, err := ioutil.TempFile("", "jx-browser")
if err != nil {
return logger, err
}
writer := bufio.NewWriter(file)
log.Infof("Chrome debugging logs written to: %s\n", util.ColorInfo(file.Name()))
logger = func(message string, args ...interface{}) {
fmt.Fprintf(writer, message+"\n", args...)
}
}
return logger, nil
}