-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
626 lines (558 loc) · 16.8 KB
/
user.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
// Copyright 2018 Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"errors"
"fmt"
"net/http"
"regexp"
"strconv"
"github.com/goharbor/harbor/src/common"
"github.com/goharbor/harbor/src/common/dao"
"github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/rbac"
"github.com/goharbor/harbor/src/common/rbac/project"
"github.com/goharbor/harbor/src/common/utils"
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/core/config"
"github.com/goharbor/harbor/src/core/filter"
)
// UserAPI handles request to /api/users/{}
type UserAPI struct {
BaseController
currentUserID int
userID int
SelfRegistration bool
IsAdmin bool
AuthMode string
secretKey string
}
type passwordReq struct {
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
}
type userSearch struct {
UserID int `json:"user_id"`
Username string `json:"username"`
}
type secretResp struct {
Secret string `json:"secret"`
}
// Prepare validates the URL and parms
func (ua *UserAPI) Prepare() {
ua.BaseController.Prepare()
mode, err := config.AuthMode()
if err != nil {
log.Errorf("failed to get auth mode: %v", err)
ua.SendInternalServerError(errors.New(""))
return
}
ua.AuthMode = mode
if mode == common.OIDCAuth {
key, err := config.SecretKey()
if err != nil {
log.Errorf("failed to get secret key: %v", err)
ua.SendInternalServerError(fmt.Errorf("failed to get secret key: %v", err))
return
}
ua.secretKey = key
}
self, err := config.SelfRegistration()
if err != nil {
log.Errorf("failed to get self registration: %v", err)
ua.SendInternalServerError(errors.New(""))
return
}
ua.SelfRegistration = self
if !ua.SecurityCtx.IsAuthenticated() {
if ua.Ctx.Input.IsPost() {
return
}
ua.SendUnAuthorizedError(errors.New("UnAuthorize"))
return
}
user, err := dao.GetUser(models.User{
Username: ua.SecurityCtx.GetUsername(),
})
if err != nil {
ua.SendInternalServerError(fmt.Errorf("failed to get user %s: %v",
ua.SecurityCtx.GetUsername(), err))
return
}
if user == nil {
log.Errorf("User with username %s does not exist in DB.", ua.SecurityCtx.GetUsername())
ua.SendInternalServerError(fmt.Errorf("user %s does not exist in DB", ua.SecurityCtx.GetUsername()))
return
}
ua.currentUserID = user.UserID
id := ua.Ctx.Input.Param(":id")
if id == "current" {
ua.userID = ua.currentUserID
} else if len(id) > 0 {
var err error
ua.userID, err = strconv.Atoi(id)
if err != nil {
log.Errorf("Invalid user id, error: %v", err)
ua.SendBadRequestError(errors.New("invalid user Id"))
return
}
userQuery := models.User{UserID: ua.userID}
u, err := dao.GetUser(userQuery)
if err != nil {
log.Errorf("Error occurred in GetUser, error: %v", err)
ua.SendInternalServerError(errors.New("internal error"))
return
}
if u == nil {
log.Errorf("User with Id: %d does not exist", ua.userID)
ua.SendNotFoundError(errors.New(""))
return
}
}
ua.IsAdmin = ua.SecurityCtx.IsSysAdmin()
}
// Get ...
func (ua *UserAPI) Get() {
if ua.userID == ua.currentUserID || ua.IsAdmin {
userQuery := models.User{UserID: ua.userID}
u, err := dao.GetUser(userQuery)
if err != nil {
log.Errorf("Error occurred in GetUser, error: %v", err)
ua.SendInternalServerError(err)
return
}
u.Password = ""
if ua.userID == ua.currentUserID {
u.HasAdminRole = ua.SecurityCtx.IsSysAdmin()
}
if ua.AuthMode == common.OIDCAuth {
o, err := ua.getOIDCUserInfo()
if err != nil {
ua.SendInternalServerError(err)
return
}
u.OIDCUserMeta = o
}
ua.Data["json"] = u
ua.ServeJSON()
return
}
log.Errorf("Current user, id: %d does not have admin role, can not view other user's detail", ua.currentUserID)
ua.SendForbiddenError(errors.New("user does not have admin role"))
return
}
// List ...
func (ua *UserAPI) List() {
if !ua.IsAdmin {
log.Errorf("Current user, id: %d does not have admin role, can not list users", ua.currentUserID)
ua.SendForbiddenError(errors.New("user does not have admin role"))
return
}
page, size, err := ua.GetPaginationParams()
if err != nil {
ua.SendBadRequestError(err)
return
}
query := &models.UserQuery{
Username: ua.GetString("username"),
Email: ua.GetString("email"),
Pagination: &models.Pagination{
Page: page,
Size: size,
},
}
total, err := dao.GetTotalOfUsers(query)
if err != nil {
ua.SendInternalServerError(fmt.Errorf("failed to get total of users: %v", err))
return
}
users, err := dao.ListUsers(query)
if err != nil {
ua.SendInternalServerError(fmt.Errorf("failed to get users: %v", err))
return
}
for i := range users {
user := &users[i]
user.Password = ""
}
ua.SetPaginationHeader(total, page, size)
ua.Data["json"] = users
ua.ServeJSON()
}
// Search ...
func (ua *UserAPI) Search() {
page, size, err := ua.GetPaginationParams()
if err != nil {
ua.SendBadRequestError(err)
return
}
query := &models.UserQuery{
Username: ua.GetString("username"),
Pagination: &models.Pagination{
Page: page,
Size: size,
},
}
if len(query.Username) == 0 {
ua.SendBadRequestError(errors.New("username is required"))
return
}
total, err := dao.GetTotalOfUsers(query)
if err != nil {
ua.SendInternalServerError(fmt.Errorf("failed to get total of users: %v", err))
return
}
users, err := dao.ListUsers(query)
if err != nil {
ua.SendInternalServerError(fmt.Errorf("failed to get users: %v", err))
return
}
var userSearches []userSearch
for _, user := range users {
userSearches = append(userSearches, userSearch{UserID: user.UserID, Username: user.Username})
}
ua.SetPaginationHeader(total, page, size)
ua.Data["json"] = userSearches
ua.ServeJSON()
}
// Put ...
func (ua *UserAPI) Put() {
if !ua.modifiable() {
ua.SendForbiddenError(fmt.Errorf("User with ID %d cannot be modified", ua.userID))
return
}
user := models.User{}
if err := ua.DecodeJSONReq(&user); err != nil {
ua.SendBadRequestError(err)
return
}
user.UserID = ua.userID
err := commonValidate(user)
if err != nil {
log.Warningf("Bad request in change user profile: %v", err)
ua.SendBadRequestError(fmt.Errorf("change user profile error:" + err.Error()))
return
}
userQuery := models.User{UserID: ua.userID}
u, err := dao.GetUser(userQuery)
if err != nil {
log.Errorf("Error occurred in GetUser, error: %v", err)
ua.SendInternalServerError(errors.New("internal error"))
return
}
if u == nil {
log.Errorf("User with Id: %d does not exist", ua.userID)
ua.SendNotFoundError(errors.New(""))
return
}
if u.Email != user.Email {
emailExist, err := dao.UserExists(user, "email")
if err != nil {
log.Errorf("Error occurred in change user profile: %v", err)
ua.SendInternalServerError(errors.New("internal error"))
return
}
if emailExist {
log.Warning("email has already been used!")
ua.SendConflictError(errors.New("email has already been used"))
return
}
}
if err := dao.ChangeUserProfile(user); err != nil {
log.Errorf("Failed to update user profile, error: %v", err)
ua.SendInternalServerError(err)
return
}
}
// Post ...
func (ua *UserAPI) Post() {
if !(ua.AuthMode == common.DBAuth) {
ua.SendForbiddenError(errors.New(""))
return
}
if !(ua.SelfRegistration || ua.IsAdmin) {
log.Warning("Registration can only be used by admin role user when self-registration is off.")
ua.SendForbiddenError(errors.New(""))
return
}
if !ua.IsAdmin && !filter.ReqCarriesSession(ua.Ctx.Request) {
ua.SendForbiddenError(errors.New("self-registration cannot be triggered via API"))
return
}
user := models.User{}
if err := ua.DecodeJSONReq(&user); err != nil {
ua.SendBadRequestError(err)
return
}
err := validate(user)
if err != nil {
log.Warningf("Bad request in Register: %v", err)
ua.RenderError(http.StatusBadRequest, "register error:"+err.Error())
return
}
if !ua.IsAdmin && user.HasAdminRole {
msg := "Non-admin cannot create an admin user."
log.Errorf(msg)
ua.SendForbiddenError(errors.New(msg))
return
}
userExist, err := dao.UserExists(user, "username")
if err != nil {
log.Errorf("Error occurred in Register: %v", err)
ua.SendInternalServerError(errors.New("internal error"))
return
}
if userExist {
log.Warning("username has already been used!")
ua.SendConflictError(errors.New("username has already been used"))
return
}
emailExist, err := dao.UserExists(user, "email")
if err != nil {
log.Errorf("Error occurred in change user profile: %v", err)
ua.SendInternalServerError(errors.New("internal error"))
return
}
if emailExist {
log.Warning("email has already been used!")
ua.SendConflictError(errors.New("email has already been used"))
return
}
userID, err := dao.Register(user)
if err != nil {
log.Errorf("Error occurred in Register: %v", err)
ua.SendInternalServerError(errors.New("internal error"))
return
}
ua.Redirect(http.StatusCreated, strconv.FormatInt(userID, 10))
}
// Delete ...
func (ua *UserAPI) Delete() {
if !ua.IsAdmin || ua.AuthMode != common.DBAuth || ua.userID == 1 || ua.currentUserID == ua.userID {
ua.SendForbiddenError(fmt.Errorf("User with ID: %d cannot be removed, auth mode: %s, current user ID: %d", ua.userID, ua.AuthMode, ua.currentUserID))
return
}
var err error
err = dao.DeleteUser(ua.userID)
if err != nil {
log.Errorf("Failed to delete data from database, error: %v", err)
ua.SendInternalServerError(errors.New("failed to delete User"))
return
}
}
// ChangePassword handles PUT to /api/users/{}/password
func (ua *UserAPI) ChangePassword() {
if !ua.modifiable() {
ua.SendForbiddenError(fmt.Errorf("User with ID: %d is not modifiable", ua.userID))
return
}
changePwdOfOwn := ua.userID == ua.currentUserID
var req passwordReq
if err := ua.DecodeJSONReq(&req); err != nil {
ua.SendBadRequestError(err)
return
}
if changePwdOfOwn && len(req.OldPassword) == 0 {
ua.SendBadRequestError(errors.New("empty old_password"))
return
}
if len(req.NewPassword) == 0 {
ua.SendBadRequestError(errors.New("empty new_password"))
return
}
user, err := dao.GetUser(models.User{UserID: ua.userID})
if err != nil {
ua.SendInternalServerError(fmt.Errorf("failed to get user %d: %v", ua.userID, err))
return
}
if user == nil {
ua.SendNotFoundError(fmt.Errorf("user %d not found", ua.userID))
return
}
if changePwdOfOwn {
if user.Password != utils.Encrypt(req.OldPassword, user.Salt) {
log.Info("incorrect old_password")
ua.SendForbiddenError(errors.New("incorrect old_password"))
return
}
}
if user.Password == utils.Encrypt(req.NewPassword, user.Salt) {
ua.SendBadRequestError(errors.New("the new password can not be same with the old one"))
return
}
updatedUser := models.User{
UserID: ua.userID,
Password: req.NewPassword,
}
if err = dao.ChangeUserPassword(updatedUser); err != nil {
ua.SendInternalServerError(fmt.Errorf("failed to change password of user %d: %v", ua.userID, err))
return
}
}
// ToggleUserAdminRole handles PUT api/users/{}/sysadmin
func (ua *UserAPI) ToggleUserAdminRole() {
if !ua.IsAdmin {
log.Warningf("current user, id: %d does not have admin role, can not update other user's role", ua.currentUserID)
ua.RenderError(http.StatusForbidden, "User does not have admin role")
return
}
userQuery := models.User{UserID: ua.userID}
if err := ua.DecodeJSONReq(&userQuery); err != nil {
ua.SendBadRequestError(err)
return
}
if err := dao.ToggleUserAdminRole(userQuery.UserID, userQuery.HasAdminRole); err != nil {
log.Errorf("Error occurred in ToggleUserAdminRole: %v", err)
ua.SendInternalServerError(errors.New("internal error"))
return
}
}
// ListUserPermissions handles GET to /api/users/{}/permissions
func (ua *UserAPI) ListUserPermissions() {
if ua.userID != ua.currentUserID {
log.Warningf("Current user, id: %d can not view other user's permissions", ua.currentUserID)
ua.RenderError(http.StatusForbidden, "User does not have permission")
return
}
relative := ua.Ctx.Input.Query("relative") == "true"
scope := rbac.Resource(ua.Ctx.Input.Query("scope"))
policies := []*rbac.Policy{}
namespace, err := scope.GetNamespace()
if err == nil {
switch namespace.Kind() {
case "project":
for _, policy := range project.GetAllPolicies(namespace) {
if ua.SecurityCtx.Can(policy.Action, policy.Resource) {
policies = append(policies, policy)
}
}
}
}
results := []map[string]string{}
for _, policy := range policies {
var resource rbac.Resource
// for resource `/project/1/repository` if `relative` is `true` then the resource in response will be `repository`
if relative {
relativeResource, err := policy.Resource.RelativeTo(scope)
if err != nil {
continue
}
resource = relativeResource
} else {
resource = policy.Resource
}
results = append(results, map[string]string{
"resource": resource.String(),
"action": policy.Action.String(),
})
}
ua.Data["json"] = results
ua.ServeJSON()
return
}
// GenCLISecret generates a new CLI secret and replace the old one
func (ua *UserAPI) GenCLISecret() {
if ua.AuthMode != common.OIDCAuth {
ua.SendPreconditionFailedError(errors.New("the auth mode has to be oidc auth"))
return
}
if ua.userID != ua.currentUserID && !ua.IsAdmin {
ua.SendForbiddenError(errors.New(""))
return
}
oidcData, err := dao.GetOIDCUserByUserID(ua.userID)
if err != nil {
log.Errorf("Failed to get OIDC User meta for user, id: %d, error: %v", ua.userID, err)
ua.SendInternalServerError(errors.New("failed to get OIDC meta data for user"))
return
}
if oidcData == nil {
log.Errorf("User is not onboarded via OIDC AuthN, user id: %d", ua.userID)
ua.SendPreconditionFailedError(errors.New("user is not onboarded via OIDC AuthN"))
return
}
sec := utils.GenerateRandomString()
encSec, err := utils.ReversibleEncrypt(sec, ua.secretKey)
if err != nil {
log.Errorf("Failed to encrypt secret, error: %v", err)
ua.SendInternalServerError(errors.New("failed to encrypt secret"))
return
}
oidcData.Secret = encSec
err = dao.UpdateOIDCUserSecret(oidcData)
if err != nil {
log.Errorf("Failed to update secret in DB, error: %v", err)
ua.SendInternalServerError(errors.New("failed to update secret in DB"))
return
}
ua.Data["json"] = secretResp{sec}
ua.ServeJSON()
}
func (ua *UserAPI) getOIDCUserInfo() (*models.OIDCUser, error) {
o, err := dao.GetOIDCUserByUserID(ua.userID)
if err != nil || o == nil {
return nil, err
}
if len(o.Secret) > 0 {
p, err := utils.ReversibleDecrypt(o.Secret, ua.secretKey)
if err != nil {
return nil, err
}
o.PlainSecret = p
}
return o, nil
}
// modifiable returns whether the modify is allowed based on current auth mode and context
func (ua *UserAPI) modifiable() bool {
if ua.AuthMode == common.DBAuth {
// When the auth mode is local DB, admin can modify anyone, non-admin can modify himself.
return ua.IsAdmin || ua.userID == ua.currentUserID
}
// When the auth mode is external IDM backend, only the super user can modify himself,
// because he's the only one whose information is stored in local DB.
return ua.userID == 1 && ua.userID == ua.currentUserID
}
// validate only validate when user register
func validate(user models.User) error {
if utils.IsIllegalLength(user.Username, 1, 255) {
return fmt.Errorf("username with illegal length")
}
if utils.IsContainIllegalChar(user.Username, []string{",", "~", "#", "$", "%"}) {
return fmt.Errorf("username contains illegal characters")
}
if utils.IsIllegalLength(user.Password, 8, 20) {
return fmt.Errorf("password with illegal length")
}
return commonValidate(user)
}
// commonValidate validates email, realname, comment information when user register or change their profile
func commonValidate(user models.User) error {
if len(user.Email) > 0 {
if m, _ := regexp.MatchString(`^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$`, user.Email); !m {
return fmt.Errorf("email with illegal format")
}
} else {
return fmt.Errorf("Email can't be empty")
}
if utils.IsIllegalLength(user.Realname, 1, 255) {
return fmt.Errorf("realname with illegal length")
}
if utils.IsContainIllegalChar(user.Realname, []string{",", "~", "#", "$", "%"}) {
return fmt.Errorf("realname contains illegal characters")
}
if utils.IsIllegalLength(user.Comment, -1, 30) {
return fmt.Errorf("comment with illegal length")
}
return nil
}