-
Notifications
You must be signed in to change notification settings - Fork 787
/
create_jenkins_token.go
392 lines (358 loc) · 12 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
package cmd
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/blang/semver"
"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
BearerToken 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 REST to generate the API token (by passing username and password)")
cmd.Flags().BoolVarP(&options.UseBrowser, "browser", "", false, "Use REST calls 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.KubeClientAndNamespace()
if err != nil {
return fmt.Errorf("error connecting to Kubernetes cluster: %v", err)
}
authConfigSvc, err := o.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.BearerToken != "" {
userAuth.BearerToken = o.BearerToken
}
if o.Password != "" {
userAuth.Password = o.Password
}
if userAuth.IsInvalid() && o.Password != "" && o.UseBrowser {
err := o.getAPITokenFromREST(server.URL, userAuth)
if err != nil {
return err
}
}
if userAuth.IsInvalid() {
f := func(username string) error {
jenkins.PrintGetTokenFromURL(o.Out, jenkins.JenkinsTokenURL(server.URL))
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 := kubeClient.CoreV1().Secrets(o.currentNamespace).Get(kube.SecretJenkins, metav1.GetOptions{})
if err != nil {
return err
}
s.Data[kube.JenkinsAdminApiToken] = []byte(userAuth.ApiToken)
s.Data[kube.JenkinsBearTokenField] = []byte(userAuth.BearerToken)
s.Data[kube.JenkinsAdminUserField] = []byte(userAuth.Username)
_, err = 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
}
// Uses Jenkins REST(ish) calls to obtain an API token given a username and password.
func (o *CreateJenkinsUserOptions) getAPITokenFromREST(serverURL 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)
defer cancel()
} else {
ctx, cancel = context.WithCancel(context.Background())
}
defer cancel()
log.Infoln("Generating the API token...")
decorator, err := loginLegacy(ctx, serverURL, o.Verbose, userAuth.Username, o.Password)
if err != nil {
// Might be a modern realm, which would normally support BasicHeaderRealPasswordAuthenticator.
decorator = func(req *http.Request) {
req.SetBasicAuth(userAuth.Username, o.Password)
}
err2 := verifyLogin(ctx, serverURL, o.Verbose, decorator)
if err2 != nil {
// That did not work either.
log.Warnf("Failed to log in via modern security realm: %s\n", err2)
return errors.Wrap(err, "logging in")
}
log.Infof("Logged in %s to Jenkins server at %s via modern security realm\n",
util.ColorInfo(username), util.ColorInfo(serverURL))
}
decorator = checkForCrumb(ctx, serverURL, o.Verbose, decorator)
token, err := generateNewAPIToken(ctx, serverURL, o.Verbose, decorator)
if err != nil {
return errors.Wrap(err, "generating the API token")
}
if token == "" {
return errors.New("received an empty API token")
}
userAuth.ApiToken = token
return nil
}
// Try logging in as if LegacySecurityRealm were configured. This uses the old Servlet API login cookies.
func loginLegacy(ctx context.Context, serverURL string, verbose bool, username string, password string) (func(req *http.Request), error) {
client := http.Client{
// https://stackoverflow.com/a/38150816/12916 Jenkins returns a 303, but you cannot actually follow it
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
req, err := http.NewRequest(http.MethodPost, util.UrlJoin(serverURL, fmt.Sprintf("/j_security_check?j_username=%s&j_password=%s", url.QueryEscape(username), url.QueryEscape(password))), nil)
if err != nil {
return nil, errors.Wrap(err, "building request to log in")
}
req = req.WithContext(ctx)
if verbose {
req.Write(os.Stderr)
}
resp, err := client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "execute log in")
}
defer resp.Body.Close()
cookies := resp.Cookies()
decorator := func(req *http.Request) {
for _, c := range cookies {
req.AddCookie(c)
}
}
// We get the same response even if Jenkins is actually using a modern security realm, so verify it:
err = verifyLogin(ctx, serverURL, verbose, decorator)
if err != nil {
return nil, errors.Wrap(err, "cookies did not work; bad login or not using legacy security realm")
}
log.Infof("Logged in %s to Jenkins server at %s via legacy security realm\n",
util.ColorInfo(username), util.ColorInfo(serverURL))
return decorator, nil
}
// Checks whether a purported login decorator actually seems to work.
func verifyLogin(ctx context.Context, serverURL string, verbose bool, decorator func (req *http.Request)) error {
client := http.Client{}
req, err := http.NewRequest(http.MethodGet, util.UrlJoin(serverURL, "/me/api/json?tree=id"), nil)
if err != nil {
return errors.Wrap(err, "building request to verify login")
}
req = req.WithContext(ctx)
decorator(req)
if verbose {
req.Write(os.Stderr)
}
resp, err := client.Do(req)
if err != nil {
return errors.Wrap(err, "execute verify login")
}
defer resp.Body.Close()
if verbose {
resp.Write(os.Stderr)
}
if resp.StatusCode != 200 {
return errors.New(resp.Status)
}
return nil
}
// Checks if CSRF defense is enabled, and if so, amends the decorator to include a crumb.
func checkForCrumb(ctx context.Context, serverURL string, verbose bool, decorator func (req *http.Request)) func (req *http.Request) {
client := http.Client{}
req, err := http.NewRequest(http.MethodGet, util.UrlJoin(serverURL, "/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)"), nil)
if err != nil {
log.Warnf("Failed to build request to check for crumb: %s\n", err)
return decorator
}
req = req.WithContext(ctx)
decorator(req)
if verbose {
req.Write(os.Stderr)
}
resp, err := client.Do(req)
if err != nil {
log.Warnf("Failed to execute request to check for crumb: %s\n", err)
return decorator
}
defer resp.Body.Close()
if resp.StatusCode == 404 {
log.Infof("Enable CSRF protection at: %s/configureSecurity/\n", serverURL)
return decorator
} else if resp.StatusCode != 200 {
log.Warnf("Could not find CSRF crumb: %d %s\n", resp.StatusCode, resp.Status)
return decorator
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Warnf("Failed to read crumb: %s\n", err)
return decorator
}
crumbPieces := strings.SplitN(string(body), ":", 2)
if len(crumbPieces) != 2 {
log.Warnf("Malformed crumb: %s\n", body)
return decorator
}
log.Infof("Obtained crumb\n")
return func(req *http.Request) {
decorator(req)
req.Header.Add(crumbPieces[0], crumbPieces[1])
}
}
// Actually generates a new API token.
func generateNewAPIToken(ctx context.Context, serverURL string, verbose bool, decorator func(req *http.Request)) (string, error) {
client := http.Client{}
req, err := http.NewRequest(http.MethodPost, util.UrlJoin(serverURL, fmt.Sprintf("/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken?newTokenName=%s", url.QueryEscape("jx create jenkins token"))), nil)
if err != nil {
return "", errors.Wrap(err, "building request to generate the API token")
}
req = req.WithContext(ctx)
decorator(req)
if verbose {
req.Write(os.Stderr)
}
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
}