forked from goharbor/harbor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
project.go
543 lines (480 loc) · 13.5 KB
/
project.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
// 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 (
"fmt"
"net/http"
"regexp"
"strconv"
"time"
"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/utils"
errutil "github.com/goharbor/harbor/src/common/utils/error"
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/core/config"
"github.com/pkg/errors"
)
type deletableResp struct {
Deletable bool `json:"deletable"`
Message string `json:"message"`
}
// ProjectAPI handles request to /api/projects/{} /api/projects/{}/logs
type ProjectAPI struct {
BaseController
project *models.Project
}
const projectNameMaxLen int = 255
const projectNameMinLen int = 2
const restrictedNameChars = `[a-z0-9]+(?:[._-][a-z0-9]+)*`
// Prepare validates the URL and the user
func (p *ProjectAPI) Prepare() {
p.BaseController.Prepare()
if len(p.GetStringFromPath(":id")) != 0 {
id, err := p.GetInt64FromPath(":id")
if err != nil || id <= 0 {
text := "invalid project ID: "
if err != nil {
text += err.Error()
} else {
text += fmt.Sprintf("%d", id)
}
p.SendBadRequestError(errors.New(text))
return
}
project, err := p.ProjectMgr.Get(id)
if err != nil {
p.ParseAndHandleError(fmt.Sprintf("failed to get project %d", id), err)
return
}
if project == nil {
p.SendNotFoundError(fmt.Errorf("project %d not found", id))
return
}
p.project = project
}
}
func (p *ProjectAPI) requireAccess(action rbac.Action, subresource ...rbac.Resource) bool {
if len(subresource) == 0 {
subresource = append(subresource, rbac.ResourceSelf)
}
return p.RequireProjectAccess(p.project.ProjectID, action, subresource...)
}
// Post ...
func (p *ProjectAPI) Post() {
if !p.SecurityCtx.IsAuthenticated() {
p.SendUnAuthorizedError(errors.New("Unauthorized"))
return
}
var onlyAdmin bool
var err error
if config.WithAdmiral() {
onlyAdmin = true
} else {
onlyAdmin, err = config.OnlyAdminCreateProject()
if err != nil {
log.Errorf("failed to determine whether only admin can create projects: %v", err)
p.SendInternalServerError(fmt.Errorf("failed to determine whether only admin can create projects: %v", err))
return
}
}
if onlyAdmin && !(p.SecurityCtx.IsSysAdmin() || p.SecurityCtx.IsSolutionUser()) {
log.Errorf("Only sys admin can create project")
p.SendForbiddenError(errors.New("Only system admin can create project"))
return
}
var pro *models.ProjectRequest
if err := p.DecodeJSONReq(&pro); err != nil {
p.SendBadRequestError(err)
return
}
err = validateProjectReq(pro)
if err != nil {
log.Errorf("Invalid project request, error: %v", err)
p.SendBadRequestError(fmt.Errorf("invalid request: %v", err))
return
}
exist, err := p.ProjectMgr.Exists(pro.Name)
if err != nil {
p.ParseAndHandleError(fmt.Sprintf("failed to check the existence of project %s",
pro.Name), err)
return
}
if exist {
p.SendConflictError(errors.New("conflict project"))
return
}
if pro.Metadata == nil {
pro.Metadata = map[string]string{}
}
// accept the "public" property to make replication work well with old versions(<=1.2.0)
if pro.Public != nil && len(pro.Metadata[models.ProMetaPublic]) == 0 {
pro.Metadata[models.ProMetaPublic] = strconv.FormatBool(*pro.Public == 1)
}
// populate public metadata as false if it isn't set
if _, ok := pro.Metadata[models.ProMetaPublic]; !ok {
pro.Metadata[models.ProMetaPublic] = strconv.FormatBool(false)
}
owner := p.SecurityCtx.GetUsername()
// set the owner as the system admin when the API being called by replication
// it's a solution to workaround the restriction of project creation API:
// only normal users can create projects
if p.SecurityCtx.IsSolutionUser() {
user, err := dao.GetUser(models.User{
UserID: 1,
})
if err != nil {
p.SendInternalServerError(fmt.Errorf("failed to get the user 1: %v", err))
return
}
owner = user.Username
}
projectID, err := p.ProjectMgr.Create(&models.Project{
Name: pro.Name,
OwnerName: owner,
Metadata: pro.Metadata,
})
if err != nil {
if err == errutil.ErrDupProject {
log.Debugf("conflict %s", pro.Name)
p.SendConflictError(fmt.Errorf("conflict %s", pro.Name))
} else {
p.ParseAndHandleError("failed to add project", err)
}
return
}
go func() {
if err = dao.AddAccessLog(
models.AccessLog{
Username: p.SecurityCtx.GetUsername(),
ProjectID: projectID,
RepoName: pro.Name + "/",
RepoTag: "N/A",
Operation: "create",
OpTime: time.Now(),
}); err != nil {
log.Errorf("failed to add access log: %v", err)
}
}()
p.Redirect(http.StatusCreated, strconv.FormatInt(projectID, 10))
}
// Head ...
func (p *ProjectAPI) Head() {
name := p.GetString("project_name")
if len(name) == 0 {
p.SendBadRequestError(errors.New("project_name is needed"))
return
}
project, err := p.ProjectMgr.Get(name)
if err != nil {
p.ParseAndHandleError(fmt.Sprintf("failed to get project %s", name), err)
return
}
if project == nil {
p.SendNotFoundError(fmt.Errorf("project %s not found", name))
return
}
}
// Get ...
func (p *ProjectAPI) Get() {
if !p.requireAccess(rbac.ActionRead) {
return
}
err := p.populateProperties(p.project)
if err != nil {
log.Errorf("populate project poroperties failed with : %+v", err)
}
p.Data["json"] = p.project
p.ServeJSON()
}
// Delete ...
func (p *ProjectAPI) Delete() {
if !p.requireAccess(rbac.ActionDelete) {
return
}
result, err := p.deletable(p.project.ProjectID)
if err != nil {
p.SendInternalServerError(fmt.Errorf(
"failed to check the deletable of project %d: %v", p.project.ProjectID, err))
return
}
if !result.Deletable {
p.SendPreconditionFailedError(errors.New(result.Message))
return
}
if err = p.ProjectMgr.Delete(p.project.ProjectID); err != nil {
p.ParseAndHandleError(fmt.Sprintf("failed to delete project %d", p.project.ProjectID), err)
return
}
go func() {
if err := dao.AddAccessLog(models.AccessLog{
Username: p.SecurityCtx.GetUsername(),
ProjectID: p.project.ProjectID,
RepoName: p.project.Name + "/",
RepoTag: "N/A",
Operation: "delete",
OpTime: time.Now(),
}); err != nil {
log.Errorf("failed to add access log: %v", err)
}
}()
}
// Deletable ...
func (p *ProjectAPI) Deletable() {
if !p.requireAccess(rbac.ActionDelete) {
return
}
result, err := p.deletable(p.project.ProjectID)
if err != nil {
p.SendInternalServerError(fmt.Errorf(
"failed to check the deletable of project %d: %v", p.project.ProjectID, err))
return
}
p.Data["json"] = result
p.ServeJSON()
}
func (p *ProjectAPI) deletable(projectID int64) (*deletableResp, error) {
count, err := dao.GetTotalOfRepositories(&models.RepositoryQuery{
ProjectIDs: []int64{projectID},
})
if err != nil {
return nil, err
}
if count > 0 {
return &deletableResp{
Deletable: false,
Message: "the project contains repositories, can not be deleted",
}, nil
}
// Check helm charts number
if config.WithChartMuseum() {
charts, err := chartController.ListCharts(p.project.Name)
if err != nil {
return nil, err
}
if len(charts) > 0 {
return &deletableResp{
Deletable: false,
Message: "the project contains helm charts, can not be deleted",
}, nil
}
}
return &deletableResp{
Deletable: true,
}, nil
}
// List ...
func (p *ProjectAPI) List() {
// query strings
page, size, err := p.GetPaginationParams()
if err != nil {
p.SendBadRequestError(err)
return
}
query := &models.ProjectQueryParam{
Name: p.GetString("name"),
Owner: p.GetString("owner"),
Pagination: &models.Pagination{
Page: page,
Size: size,
},
}
public := p.GetString("public")
if len(public) > 0 {
pub, err := strconv.ParseBool(public)
if err != nil {
p.SendBadRequestError(fmt.Errorf("invalid public: %s", public))
return
}
query.Public = &pub
}
// standalone, filter projects according to the privilleges of the user first
if !config.WithAdmiral() {
var projects []*models.Project
if !p.SecurityCtx.IsAuthenticated() {
// not login, only get public projects
pros, err := p.ProjectMgr.GetPublic()
if err != nil {
p.SendInternalServerError(fmt.Errorf("failed to get public projects: %v", err))
return
}
projects = []*models.Project{}
projects = append(projects, pros...)
} else {
if !(p.SecurityCtx.IsSysAdmin() || p.SecurityCtx.IsSolutionUser()) {
projects = []*models.Project{}
// login, but not system admin or solution user, get public projects and
// projects that the user is member of
pros, err := p.ProjectMgr.GetPublic()
if err != nil {
p.SendInternalServerError(fmt.Errorf("failed to get public projects: %v", err))
return
}
projects = append(projects, pros...)
mps, err := p.SecurityCtx.GetMyProjects()
if err != nil {
p.SendInternalServerError(fmt.Errorf("failed to list projects: %v", err))
return
}
projects = append(projects, mps...)
}
}
// Query projects by user group
if projects != nil {
projectIDs := []int64{}
for _, project := range projects {
projectIDs = append(projectIDs, project.ProjectID)
}
query.ProjectIDs = projectIDs
}
}
result, err := p.ProjectMgr.List(query)
if err != nil {
p.ParseAndHandleError("failed to list projects", err)
return
}
for _, project := range result.Projects {
err = p.populateProperties(project)
if err != nil {
log.Errorf("populate project properties failed %v", err)
}
}
p.SetPaginationHeader(result.Total, page, size)
p.Data["json"] = result.Projects
p.ServeJSON()
}
func (p *ProjectAPI) populateProperties(project *models.Project) error {
if p.SecurityCtx.IsAuthenticated() {
roles := p.SecurityCtx.GetProjectRoles(project.ProjectID)
if len(roles) != 0 {
project.Role = roles[0]
}
if project.Role == common.RoleProjectAdmin ||
p.SecurityCtx.IsSysAdmin() {
project.Togglable = true
}
}
total, err := dao.GetTotalOfRepositories(&models.RepositoryQuery{
ProjectIDs: []int64{project.ProjectID},
})
if err != nil {
err = errors.Wrap(err, fmt.Sprintf("get repo count of project %d failed", project.ProjectID))
return err
}
project.RepoCount = total
// Populate chart count property
if config.WithChartMuseum() {
count, err := chartController.GetCountOfCharts([]string{project.Name})
if err != nil {
err = errors.Wrap(err, fmt.Sprintf("get chart count of project %d failed", project.ProjectID))
return err
}
project.ChartCount = count
}
return nil
}
// Put ...
func (p *ProjectAPI) Put() {
if !p.requireAccess(rbac.ActionUpdate) {
return
}
var req *models.ProjectRequest
if err := p.DecodeJSONReq(&req); err != nil {
p.SendBadRequestError(err)
return
}
if err := p.ProjectMgr.Update(p.project.ProjectID,
&models.Project{
Metadata: req.Metadata,
}); err != nil {
p.ParseAndHandleError(fmt.Sprintf("failed to update project %d",
p.project.ProjectID), err)
return
}
}
// Logs ...
func (p *ProjectAPI) Logs() {
if !p.requireAccess(rbac.ActionList, rbac.ResourceLog) {
return
}
page, size, err := p.GetPaginationParams()
if err != nil {
p.SendBadRequestError(err)
return
}
query := &models.LogQueryParam{
ProjectIDs: []int64{p.project.ProjectID},
Username: p.GetString("username"),
Repository: p.GetString("repository"),
Tag: p.GetString("tag"),
Operations: p.GetStrings("operation"),
Pagination: &models.Pagination{
Page: page,
Size: size,
},
}
timestamp := p.GetString("begin_timestamp")
if len(timestamp) > 0 {
t, err := utils.ParseTimeStamp(timestamp)
if err != nil {
p.SendBadRequestError(fmt.Errorf("invalid begin_timestamp: %s", timestamp))
return
}
query.BeginTime = t
}
timestamp = p.GetString("end_timestamp")
if len(timestamp) > 0 {
t, err := utils.ParseTimeStamp(timestamp)
if err != nil {
p.SendBadRequestError(fmt.Errorf("invalid end_timestamp: %s", timestamp))
return
}
query.EndTime = t
}
total, err := dao.GetTotalOfAccessLogs(query)
if err != nil {
p.SendInternalServerError(fmt.Errorf(
"failed to get total of access log: %v", err))
return
}
logs, err := dao.GetAccessLogs(query)
if err != nil {
p.SendInternalServerError(fmt.Errorf(
"failed to get access log: %v", err))
return
}
p.SetPaginationHeader(total, page, size)
p.Data["json"] = logs
p.ServeJSON()
}
// TODO move this to pa ckage models
func validateProjectReq(req *models.ProjectRequest) error {
pn := req.Name
if utils.IsIllegalLength(pn, projectNameMinLen, projectNameMaxLen) {
return fmt.Errorf("Project name %s is illegal in length. (greater than %d or less than %d)", pn, projectNameMaxLen, projectNameMinLen)
}
validProjectName := regexp.MustCompile(`^` + restrictedNameChars + `$`)
legal := validProjectName.MatchString(pn)
if !legal {
return fmt.Errorf("project name is not in lower case or contains illegal characters")
}
metas, err := validateProjectMetadata(req.Metadata)
if err != nil {
return err
}
req.Metadata = metas
return nil
}