/
3scale_api.go
376 lines (304 loc) · 9.75 KB
/
3scale_api.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
package resources
import (
"errors"
"fmt"
"net/http"
url2 "net/url"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
)
const (
ThreeScalePingUrl = "%v/p/admin/applications"
ThreeScaleProductCreateUrl = "%v/apiconfig/services"
ThreeScaleProductDeleteUrl = "%v/apiconfig/services/%v"
ThreeScaleClient = "3scale"
ThreeScaleUserInviteUrl = "%v/p/admin/account/invitations/"
)
type ThreeScaleAPIClient interface {
Ping() error
LoginOpenshift(masterUrl, username, password, namespacePrefix string) error
Login3Scale(clientSecret string) error
CreateProduct(name string) (string, error)
DeleteProduct(href string) error
SendUserInvitation(name string) (string, error)
SetUserAsAdmin(username string, email string, userID string) error
GetUserId(username string) (string, error)
VerifyUserIsAdmin(userID string) (bool, error)
}
type ThreeScaleAPIClientImpl struct {
host string
client *http.Client
kubeClient k8sclient.Client
token string
keycloakHost string
redirectUrl string
logger SimpleLogger
}
func NewThreeScaleAPIClient(host, keycloakHost, redirectUrl string, client *http.Client, kubeClient k8sclient.Client, logger SimpleLogger) ThreeScaleAPIClient {
return &ThreeScaleAPIClientImpl{
host: host,
client: client,
kubeClient: kubeClient,
keycloakHost: keycloakHost,
redirectUrl: redirectUrl,
logger: logger,
}
}
// Request a csrf token to be used in a form post request by sending
// a get request to the form url first
func requestCRSFToken(c *http.Client, formUrl string) (string, error) {
resp, err := c.Get(formUrl)
if err != nil {
return "", err
}
defer resp.Body.Close()
doc, err := ParseHtmlResponse(resp)
if err != nil {
return "", err
}
selector := doc.Find("meta[name='csrf-token']")
if selector.Length() == 0 {
return "", fmt.Errorf("no csrf token found in: %v", doc.Text())
}
// Get the csrf token from the form to use it in the post
csrf, _ := selector.Attr("content")
return csrf, nil
}
func (r *ThreeScaleAPIClientImpl) Login3Scale(clientSecret string) error {
token, err := Auth3Scale(r.client, r.redirectUrl, r.keycloakHost, ThreeScaleClient, clientSecret)
if err != nil {
return err
}
r.token = token
return nil
}
func (r *ThreeScaleAPIClientImpl) LoginOpenshift(masterUrl, username, password, namespacePrefix string) error {
authUrl := fmt.Sprintf("%s/auth/login", masterUrl)
if err := DoAuthOpenshiftUser(authUrl, username, password, r.client, "testing-idp", r.logger); err != nil {
return err
}
openshiftClient := NewOpenshiftClient(r.client, masterUrl)
if err := OpenshiftUserReconcileCheck(openshiftClient, r.kubeClient, namespacePrefix, username); err != nil {
return err
}
return nil
}
// Call the applications endpoint of 3Scale to make sure it is available
// and the user has permissions to retrieve the list of applications
func (r *ThreeScaleAPIClientImpl) Ping() error {
url := fmt.Sprintf(ThreeScalePingUrl, r.host)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := r.client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("expected 200 but got %v", resp.StatusCode)
}
return nil
}
// Delete a 3Scale product by id
func (r *ThreeScaleAPIClientImpl) DeleteProduct(id string) error {
url := fmt.Sprintf(ThreeScaleProductDeleteUrl, r.host, id)
formUrl := fmt.Sprintf("%v/apiconfig/services/%v/edit", r.host, id)
csrf, err := requestCRSFToken(r.client, formUrl)
if err != nil {
return err
}
formValues := url2.Values{
"authenticity_token": []string{csrf},
"_method": []string{"delete"},
}
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(formValues.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", r.token))
resp, err := r.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("expected 200 but got %v", resp.StatusCode)
}
return nil
}
// Create a 3Scale product
func (r *ThreeScaleAPIClientImpl) CreateProduct(name string) (string, error) {
url := fmt.Sprintf(ThreeScaleProductCreateUrl, r.host)
formUrl := fmt.Sprintf("%v/apiconfig/services/new", r.host)
// First try to get the CRSF token by requesting the form
csrf, err := requestCRSFToken(r.client, formUrl)
if err != nil {
return "", err
}
formValues := url2.Values{
"service[name]": []string{name},
"service[system_name]": []string{fmt.Sprintf("%v-system", name)},
"service[description]": []string{fmt.Sprintf("%v dummy service", name)},
"commit": []string{"Create+Product"},
"authenticity_token": []string{csrf},
}
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(formValues.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", r.token))
resp, err := r.client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("expected 200 but got %v", resp.StatusCode)
}
// Parse the html to get a link back to the created service
doc, err := ParseHtmlResponse(resp)
if err != nil {
return "", err
}
// Get the div containing a link that contains the product ID
selector := doc.Find("a.pf-c-button")
if selector.Length() == 0 {
return "", errors.New("unable to retrieve service id")
}
// Parse the href from the div
href, _ := selector.Attr("href")
if !strings.Contains(href, "/") {
return "", fmt.Errorf("invalid href format %v", href)
}
// Parse the product ID from the href
id := strings.Split(href, "/")
return id[len(id)-2], nil
}
// Create a 3Scale user invite
func (r *ThreeScaleAPIClientImpl) SendUserInvitation(name string) (string, error) {
url := fmt.Sprintf(ThreeScaleUserInviteUrl, r.host)
formUrl := fmt.Sprintf("%v/p/admin/account/invitations/new", r.host)
// First try to get the CRSF token by requesting the form
csrf, err := requestCRSFToken(r.client, formUrl)
if err != nil {
return "", err
}
formValues := url2.Values{
"invitation[email]": []string{name},
//"service[system_name]": []string{fmt.Sprintf("%v-system", name)},
//"service[description]": []string{fmt.Sprintf("%v dummy service", name)},
"commit": []string{"Send"},
"authenticity_token": []string{csrf},
}
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(formValues.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", r.token))
resp, err := r.client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("expected 200 but got %v", resp.StatusCode)
}
return "Completed", nil
}
func (r *ThreeScaleAPIClientImpl) SetUserAsAdmin(username string, email string, userID string) error {
url := fmt.Sprintf("%v/p/admin/account/users/%v", r.host, userID)
formUrl := fmt.Sprintf("%v/p/admin/account/users/%v/edit", r.host, userID)
// First try to get the CRSF token by requesting the form
csrf, err := requestCRSFToken(r.client, formUrl)
if err != nil {
return err
}
formValues := url2.Values{
"user[username]": []string{username},
"user[email]": []string{email},
"user[role]": []string{"admin"},
"user[password]": []string{},
"user[password_confirmation]": []string{},
"commit": []string{"Update+User"},
"authenticity_token": []string{csrf},
"_method": []string{"patch"},
}
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(formValues.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", r.token))
resp, err := r.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("expected 200 but got %v", resp.StatusCode)
}
return nil
}
func (r *ThreeScaleAPIClientImpl) GetUserId(username string) (string, error) {
url := fmt.Sprintf("%v/p/admin/account/users", r.host)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", r.token))
resp, err := r.client.Do(req)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("expected 200 but got %v", resp.StatusCode)
}
doc, err := ParseHtmlResponse(resp)
if err != nil {
return "", err
}
links := doc.Find("a[title='Edit']")
link := ""
links.Each(func(index int, s *goquery.Selection) {
if s.Contents().Text() == username {
link, _ = s.Attr("href")
return
}
})
if link == "" {
return "", fmt.Errorf("failed to retrieve link to edit user")
}
userId := ""
s := strings.Split(link, "/")
for _, val := range s {
if _, err := strconv.Atoi(val); err == nil {
userId = val
break
}
}
return userId, nil
}
func (r *ThreeScaleAPIClientImpl) VerifyUserIsAdmin(userID string) (bool, error) {
formUrl := fmt.Sprintf("%v/p/admin/account/users/%v/edit", r.host, userID)
resp, err := r.client.Get(formUrl)
if err != nil {
return false, err
}
defer resp.Body.Close()
doc, err := ParseHtmlResponse(resp)
if err != nil {
return false, err
}
selector := doc.Find("input[id='user_role_admin']")
_, exists := selector.Attr("checked")
if exists {
return true, nil
}
return false, nil
}