-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttputils.go
478 lines (408 loc) · 13.5 KB
/
httputils.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
package couchbasecapella
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/cenkalti/backoff"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-version"
"bytes"
"crypto/hmac"
"crypto/sha256"
"crypto/tls"
"io"
"strconv"
)
func CheckForOldCouchbaseCapellaVersion(hostname, username, password string) (is_old bool, err error) {
//[TODO] handle list of hostnames
resp, err := http.Get(fmt.Sprintf("http://%s:%s@%s:8091/pools", username, password, hostname))
if err != nil {
return false, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return false, err
}
type Pools struct {
ImplementationVersion string `json:"implementationVersion"`
}
data := Pools{}
err = json.Unmarshal(body, &data)
if err != nil {
return false, err
}
v, err := version.NewVersion(data.ImplementationVersion)
v650, err := version.NewVersion("6.5.0-0000")
if err != nil {
return false, err
}
if v.LessThan(v650) {
return true, nil
}
return false, nil
}
func getRootCAfromCouchbaseCapella(url string) (Base64pemCA string, err error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(body), nil
}
func createUser(hostname string, port int, adminuser, adminpassword, username, password, rbacName, roles string) (err error) {
v := url.Values{}
v.Set("password", password)
v.Add("roles", roles)
v.Add("name", rbacName)
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("http://%s:%s@%s:%d/settings/rbac/users/local/%s",
adminuser, adminpassword, hostname, port, username),
strings.NewReader(v.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("createUser returned %s", resp.Status)
}
return nil
}
func createGroup(hostname string, port int, adminuser, adminpassword, group, roles string) (err error) {
v := url.Values{}
v.Set("roles", roles)
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("http://%s:%s@%s:%d/settings/rbac/groups/%s",
adminuser, adminpassword, hostname, port, group),
strings.NewReader(v.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("createGroup returned %s", resp.Status)
}
return nil
}
func waitForBucket(t *testing.T, address, username, password, bucketName string) {
t.Logf("Waiting for bucket %s...", bucketName)
f := func() error {
return checkBucketReady(address, username, password, bucketName)
}
bo := backoff.WithMaxRetries(backoff.NewConstantBackOff(1*time.Second), 10)
err := backoff.Retry(f, bo)
if err != nil {
t.Fatalf("bucket %s installed check failed: %s", bucketName, err)
}
}
func checkBucketReady(address, username, password, bucket string) (err error) {
resp, err := http.Get(fmt.Sprintf("http://%s:%s@%s:8091/sampleBuckets", username, password, address))
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
type installed []struct {
Name string `json:"name"`
Installed bool `json:"installed"`
QuotaNeeded int64 `json:"quotaNeeded"`
}
var iresult installed
err = json.Unmarshal(body, &iresult)
if err != nil {
err := &backoff.PermanentError{
Err: fmt.Errorf("error unmarshaling JSON %s", err),
}
return err
}
bucketFound := false
for _, s := range iresult {
if s.Name == bucket {
bucketFound = true
if s.Installed == true {
return nil // Found & installed
}
}
}
err = fmt.Errorf("bucket not found")
if !bucketFound {
return backoff.Permanent(err)
}
return err
}
// Capella client utils
// --------------------
const (
headerKeyTimestamp = "Couchbase-Timestamp"
headerKeyAuthorization = "Authorization"
headerKeyContentType = "Content-Type"
)
type CapellaClient struct {
baseURL string
access string
secret string
httpClient *http.Client
logger hclog.Logger
}
func NewClient(baseURL, access, secret string) *CapellaClient {
return &CapellaClient{
baseURL: baseURL,
access: access,
secret: secret,
httpClient: http.DefaultClient,
logger: hclog.New(&hclog.LoggerOptions{}),
}
}
func (c *CapellaClient) sendRequest(method string, url string, payload string) (*http.Response, error) {
c.httpClient.Timeout = 30 * time.Second
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
//log.Printf("\n\n\t%s %s\n\tAuthorization: %s\n\t%s\n", method, url, authToken, payload)
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(payload)))
if err != nil {
fmt.Printf("client: could not create request: %s\n", err)
fmt.Printf("error=%v", err)
return nil, err
}
authToken := "Bearer " + base64.StdEncoding.EncodeToString([]byte(c.access+":"+c.secret))
req.Header.Set("Authorization", authToken)
//req.Header.Set("X-forwarded-for", clientIP)
if req.Method == http.MethodPost || req.Method == http.MethodPut {
if strings.Contains(url, "?") {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else {
req.Header.Set("Content-Type", "application/json")
}
}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
return c.httpClient.Do(req)
}
func (c *CapellaClient) Do(method, uri string, body interface{}) (*http.Response, error) {
var bb io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("failed to marshal body: %w", err)
}
bb = bytes.NewReader(b)
}
r, err := http.NewRequest(method, c.baseURL+uri, bb)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
r.Header.Add(headerKeyContentType, "application/json")
now := strconv.FormatInt(time.Now().Unix(), 10)
r.Header.Add(headerKeyTimestamp, now)
payload := strings.Join([]string{method, uri, now}, "\n")
h := hmac.New(sha256.New, []byte(c.secret))
h.Write([]byte(payload))
bearer := "Bearer " + c.access + ":" + base64.StdEncoding.EncodeToString(h.Sum(nil))
r.Header.Add(headerKeyAuthorization, bearer)
return c.httpClient.Do(r)
}
// --
func NewCapellaClient(baseUrl string, accessKey string, secretKey string) *CapellaClient {
return NewClient(baseUrl, accessKey, secretKey)
}
func Unmarshal(body io.Reader, v interface{}) error {
rb, err := ioutil.ReadAll(body)
if err != nil {
return err
}
return json.Unmarshal(rb, v)
}
// --
func CreateCapellaDbCredUser(baseUrl string, cloudAPIclustersEndPoint string, accessKey string, secretKey,
username string, password string, access string) error {
c := NewCapellaClient(baseUrl, accessKey, secretKey)
if c == nil {
return fmt.Errorf("failed in creating capella client, %v", c)
}
var accessdata map[string]interface{}
err := json.Unmarshal([]byte(access), &accessdata)
if err != nil {
return fmt.Errorf("failed during capella user creation, unmarshal of access statement error = %v, user = %v, access statement=%v",
err, username, access)
}
adata, err := json.Marshal(accessdata["access"])
if err != nil {
return fmt.Errorf("failed during capella user creation, marshal of access statement error = %v, user = %v, access statement=%v",
err, username, accessdata["access"])
}
data := fmt.Sprintf("{\"name\":\"%s\", \"password\":\"%s\", \"access\":%v}", username, password, string(adata))
ep := c.baseURL + cloudAPIclustersEndPoint + "/users"
resp, err := c.sendRequest(http.MethodPost, ep, string(data))
if resp != nil && resp.StatusCode != 201 {
defer resp.Body.Close()
// obfuscate password in the log
obfData := fmt.Sprintf("{\"name\":\"%s\", \"password\":\"[password]\", \"access\":%v}", username, string(adata))
b, err1 := io.ReadAll(resp.Body)
if err1 != nil {
return fmt.Errorf("failed during capella user creation, reading response error = %v, ep = %s, user = %v, payload=%v,client=%v",
err1, ep, username, obfData, c)
}
return fmt.Errorf("failed during capella user creation, response = %s, ep = %s, user = %v, payload = %v, access=%s, secret=%s",
string(b), ep, username, obfData, accessKey, secretKey)
}
if err != nil {
return err
}
return nil
}
func UpdateCapellaDbCredUser(baseUrl string, cloudAPIclustersEndPoint string, accessKey string, secretKey, username string, password string) (string, error) {
c := NewCapellaClient(baseUrl, accessKey, secretKey)
if username != accessKey { // db cred update
userId, err := getDbCredId(baseUrl, cloudAPIclustersEndPoint, accessKey, secretKey, username)
if userId == "" || err != nil {
return "", err
}
data := fmt.Sprintf("{\"password\":\"%s\"}", password)
ep := c.baseURL + cloudAPIclustersEndPoint + "/users/" + userId
resp, err := c.sendRequest(http.MethodPut, ep, data)
if resp != nil && resp.StatusCode != http.StatusNoContent {
return "", fmt.Errorf("failed during capella db cred user update, response = %v, ep = %s, payload=%s",
resp, ep, data)
}
if err != nil {
return "", err
}
} else { // secret key rotation
apiPathSlices := strings.Split(cloudAPIclustersEndPoint, "/")
ep := c.baseURL + "/organizations/" + apiPathSlices[2] + "/apikeys/" + username + "/rotate"
data := fmt.Sprintf("{\"secret\":\"%s\"}", password)
c.logger.Info(fmt.Sprintf("%s %s %s", http.MethodPost, ep, data))
resp, err := c.sendRequest(http.MethodPost, ep, data)
if resp != nil && resp.StatusCode != 201 {
return "", fmt.Errorf("failed during capella secret key rotate, response = %v, ep = %s",
resp, ep)
}
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed during capella user id fetch unmarshal, response = %v, ep = %s, error=%v",
resp, ep, err)
}
var content map[string]string
err = json.Unmarshal([]byte(body), &content)
if err != nil {
return "", fmt.Errorf("failed during capella user id fetch unmarshal, response = %v, ep = %s, error=%v",
resp, ep, err)
}
return content["secretKey"], nil
}
return "", nil
}
func DeleteCapellaDbCredUser(baseUrl string, cloudAPIclustersEndPoint string, accessKey string, secretKey, username string) error {
c := NewCapellaClient(baseUrl, accessKey, secretKey)
userId, err := getDbCredId(baseUrl, cloudAPIclustersEndPoint, accessKey, secretKey, username)
if userId == "" || err != nil {
return err
}
ep := c.baseURL + cloudAPIclustersEndPoint + "/users/" + userId
resp, err := c.sendRequest(http.MethodDelete, ep, "")
if resp != nil && resp.StatusCode != 204 {
return fmt.Errorf("failed during capella user deletion, response = %v, ep = %s",
resp, ep)
}
if err != nil {
return err
}
return nil
}
type Hrefs struct {
First string `json:"first"`
Last string `json:"last"`
Next string `json:"next"`
Previous string `json:"previous"`
}
type Pages struct {
// Last Last page number.
Last int `json:"last"`
// Next Next page number, it is not set on the last page.
Next *int `json:"next,omitempty"`
// Page Current page starting from 1.
Page int `json:"page"`
// PerPage How many items are displayed in the page.
PerPage int `json:"perPage"`
// Previous Previous page number, it is not set on the first page.
Previous *int `json:"previous,omitempty"`
// TotalItems Total items found by the given query.
TotalItems int `json:"totalItems"`
}
type Cursor struct {
Hrefs Hrefs `json:"hrefs"`
Pages Pages `json:"pages"`
}
type ListDbCredResponse struct {
Cursor Cursor `json: "cursor"`
Data []interface{} `json:"data"`
}
func getDbCredId(baseUrl string, cloudAPIclustersEndPoint string, accessKey string, secretKey, username string) (string, error) {
c := NewCapellaClient(baseUrl, accessKey, secretKey)
dbUserId := ""
page := 1
ep := fmt.Sprintf("%s%s/users?page=%d&perPage=100", c.baseURL, cloudAPIclustersEndPoint, page)
for page > 0 {
resp, _ := c.sendRequest(http.MethodGet, ep, "")
if resp.StatusCode != http.StatusOK {
return dbUserId, fmt.Errorf("failed during capella user id fetch, response = %v, ep = %s",
resp, ep)
} else {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return dbUserId, fmt.Errorf("failed during capella user id fetch unmarshal, response = %v, ep = %s, error=%v",
resp, ep, err)
}
var content ListDbCredResponse
err = json.Unmarshal([]byte(body), &content)
if err != nil {
return dbUserId, fmt.Errorf("failed during capella user id fetch unmarshal, response = %v, ep = %s, error=%v",
resp, ep, err)
}
d := content.Data
if d == nil {
return dbUserId, fmt.Errorf("failed during capella user id response data, response = %v, ep = %s, body=%v",
resp, ep, body)
}
for _, data := range d {
d1 := data.(map[string]interface{})
dbusername := d1["name"].(string)
if dbusername == username {
dbUserId = d1["id"].(string)
return dbUserId, nil
}
}
// next page
page = content.Cursor.Pages.Page
if page == 0 {
return dbUserId, fmt.Errorf("failed during capella user id fetch unmarshal, response = %v, ep = %s, error=%v",
resp, ep, "db user id is not found for the given username")
} else {
ep = content.Cursor.Hrefs.Next
}
}
}
return dbUserId, nil
}