forked from mealal/vault-atlas-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atlasAPI.go
246 lines (225 loc) · 7.43 KB
/
atlasAPI.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
package atlas
import (
"bytes"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"strings"
)
// Used source code from https://github.com/desteves/mongodb-atlas-service-broker/
// const
const (
atlasHost = "https://cloud.mongodb.com"
atlasURI = "/api/atlas/v1.0"
atlasTypeName = "atlas"
)
// Roles --
type Roles struct {
CollectionName string `json:"collectionName,omitempty"`
DatabaseName string `json:"databaseName"`
RoleName string `json:"roleName"`
}
// BindRequest struct - Bind Settings
type bindRequest struct {
DatabaseName string `json:"databaseName"`
Password string `json:"password"`
Roles []Roles `json:"roles"`
Username string `json:"username"`
DeleteAfterDate string `json:"deleteAfterDate,omitempty"`
GroupID string `json:"groupId"`
}
type response struct {
DatabaseName string `json:"databaseName,omitempty"`
DeleteAfterDate string `json:"deleteAfterDate,omitempty"`
GroupID string `json:"groupId,omitempty"`
Roles []Roles `json:"roles,omitempty"`
Username string `json:"username,omitempty"`
Error int `json:"error,omitempty"`
ErrorCode string `json:"errorCode,omitempty"`
ErrorText string `json:"detail,omitempty"`
ErrorReason string `json:"reason,omitempty"`
}
// Does the digest handshake and assembles the actuall http call to make
func setupRequest(apiID string, apiKey string, argMethod string, argURI string, argPostBody []byte) (*http.Request, error) {
uri := atlasURI + argURI
url := atlasHost + uri
emptyRequest := http.Request{}
req, err := http.NewRequest(argMethod, url, nil)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("Error - setupRequest - Failed http response. Resp: %+v, Err: %+v", resp, err)
return &emptyRequest, err
}
defer resp.Body.Close()
digestParts := digestParts(resp)
digestParts["uri"] = uri
digestParts["method"] = argMethod
username := apiID
if len(username) == 0 {
err := fmt.Errorf("apiID variable not set")
log.Printf("Error - setupRequest. Err: %+v", err)
return &emptyRequest, err
}
password := apiKey
if len(password) == 0 {
err := fmt.Errorf("apiKey variable not set")
log.Printf("Error - setupRequest. Err: %+v", err)
return &emptyRequest, err
}
digestParts["username"] = username
digestParts["password"] = password
if argPostBody == nil {
req, err = http.NewRequest(argMethod, url, nil)
} else {
req, err = http.NewRequest(argMethod, url, bytes.NewBuffer(argPostBody))
}
req.Header.Set("Authorization", getDigestAuthrization(digestParts))
req.Header.Set("Content-Type", "application/json")
return req, nil
}
func doPOST(apiID string, apiKey string, argURI string, argPostBody []byte) ([]byte, error) {
req, err := setupRequest(apiID, apiKey, http.MethodPost, argURI, argPostBody)
if err != nil {
log.Printf("Error - DoPOST - Failed setupRequest call. Req: %+v, Err: %+v", req, err)
return []byte{}, err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("Error - DoPOST - Failed http response. Resp: %+v, Err: %+v", resp, err)
return []byte{}, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Error - DoPOST - Failed parsing body response. Data: %+v, Err: %+v", data, err)
return []byte{}, err
}
return data, nil
}
func doDELETE(apiID string, apiKey string, argURI string) ([]byte, error) {
req, err := setupRequest(apiID, apiKey, http.MethodDelete, argURI, nil)
if err != nil {
log.Printf("Error - DoDELETE - Failed setupRequest call. Req: %+v, Err: %+v", req, err)
return []byte{}, err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("Error - DoDELETE - Failed http response. Resp: %+v, Err: %+v", resp, err)
return []byte{}, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Error - DoDELETE - Failed parsing body response. Data: %+v, Err: %+v", data, err)
return []byte{}, err
}
return data, nil
}
func createAtlasUser(groupID string, apiID string, apiKey string, username string, password string, database string, roles []Roles) error {
// https://docs.atlas.mongodb.com/reference/api/database-users-create-a-user/
if len(groupID) == 0 {
err := fmt.Errorf("groupID variable not set")
log.Printf("Error - NewUser. Err: %+v", err)
return err
}
uri := "/groups/" + groupID + "/databaseUsers"
request := bindRequest{}
request.DatabaseName = database
request.GroupID = groupID
request.Roles = roles
request.Username = username
request.Password = password
params, err := json.Marshal(request)
if err != nil {
log.Printf("Error - Bind - Failed Marshal. JSON: %+v, Err: %+v", params, err)
return err
}
body, err := doPOST(apiID, apiKey, uri, params)
if err != nil {
log.Printf("Error - NewUser - Failed doPOST call. Body: %+v, Err: %+v", body, err)
return err
}
returnObject := response{}
err = json.Unmarshal(body, &returnObject)
if err != nil {
log.Printf("Error - NewUser - Failed Unmarshal. Response: %+v, Err: %+v", returnObject, err)
return err
}
if returnObject.Error != 0 {
err = errors.New(returnObject.ErrorText)
}
return err
}
func deleteAtlasUser(groupID string, apiID string, apiKey string, username string) error {
//https://docs.atlas.mongodb.com/reference/api/database-users-delete-a-user/
//DELETE /api/atlas/v1.0/groups/{GROUP-ID}/databaseUsers/admin/{USERNAME}
if len(groupID) == 0 {
err := fmt.Errorf("groupID variable not set")
log.Printf("Error - DeleteUser. Err: %+v", err)
return err
}
uri := "/groups/" + groupID + "/databaseUsers/admin/" + username
body, err := doDELETE(apiID, apiKey, uri)
if err != nil {
log.Printf("Error - DeleteUser - Failed DoDELETE call. Err: %+v", err)
}
if len(body) != 0 {
returnObject := response{}
err = json.Unmarshal(body, &returnObject)
if err != nil {
log.Printf("Error - NewUser - Failed Unmarshal. Response: %+v, Err: %+v", returnObject, err)
return err
}
if returnObject.Error != 0 {
err = errors.New(returnObject.ErrorText)
}
}
return err
}
func digestParts(resp *http.Response) map[string]string {
result := map[string]string{}
if len(resp.Header["Www-Authenticate"]) > 0 {
wantedHeaders := []string{"nonce", "realm", "qop"}
responseHeaders := strings.Split(resp.Header["Www-Authenticate"][0], ",")
for _, r := range responseHeaders {
for _, w := range wantedHeaders {
if strings.Contains(r, w) {
result[w] = strings.Split(r, `"`)[1]
}
}
}
}
return result
}
func getMD5(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
func getCnonce() string {
b := make([]byte, 8)
io.ReadFull(rand.Reader, b)
return fmt.Sprintf("%x", b)[:16]
}
func getDigestAuthrization(digestParts map[string]string) string {
d := digestParts
ha1 := getMD5(d["username"] + ":" + d["realm"] + ":" + d["password"])
ha2 := getMD5(d["method"] + ":" + d["uri"])
nonceCount := 00000001
cnonce := getCnonce()
response := getMD5(fmt.Sprintf("%s:%s:%v:%s:%s:%s", ha1, d["nonce"], nonceCount, cnonce, d["qop"], ha2))
authorization := fmt.Sprintf(`Digest username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc="%v", qop="%s", response="%s"`,
d["username"], d["realm"], d["nonce"], d["uri"], cnonce, nonceCount, d["qop"], response)
return authorization
}