-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.go
264 lines (236 loc) · 7.78 KB
/
actions.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
package bitbucketserver
import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
"github.com/mrjones/oauth"
"github.com/pkg/errors"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/rancher/pkg/pipeline/remote/model"
"github.com/rancher/rancher/pkg/randomtoken"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/types/apis/project.cattle.io/v3"
"github.com/rancher/types/client/project/v3"
"k8s.io/client-go/util/cert"
)
const (
actionDisable = "disable"
actionTestAndApply = "testAndApply"
actionGenerateKeys = "generateKeys"
actionRequestLogin = "requestLogin"
actionLogin = "login"
)
func (b *BsProvider) Formatter(apiContext *types.APIContext, resource *types.RawResource) {
if convert.ToBool(resource.Values["enabled"]) {
resource.AddAction(apiContext, actionDisable)
}
resource.AddAction(apiContext, actionGenerateKeys)
resource.AddAction(apiContext, actionRequestLogin)
resource.AddAction(apiContext, actionTestAndApply)
}
func (b *BsProvider) ActionHandler(actionName string, action *types.Action, request *types.APIContext) error {
if actionName == actionTestAndApply {
return b.testAndApply(request)
} else if actionName == actionDisable {
return b.DisableAction(request, b.GetName())
} else if actionName == actionGenerateKeys {
return b.generateKeys(request)
} else if actionName == actionRequestLogin {
return b.requestLogin(request)
}
return httperror.NewAPIError(httperror.ActionNotAvailable, "")
}
func (b *BsProvider) providerFormatter(apiContext *types.APIContext, resource *types.RawResource) {
resource.AddAction(apiContext, actionRequestLogin)
resource.AddAction(apiContext, actionLogin)
}
func (b *BsProvider) providerActionHandler(actionName string, action *types.Action, request *types.APIContext) error {
if actionName == actionRequestLogin {
return b.requestLogin(request)
} else if actionName == actionLogin {
return b.login(request)
}
return httperror.NewAPIError(httperror.ActionNotAvailable, "")
}
func (b *BsProvider) generateKeys(apiContext *types.APIContext) error {
ns, _ := ref.Parse(apiContext.ID)
pConfig, err := b.GetProviderConfig(ns)
if err != nil {
return err
}
storedBitbucketPipelineConfig, ok := pConfig.(*v3.BitbucketServerPipelineConfig)
if !ok {
return fmt.Errorf("Failed to get bitbucket server provider config")
}
toUpdate := storedBitbucketPipelineConfig.DeepCopy()
token, err := randomtoken.Generate()
if err != nil {
return err
}
toUpdate.ConsumerKey = token
pub, private, err := generateKeyPair()
if err != nil {
return err
}
toUpdate.PrivateKey = private
toUpdate.PublicKey = pub
if _, err = b.SourceCodeProviderConfigs.ObjectClient().Update(toUpdate.Name, toUpdate); err != nil {
return err
}
return nil
}
func generateKeyPair() (string, string, error) {
key, err := cert.NewPrivateKey()
if err != nil {
return "", "", err
}
privateKey := string(cert.EncodePrivateKeyPEM(key))
publicKeyByte, err := cert.EncodePublicKeyPEM(&key.PublicKey)
if err != nil {
return "", "", err
}
publicKey := string(publicKeyByte)
return publicKey, privateKey, nil
}
func (b *BsProvider) requestLogin(apiContext *types.APIContext) error {
input := &v3.BitbucketServerRequestLoginInput{}
if err := json.NewDecoder(apiContext.Request.Body).Decode(input); err != nil {
return httperror.NewAPIError(httperror.InvalidBodyContent,
fmt.Sprintf("Failed to parse body: %v", err))
}
ns, _ := ref.Parse(apiContext.ID)
pConfig, err := b.GetProviderConfig(ns)
if err != nil {
return err
}
storedBitbucketPipelineConfig, ok := pConfig.(*v3.BitbucketServerPipelineConfig)
if !ok {
return fmt.Errorf("Failed to get bitbucket server provider config")
}
consumerKey := storedBitbucketPipelineConfig.ConsumerKey
rsaKey := storedBitbucketPipelineConfig.PrivateKey
host := input.Hostname
tls := input.TLS
if host == "" {
host = storedBitbucketPipelineConfig.Hostname
tls = storedBitbucketPipelineConfig.TLS
}
if tls {
host = "https://" + host
} else {
host = "http://" + host
}
consumer, err := getOauthConsumer(consumerKey, rsaKey, host)
if err != nil {
return err
}
_, loginURL, err := consumer.GetRequestTokenAndUrl(input.RedirectURL)
if err != nil {
return err
}
data := map[string]interface{}{
"loginUrl": loginURL,
"type": "bitbucketServerRequestLoginOutput",
}
apiContext.WriteResponse(http.StatusOK, data)
return nil
}
func (b *BsProvider) testAndApply(apiContext *types.APIContext) error {
applyInput := &v3.BitbucketServerApplyInput{}
if err := json.NewDecoder(apiContext.Request.Body).Decode(applyInput); err != nil {
return httperror.NewAPIError(httperror.InvalidBodyContent,
fmt.Sprintf("Failed to parse body: %v", err))
}
projectID, _ := ref.Parse(apiContext.ID)
pConfig, err := b.GetProviderConfig(projectID)
if err != nil {
return err
}
storedBitbucketPipelineConfig, ok := pConfig.(*v3.BitbucketServerPipelineConfig)
if !ok {
return fmt.Errorf("Failed to get bitbucket server provider config")
}
toUpdate := storedBitbucketPipelineConfig.DeepCopy()
toUpdate.Hostname = applyInput.Hostname
toUpdate.TLS = applyInput.TLS
toUpdate.RedirectURL = applyInput.RedirectURL
code := fmt.Sprintf("%s:%s:%s", projectID, applyInput.OAuthToken, applyInput.OAuthVerifier)
//oauth and add user
userName := apiContext.Request.Header.Get("Impersonate-User")
sourceCodeCredential, err := b.AuthAddAccount(userName, code, toUpdate, toUpdate.ProjectName, model.BitbucketServerType)
if err != nil {
return err
}
if _, err = b.RefreshReposByCredentialAndConfig(sourceCodeCredential, toUpdate); err != nil {
return err
}
toUpdate.Enabled = true
//update bitbucket pipeline config
if _, err = b.SourceCodeProviderConfigs.ObjectClient().Update(toUpdate.Name, toUpdate); err != nil {
return err
}
apiContext.WriteResponse(http.StatusOK, nil)
return nil
}
func (b *BsProvider) login(apiContext *types.APIContext) error {
loginInput := v3.AuthUserInput{}
requestBytes, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
return err
}
if err := json.Unmarshal(requestBytes, &loginInput); err != nil {
return err
}
projectID, _ := ref.Parse(apiContext.ID)
pConfig, err := b.GetProviderConfig(projectID)
if err != nil {
return err
}
config, ok := pConfig.(*v3.BitbucketServerPipelineConfig)
if !ok {
return fmt.Errorf("Failed to get bitbucket provider config")
}
if !config.Enabled {
return errors.New("bitbucket oauth app is not configured")
}
code := fmt.Sprintf("%s:%s", projectID, loginInput.Code)
//oauth and add user
userName := apiContext.Request.Header.Get("Impersonate-User")
account, err := b.AuthAddAccount(userName, code, config, config.ProjectName, model.BitbucketServerType)
if err != nil {
return err
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, apiContext.Version, client.SourceCodeCredentialType, account.Name, &data); err != nil {
return err
}
if _, err := b.RefreshReposByCredentialAndConfig(account, config); err != nil {
return err
}
apiContext.WriteResponse(http.StatusOK, data)
return nil
}
func getOauthConsumer(consumerKey, rsaKey, hostURL string) (*oauth.Consumer, error) {
keyBytes := []byte(rsaKey)
block, _ := pem.Decode(keyBytes)
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
bitbucketOauthConsumer := oauth.NewRSAConsumer(
consumerKey,
privateKey,
oauth.ServiceProvider{
RequestTokenUrl: fmt.Sprintf("%s/plugins/servlet/oauth/request-token", hostURL),
AuthorizeTokenUrl: fmt.Sprintf("%s/plugins/servlet/oauth/authorize", hostURL),
AccessTokenUrl: fmt.Sprintf("%s/plugins/servlet/oauth/access-token", hostURL),
HttpMethod: http.MethodPost,
})
return bitbucketOauthConsumer, nil
}