-
Notifications
You must be signed in to change notification settings - Fork 1
/
create_jenkins_token.go
564 lines (502 loc) · 15.6 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
package cmd
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/blang/semver"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"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"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1/terminal"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
JenkinsCookieName = "JSESSIONID"
JenkinsVersionHeader = "X-Jenkins"
)
var JenkinsReferenceVersion = semver.Version{Major: 2, Minor: 140, Patch: 0}
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 Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) *cobra.Command {
options := &CreateJenkinsUserOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
In: in,
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()
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 {
apiUrl := jenkins.JenkinsApiURL(server.URL)
version, err := o.getJenkinsVersion(apiUrl)
if err != nil {
return errors.Wrap(err, "getting Jenkins version")
}
if version.LT(JenkinsReferenceVersion) {
err = o.tryFindAPITokenFromBrowserOlderJenkins(tokenUrl, userAuth)
} else {
newTokenUrl := jenkins.JenkinsNewTokenURL(server.URL)
err = o.tryFindAPITokenFromBrowser(tokenUrl, newTokenUrl, userAuth)
}
if err != nil {
log.Warnf("Unable to automatically find API token with chromedp using URL %s\n", tokenUrl)
log.Warnf("Error: %v\n", err)
}
}
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, 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
}
// now lets create a secret for it so we can perform incluster interactions with Jenkins
s, err := o.KubeClientCached.CoreV1().Secrets(o.currentNamespace).Get(kube.SecretJenkins, metav1.GetOptions{})
if err != nil {
return err
}
s.Data[kube.JenkinsAdminApiToken] = []byte(userAuth.ApiToken)
_, err = o.KubeClientCached.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
}
func (o *CreateJenkinsUserOptions) getJenkinsVersion(apiUrl string) (*semver.Version, error) {
client := http.Client{}
req, err := http.NewRequest(http.MethodGet, apiUrl, nil)
if err != nil {
return nil, errors.Wrap(err, "building request to receive the Jenkins version")
}
resp, err := client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "execute get Jenkins version request")
}
versionHeader, ok := resp.Header[JenkinsVersionHeader]
if !ok || len(versionHeader) == 0 {
return nil, errors.New("jenkins version header missing from http response")
}
version := versionHeader[0]
v, err := semver.ParseTolerant(version)
if err != nil {
return nil, errors.Wrap(err, "failed to parse the Jenkins version")
}
return &v, nil
}
func (o *CreateJenkinsUserOptions) tryFindAPITokenFromBrowserOlderJenkins(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
}
func (o *CreateJenkinsUserOptions) tryFindAPITokenFromBrowser(tokenUrl string, newTokenUrl string, userAuth *auth.UserAuth) error {
var ctx context.Context
var cancel context.CancelFunc
if o.Timeout != "" {
duration, err := time.ParseDuration(o.Timeout)
if err != nil {
return errors.Wrap(err, "parsing the timeout value")
}
ctx, cancel = context.WithTimeout(context.Background(), duration)
} else {
ctx, cancel = context.WithCancel(context.Background())
}
defer cancel()
userDataDir, err := ioutil.TempDir("/tmp", "jx-login-chrome-userdata-dir")
if err != nil {
return errors.Wrap(err, "creating the chrome user data dir")
}
defer os.RemoveAll(userDataDir)
netLogFile := filepath.Join(userDataDir, "net-logs.json")
c, err := o.createChromeClientWithNetLog(ctx, userDataDir, netLogFile)
if err != nil {
return errors.Wrap(err, "creating the chrome client")
}
err = c.Run(ctx, chromedp.Tasks{
chromedp.Navigate(tokenUrl),
})
if err != nil {
return errors.Wrapf(err, "navigating to token URL '%s'", tokenUrl)
}
nodeSlice := []*cdp.Node{}
err = c.Run(ctx, chromedp.Nodes("//input", &nodeSlice))
if err != nil {
return errors.Wrap(err, "serching the login form")
}
login := false
userNameInputName := "j_username"
passwordInputSelector := "//input[@name='j_password']"
for _, node := range nodeSlice {
name := node.AttributeValue("name")
if name == userNameInputName {
login = true
}
}
headerId := "header"
if login {
log.Infoln("Generating the API token...")
err = c.Run(ctx, chromedp.Tasks{
chromedp.WaitVisible(userNameInputName, chromedp.ByID),
chromedp.SendKeys(userNameInputName, userAuth.Username, chromedp.ByID),
chromedp.SendKeys(passwordInputSelector, o.Password+"\n"),
chromedp.WaitVisible(headerId, chromedp.ByID),
chromedp.ActionFunc(func(ctxt context.Context, h cdp.Executor) error {
cookies, err := network.GetCookies().Do(ctxt, h)
if err != nil {
return err
}
for _, cookie := range cookies {
if strings.HasPrefix(cookie.Name, JenkinsCookieName) {
jenkinsCookie := cookie.Name + "=" + cookie.Value
token, err := o.generateNewApiToken(newTokenUrl, jenkinsCookie)
if err != nil {
return errors.Wrap(err, "generating the API token")
}
if token != "" {
userAuth.ApiToken = token
return nil
} else {
return errors.New("received an empty API token")
}
}
}
return errors.New("no Jenkins cookie found after login")
}),
})
if err != nil {
return errors.Wrap(err, "generating the API token")
}
}
err = c.Shutdown(ctx)
if err != nil {
return errors.Wrap(err, "shutting down the chrome client")
}
return nil
}
func (o *CommonOptions) generateNewApiToken(newTokenUrl string, cookie string) (string, error) {
client := http.Client{}
req, err := http.NewRequest(http.MethodPost, newTokenUrl, nil)
if err != nil {
return "", errors.Wrap(err, "building request to generate the API token")
}
parts := strings.Split(cookie, "=")
if len(parts) != 2 {
return "", errors.Wrap(err, "building jenkins cookie")
}
jenkinsCookie := http.Cookie{Name: parts[0], Value: parts[1]}
req.AddCookie(&jenkinsCookie)
resp, err := client.Do(req)
if err != nil {
return "", errors.Wrap(err, "execute generate API token request")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "reading API token from response body")
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("generate API token status code: %d, error: %s", resp.StatusCode, string(body))
}
type TokenData struct {
TokenName string `json:"tokenName"`
TokenUuid string `json:"tokenUuid"`
TokenValue string `json:"tokenValue"`
}
type TokenResponse struct {
Status string `json:"status"`
Data TokenData `json:"data"`
}
tokenResponse := &TokenResponse{}
if err := json.Unmarshal(body, tokenResponse); err != nil {
return "", errors.Wrap(err, "parsing the API token from response")
}
return tokenResponse.Data.TokenValue, nil
}
func (o *CommonOptions) extractJenkinsCookie(text string) string {
start := strings.Index(text, JenkinsCookieName)
if start < 0 {
return ""
}
end := -1
for i, ch := range text[start:] {
if ch == '"' {
end = start + i
break
}
}
if end < 0 {
return ""
}
return text[start:end]
}
// 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) createChromeClientWithNetLog(ctx context.Context, userDataDir string, netLogFile string) (*chromedp.CDP, error) {
options := func(m map[string]interface{}) error {
if o.Headless {
m["remote-debugging-port"] = 9222
m["no-sandbox"] = true
m["headless"] = true
}
m["user-data-dir"] = userDataDir
m["log-net-log"] = netLogFile
m["net-log-capture-mode"] = "IncludeCookiesAndCredentials"
m["v"] = 1
return nil
}
logger := func(string, ...interface{}) {
return
}
return chromedp.New(ctx,
chromedp.WithRunnerOptions(runner.CommandLineOption(options)),
chromedp.WithLog(logger))
}
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() (func(string, ...interface{}), error) {
var logger func(string, ...interface{})
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
}