forked from raystack/guardian
-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
284 lines (238 loc) · 6.39 KB
/
client.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
package grafana
import (
"bytes"
b64 "encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"github.com/go-playground/validator/v10"
"github.com/goto/guardian/pkg/tracing"
)
type GrafanaClient interface {
GetDashboards(folderId int) ([]*Dashboard, error)
GetFolders() ([]*Folder, error)
GrantDashboardAccess(resource *Dashboard, user, role string) error
RevokeDashboardAccess(resource *Dashboard, user, role string) error
}
type ClientConfig struct {
Host string `validate:"required,url" mapstructure:"host"`
Username string `validate:"required" mapstructure:"username"`
Password string `validate:"required" mapstructure:"password"`
Org string `validate:"required" mapstructure:"org"`
HTTPClient HTTPClient
}
type PermissionRequest struct {
UserID int `json:"userId,omitempty"`
TeamID int `json:"teamId,omitempty"`
Permission int `json:"permission"`
Role string `json:"role,omitempty"`
Inherited bool `json:"inherited,omitempty"`
}
type user struct {
ID int `json:"id"`
Email string `json:"email"`
}
type UpdatePermissionRequest struct {
Items []*PermissionRequest `json:"items"`
}
type client struct {
baseURL *url.URL
username string
password string
org string
httpClient HTTPClient
}
func NewClient(config *ClientConfig) (*client, error) {
if err := validator.New().Struct(config); err != nil {
return nil, err
}
httpClient := config.HTTPClient
if httpClient == nil {
httpClient = tracing.NewHttpClient("GrafanaHttpClient")
}
baseURL, err := url.Parse(config.Host)
if err != nil {
return nil, err
}
username := config.Username
password := config.Password
org := config.Org
c := &client{
baseURL: baseURL,
username: username,
password: password,
org: org,
httpClient: httpClient,
}
return c, nil
}
func (c *client) GrantDashboardAccess(resource *Dashboard, user, role string) error {
userDetails, err := c.getUser(user)
if err != nil {
return err
}
permissionCode := permissionCodes[role]
if permissionCode == 0 {
return ErrInvalidPermissionType
}
permissions, err := c.getDashboardPermissions(resource.ID)
if err != nil {
return err
}
nonInheritedPermissions := []*PermissionRequest{}
isPermissionUpdated := false
for _, permission := range permissions {
if !permission.Inherited {
p := permission
if permission.UserID == userDetails.ID {
p.Permission = permissionCode
isPermissionUpdated = true
}
nonInheritedPermissions = append(nonInheritedPermissions, p)
}
}
if !isPermissionUpdated {
nonInheritedPermissions = append(nonInheritedPermissions, &PermissionRequest{
UserID: userDetails.ID,
Permission: permissionCode,
})
}
return c.updateDashboardPermissions(resource.ID, nonInheritedPermissions)
}
func (c *client) RevokeDashboardAccess(resource *Dashboard, user, role string) error {
userDetails, err := c.getUser(user)
if err != nil {
return err
}
permissionCode := permissionCodes[role]
if permissionCode == 0 {
return ErrInvalidPermissionType
}
permissions, err := c.getDashboardPermissions(resource.ID)
if err != nil {
return err
}
nonInheritedPermissions := []*PermissionRequest{}
isPermissionFound := false
for _, permission := range permissions {
if !permission.Inherited {
p := permission
if permission.UserID == userDetails.ID && permission.Permission == permissionCode {
isPermissionFound = true
} else {
nonInheritedPermissions = append(nonInheritedPermissions, p)
}
}
}
if !isPermissionFound {
return ErrPermissionNotFound
}
return c.updateDashboardPermissions(resource.ID, nonInheritedPermissions)
}
func (c *client) base64Encode() string {
data := c.username + ":" + c.password
basicKeyEncoded := b64.StdEncoding.EncodeToString([]byte(data))
return basicKeyEncoded
}
func (c *client) newRequest(method, path string, body interface{}) (*http.Request, error) {
basicKey := c.base64Encode()
u, err := c.baseURL.Parse(path)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Basic "+basicKey)
req.Header.Set("X-Grafana-Org-Id", c.org)
return req, nil
}
func (c *client) do(req *http.Request, v interface{}) (*http.Response, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if v != nil {
err = json.NewDecoder(resp.Body).Decode(v)
}
return resp, err
}
func (c *client) GetFolders() ([]*Folder, error) {
req, err := c.newRequest(http.MethodGet, "/api/folders", nil)
if err != nil {
return nil, err
}
var folders []*Folder
if _, err := c.do(req, &folders); err != nil {
return nil, err
}
return folders, nil
}
func (c *client) GetDashboards(folderId int) ([]*Dashboard, error) {
url := fmt.Sprintf("/api/search?folderIds=%d&type=dash-db", folderId)
req, err := c.newRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
var dashboard []*Dashboard
if _, err := c.do(req, &dashboard); err != nil {
return nil, err
}
return dashboard, nil
}
func (c *client) getDashboardPermissions(id int) ([]*PermissionRequest, error) {
url := fmt.Sprintf("/api/dashboards/id/%d/permissions", id)
req, err := c.newRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
var permissions []*PermissionRequest
if _, err := c.do(req, &permissions); err != nil {
return nil, err
}
return permissions, nil
}
func (c *client) updateDashboardPermissions(id int, permissions []*PermissionRequest) error {
body := UpdatePermissionRequest{
Items: permissions,
}
url := fmt.Sprintf("/api/dashboards/id/%d/permissions", id)
req, err := c.newRequest(http.MethodPost, url, body)
if err != nil {
return err
}
_, err = c.do(req, nil)
return err
}
func (c *client) getUser(email string) (*user, error) {
url := fmt.Sprintf("/api/users/lookup?loginOrEmail=%s", email)
req, err := c.newRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
var user *user
res, err := c.do(req, &user)
if err != nil {
return nil, err
}
if res.StatusCode == http.StatusNotFound {
return nil, ErrUserNotFound
}
return user, nil
}