forked from influxdata/chronograf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers.go
394 lines (347 loc) · 11.3 KB
/
users.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
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"sort"
"strconv"
"github.com/bouk/httprouter"
"github.com/influxdata/chronograf"
"github.com/influxdata/chronograf/roles"
)
type userRequest struct {
ID uint64 `json:"id,string"`
Name string `json:"name"`
Provider string `json:"provider"`
Scheme string `json:"scheme"`
SuperAdmin bool `json:"superAdmin"`
Roles []chronograf.Role `json:"roles"`
}
func (r *userRequest) ValidCreate() error {
if r.Name == "" {
return fmt.Errorf("Name required on Chronograf User request body")
}
if r.Provider == "" {
return fmt.Errorf("provider required on Chronograf User request body")
}
if r.Scheme == "" {
return fmt.Errorf("scheme required on Chronograf User request body")
}
// TODO: This Scheme value is hard-coded temporarily since we only currently
// support OAuth2. This hard-coding should be removed whenever we add
// support for other authentication schemes.
r.Scheme = "oauth2"
return r.ValidRoles()
}
func (r *userRequest) ValidUpdate() error {
if r.Roles == nil {
return fmt.Errorf("no roles to update")
}
return r.ValidRoles()
}
func (r *userRequest) ValidRoles() error {
if len(r.Roles) > 0 {
orgs := map[string]bool{}
for _, r := range r.Roles {
if r.Organization == "" {
return fmt.Errorf("no organization was provided")
}
if _, ok := orgs[r.Organization]; ok {
return fmt.Errorf("duplicate organization %q in roles", r.Organization)
}
orgs[r.Organization] = true
switch r.Name {
case roles.MemberRoleName, roles.ReaderRoleName, roles.ViewerRoleName, roles.EditorRoleName, roles.AdminRoleName, roles.WildcardRoleName:
continue
default:
return fmt.Errorf("unknown role %s, valid roles are 'member', 'reader', 'viewer', 'editor', 'admin', and '*'", r.Name)
}
}
}
return nil
}
type userResponse struct {
Links selfLinks `json:"links"`
ID uint64 `json:"id,string"`
Name string `json:"name"`
Provider string `json:"provider"`
Scheme string `json:"scheme"`
SuperAdmin bool `json:"superAdmin"`
Roles []chronograf.Role `json:"roles"`
}
func newUserResponse(u *chronograf.User, org string) *userResponse {
// This ensures that any user response with no roles returns an empty array instead of
// null when marshaled into JSON. That way, JavaScript doesn't need any guard on the
// key existing and it can simply be iterated over.
if u.Roles == nil {
u.Roles = []chronograf.Role{}
}
var selfLink string
if org != "" {
selfLink = fmt.Sprintf("/chronograf/v1/organizations/%s/users/%d", org, u.ID)
} else {
selfLink = fmt.Sprintf("/chronograf/v1/users/%d", u.ID)
}
return &userResponse{
ID: u.ID,
Name: u.Name,
Provider: u.Provider,
Scheme: u.Scheme,
Roles: u.Roles,
SuperAdmin: u.SuperAdmin,
Links: selfLinks{
Self: selfLink,
},
}
}
type usersResponse struct {
Links selfLinks `json:"links"`
Users []*userResponse `json:"users"`
}
func newUsersResponse(users []chronograf.User, org string) *usersResponse {
usersResp := make([]*userResponse, len(users))
for i, user := range users {
usersResp[i] = newUserResponse(&user, org)
}
sort.Slice(usersResp, func(i, j int) bool {
return usersResp[i].ID < usersResp[j].ID
})
var selfLink string
if org != "" {
selfLink = fmt.Sprintf("/chronograf/v1/organizations/%s/users", org)
} else {
selfLink = "/chronograf/v1/users"
}
return &usersResponse{
Users: usersResp,
Links: selfLinks{
Self: selfLink,
},
}
}
// UserID retrieves a Chronograf user with ID from store
func (s *Service) UserID(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
idStr := httprouter.GetParamFromContext(ctx, "id")
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, fmt.Sprintf("invalid user id: %s", err.Error()), s.Logger)
return
}
user, err := s.Store.Users(ctx).Get(ctx, chronograf.UserQuery{ID: &id})
if err != nil {
Error(w, http.StatusBadRequest, err.Error(), s.Logger)
return
}
orgID := httprouter.GetParamFromContext(ctx, "oid")
res := newUserResponse(user, orgID)
location(w, res.Links.Self)
encodeJSON(w, http.StatusOK, res, s.Logger)
}
// NewUser adds a new Chronograf user to store
func (s *Service) NewUser(w http.ResponseWriter, r *http.Request) {
var req userRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
invalidJSON(w, s.Logger)
return
}
if err := req.ValidCreate(); err != nil {
invalidData(w, err, s.Logger)
return
}
ctx := r.Context()
serverCtx := serverContext(ctx)
cfg, err := s.Store.Config(serverCtx).Get(serverCtx)
if err != nil {
Error(w, http.StatusInternalServerError, err.Error(), s.Logger)
return
}
roles, err := s.validRoles(serverCtx, req.Roles, []chronograf.Role{})
if err != nil {
invalidData(w, err, s.Logger)
return
}
user := &chronograf.User{
Name: req.Name,
Provider: req.Provider,
Scheme: req.Scheme,
Roles: roles,
}
if cfg.Auth.SuperAdminNewUsers {
req.SuperAdmin = true
}
if err := setSuperAdmin(ctx, req, user); err != nil {
Error(w, http.StatusUnauthorized, err.Error(), s.Logger)
return
}
res, err := s.Store.Users(ctx).Add(ctx, user)
if err != nil {
Error(w, http.StatusBadRequest, err.Error(), s.Logger)
return
}
orgID := httprouter.GetParamFromContext(ctx, "oid")
cu := newUserResponse(res, orgID)
location(w, cu.Links.Self)
encodeJSON(w, http.StatusCreated, cu, s.Logger)
}
// RemoveUser deletes a Chronograf user from store
func (s *Service) RemoveUser(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
idStr := httprouter.GetParamFromContext(ctx, "id")
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, fmt.Sprintf("invalid user id: %s", err.Error()), s.Logger)
return
}
u, err := s.Store.Users(ctx).Get(ctx, chronograf.UserQuery{ID: &id})
if err != nil {
Error(w, http.StatusNotFound, err.Error(), s.Logger)
return
}
if err := s.Store.Users(ctx).Delete(ctx, u); err != nil {
Error(w, http.StatusBadRequest, err.Error(), s.Logger)
return
}
w.WriteHeader(http.StatusNoContent)
}
// UpdateUser updates a Chronograf user in store
func (s *Service) UpdateUser(w http.ResponseWriter, r *http.Request) {
var req userRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
invalidJSON(w, s.Logger)
return
}
ctx := r.Context()
idStr := httprouter.GetParamFromContext(ctx, "id")
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, fmt.Sprintf("invalid user id: %s", err.Error()), s.Logger)
return
}
if err := req.ValidUpdate(); err != nil {
invalidData(w, err, s.Logger)
return
}
u, err := s.Store.Users(ctx).Get(ctx, chronograf.UserQuery{ID: &id})
if err != nil {
Error(w, http.StatusNotFound, err.Error(), s.Logger)
return
}
serverCtx := serverContext(ctx)
roles, err := s.validRoles(serverCtx, req.Roles, u.Roles)
if err != nil {
invalidData(w, err, s.Logger)
return
}
u.Roles = roles
// If the request contains a name, it must be the same as the
// one on the user. This is particularly useful to the front-end
// because they would like to provide the whole user object,
// including the name, provider, and scheme in update requests.
// But currently, it is not possible to change name, provider, or
// scheme via the API.
if req.Name != "" && req.Name != u.Name {
err := fmt.Errorf("cannot update Name")
invalidData(w, err, s.Logger)
return
}
if req.Provider != "" && req.Provider != u.Provider {
err := fmt.Errorf("cannot update Provider")
invalidData(w, err, s.Logger)
return
}
if req.Scheme != "" && req.Scheme != u.Scheme {
err := fmt.Errorf("cannot update Scheme")
invalidData(w, err, s.Logger)
return
}
// Don't allow SuperAdmins to modify their own SuperAdmin status.
// Allowing them to do so could result in an application where there
// are no super admins.
ctxUser, ok := hasUserContext(ctx)
if !ok {
Error(w, http.StatusInternalServerError, "failed to retrieve user from context", s.Logger)
return
}
// If the user being updated is the user making the request and they are
// changing their SuperAdmin status, return an unauthorized error
if ctxUser.ID == u.ID && u.SuperAdmin && !req.SuperAdmin {
Error(w, http.StatusUnauthorized, "user cannot modify their own SuperAdmin status", s.Logger)
return
}
if err := setSuperAdmin(ctx, req, u); err != nil {
Error(w, http.StatusUnauthorized, err.Error(), s.Logger)
return
}
err = s.Store.Users(ctx).Update(ctx, u)
if err != nil {
Error(w, http.StatusBadRequest, err.Error(), s.Logger)
return
}
orgID := httprouter.GetParamFromContext(ctx, "oid")
cu := newUserResponse(u, orgID)
location(w, cu.Links.Self)
encodeJSON(w, http.StatusOK, cu, s.Logger)
}
// Users retrieves all Chronograf users from store
func (s *Service) Users(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
users, err := s.Store.Users(ctx).All(ctx)
if err != nil {
Error(w, http.StatusBadRequest, err.Error(), s.Logger)
return
}
orgID := httprouter.GetParamFromContext(ctx, "oid")
res := newUsersResponse(users, orgID)
encodeJSON(w, http.StatusOK, res, s.Logger)
}
func setSuperAdmin(ctx context.Context, req userRequest, user *chronograf.User) error {
// At a high level, this function checks the following
// 1. Is the user making the request a SuperAdmin.
// If they are, allow them to make whatever changes they please.
//
// 2. Is the user making the request trying to change the SuperAdmin
// status. If so, return an error.
//
// 3. If none of the above are the case, let the user make whichever
// changes were requested.
// Only allow users to set SuperAdmin if they have the superadmin context
// TODO(desa): Refactor this https://github.com/influxdata/chronograf/issues/2207
if isSuperAdmin := hasSuperAdminContext(ctx); isSuperAdmin {
user.SuperAdmin = req.SuperAdmin
} else if !isSuperAdmin && (user.SuperAdmin != req.SuperAdmin) {
// If req.SuperAdmin has been set, and the request was not made with the SuperAdmin
// context, return error
return fmt.Errorf("user does not have authorization required to set SuperAdmin status, see https://github.com/influxdata/chronograf/issues/2601 for more information")
}
return nil
}
func (s *Service) validRoles(ctx context.Context, rs []chronograf.Role, existing []chronograf.Role) ([]chronograf.Role, error) {
// validates that newly added roles reference existing organization
// and remove existing roles that reference organization that does not exist
// https://github.com/influxdata/chronograf/pull/5722
validRoles := make([]chronograf.Role, 0, len(existing))
existingOrgs := make(map[string]struct{})
for _, role := range existing {
existingOrgs[role.Organization] = struct{}{}
}
for i, role := range rs {
_, orgAlreadyUsed := existingOrgs[role.Organization]
org, err := s.Store.Organizations(ctx).Get(ctx, chronograf.OrganizationQuery{ID: &role.Organization})
if err != nil && !orgAlreadyUsed {
return nil, err
}
if role.Name == roles.WildcardRoleName {
if err != nil {
return nil, err
}
role.Name = org.DefaultRole
rs[i] = role
}
if err != chronograf.ErrOrganizationNotFound {
validRoles = append(validRoles, role)
}
}
return validRoles, nil
}