-
Notifications
You must be signed in to change notification settings - Fork 786
/
create_git_api_token.go
258 lines (222 loc) · 6.72 KB
/
create_git_api_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
package cmd
import (
"context"
"fmt"
"io"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/chromedp"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/nodes"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1/terminal"
"k8s.io/apimachinery/pkg/util/uuid"
)
const (
jenkinsGitCredentialsSecretKey = "credentials"
)
var (
create_git_token_long = templates.LongDesc(`
Creates a new API Token for a user on a Git Server
`)
create_git_token_example = templates.Examples(`
# Add a new API Token for a user for the local Git server
# prompting the user to find and enter the API Token
jx create git token -n local someUserName
# Add a new API Token for a user for the local Git server
# using browser automation to login to the Git server
# with the username and password to find the API Token
jx create git token -n local -p somePassword someUserName
`)
)
// CreateGitTokenOptions the command line options for the command
type CreateGitTokenOptions struct {
CreateOptions
ServerFlags ServerFlags
Username string
Password string
ApiToken string
Timeout string
}
// NewCmdCreateGitToken creates a command
func NewCmdCreateGitToken(f Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) *cobra.Command {
options := &CreateGitTokenOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
In: in,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "token [username]",
Short: "Adds a new API token for a user on a Git server",
Aliases: []string{"api-token"},
Long: create_git_token_long,
Example: create_git_token_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)")
return cmd
}
// Run implements the command
func (o *CreateGitTokenOptions) Run() error {
args := o.Args
if len(args) > 0 {
o.Username = args[0]
}
if len(args) > 1 {
o.ApiToken = args[1]
}
authConfigSvc, err := o.CreateGitAuthConfigService()
if err != nil {
return err
}
config := authConfigSvc.Config()
server, err := o.findGitServer(config, &o.ServerFlags)
if err != nil {
return err
}
err = o.ensureGitServiceCRD(server)
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
}
tokenUrl := gits.ProviderAccessTokenURL(server.Kind, server.URL, userAuth.Username)
if userAuth.IsInvalid() && o.Password != "" {
err = o.tryFindAPITokenFromBrowser(tokenUrl, userAuth)
}
if err != nil || userAuth.IsInvalid() {
f := func(username string) error {
tokenUrl := gits.ProviderAccessTokenURL(server.Kind, server.URL, username)
log.Infof("Please generate an API Token for %s server %s\n", server.Kind, server.Label())
log.Infof("Click this URL %s\n\n", util.ColorInfo(tokenUrl))
log.Infof("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.updatePipelineGitCredentialsSecret(server, userAuth)
if err != nil {
log.Warnf("Failed to update Jenkins X pipeline Git credentials secret: %v\n", err)
}
log.Infof("Created user %s API Token for Git 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 *CreateGitTokenOptions) 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()
log.Infof("Trying to generate an API token for user: %s\n", util.ColorInfo(userAuth.Username))
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
for _, node := range nodeSlice {
name := node.AttributeValue("name")
if name == "user_name" {
login = true
}
}
if login {
o.captureScreenshot(ctxt, c, "screenshot-git-login.png", "//div")
log.Infof("logging in\n")
err = c.Run(ctxt, chromedp.Tasks{
chromedp.WaitVisible("user_name", chromedp.ByID),
chromedp.SendKeys("user_name", userAuth.Username, chromedp.ByID),
chromedp.SendKeys("password", o.Password+"\n", chromedp.ByID),
})
if err != nil {
return err
}
}
o.captureScreenshot(ctxt, c, "screenshot-git-api-token.png", "//div")
log.Infoln("Generating new token")
tokenId := "jx-" + string(uuid.NewUUID())
generateNewTokenButtonSelector := "//div[normalize-space(text())='Generate New Token']"
tokenResultDivSelector := "//div[@class='ui info message']/p"
err = c.Run(ctxt, chromedp.Tasks{
chromedp.WaitVisible(generateNewTokenButtonSelector),
chromedp.Click(generateNewTokenButtonSelector),
chromedp.WaitVisible("name", chromedp.ByID),
chromedp.SendKeys("name", tokenId+"\n", chromedp.ByID),
chromedp.WaitVisible(tokenResultDivSelector),
chromedp.Nodes(tokenResultDivSelector, &nodeSlice),
})
if err != nil {
return err
}
token := ""
for _, node := range nodeSlice {
text := nodes.NodeText(node)
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
}