-
Notifications
You must be signed in to change notification settings - Fork 125
/
project.go
1495 lines (1284 loc) · 55.6 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
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package route
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/evergreen-ci/cocoa"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/cloud"
dbModel "github.com/evergreen-ci/evergreen/model"
"github.com/evergreen-ci/evergreen/model/artifact"
"github.com/evergreen-ci/evergreen/model/commitqueue"
"github.com/evergreen-ci/evergreen/model/event"
"github.com/evergreen-ci/evergreen/model/parsley"
"github.com/evergreen-ci/evergreen/model/task"
"github.com/evergreen-ci/evergreen/model/user"
"github.com/evergreen-ci/evergreen/rest/data"
"github.com/evergreen-ci/evergreen/rest/model"
"github.com/evergreen-ci/evergreen/units"
"github.com/evergreen-ci/gimlet"
"github.com/evergreen-ci/utility"
"github.com/mongodb/amboy"
"github.com/mongodb/grip"
"github.com/mongodb/grip/message"
"github.com/pkg/errors"
)
type projectGetHandler struct {
key string
limit int
user *user.DBUser
url string
}
func makeFetchProjectsRoute(url string) gimlet.RouteHandler {
return &projectGetHandler{url: url}
}
// Factory creates an instance of the handler.
//
// @Summary Fetch all projects
// @Description Returns a paginated list of all projects. Any authenticated user can access this endpoint, so potentially sensitive information (variables, task annotation settings, workstation settings, and container secrets) is omitted.
// @Tags projects
// @Router /projects [get]
// @Security Api-User || Api-Key
// @Param start_at query string false "The identifier of the host to start at in the pagination"
// @Param limit query int false "The number of hosts to be returned per page of pagination. Defaults to 100"
// @Success 200 {array} model.APIProjectRef
func (p *projectGetHandler) Factory() gimlet.RouteHandler {
return &projectGetHandler{url: p.url}
}
func (p *projectGetHandler) Parse(ctx context.Context, r *http.Request) error {
p.user, _ = gimlet.GetUser(ctx).(*user.DBUser)
vals := r.URL.Query()
p.key = vals.Get("start_at")
var err error
p.limit, err = getLimit(vals)
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (p *projectGetHandler) Run(ctx context.Context) gimlet.Responder {
projects, err := dbModel.FindProjects(p.key, p.limit+1, 1)
if err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrap(err, "Database error"))
}
if len(projects) == 0 {
return gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{
Message: "no projects found",
StatusCode: http.StatusNotFound,
})
}
resp := gimlet.NewResponseBuilder()
lastIndex := len(projects)
if len(projects) > p.limit {
lastIndex = p.limit
err = resp.SetPages(&gimlet.ResponsePages{
Next: &gimlet.Page{
Relation: "next",
LimitQueryParam: "limit",
KeyQueryParam: "start_at",
BaseURL: p.url,
Key: projects[p.limit].Id,
Limit: p.limit,
},
})
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "paginating response"))
}
}
projects = projects[:lastIndex]
for _, proj := range projects {
projectModel := &model.APIProjectRef{}
// Because this is route to accessible to non-admins, only return basic fields.
if err = projectModel.BuildPublicFields(proj); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "converting project '%s' to API model", proj.Id))
}
if err = resp.AddData(projectModel); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "adding response data for project '%s'", utility.FromStringPtr(projectModel.Id)))
}
}
return resp
}
type legacyVersionsGetHandler struct {
project string
limit int
offset int
}
func makeFetchProjectVersionsLegacy() gimlet.RouteHandler {
return &legacyVersionsGetHandler{}
}
func (h *legacyVersionsGetHandler) Factory() gimlet.RouteHandler {
return &legacyVersionsGetHandler{}
}
func (h *legacyVersionsGetHandler) Parse(ctx context.Context, r *http.Request) error {
var err error
h.project = gimlet.GetVars(r)["project_id"]
var query = r.URL.Query()
limit := query.Get("limit")
if limit != "" {
h.limit, err = strconv.Atoi(limit)
if err != nil {
return errors.Wrap(err, "invalid limit")
}
} else {
h.limit = 10
}
offset := query.Get("offset")
if offset != "" {
h.offset, err = strconv.Atoi(offset)
if err != nil {
return errors.Wrap(err, "invalid offset")
}
} else {
h.offset = 0
}
return nil
}
func (h *legacyVersionsGetHandler) Run(ctx context.Context) gimlet.Responder {
projRefId, err := dbModel.GetIdForProject(h.project)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "getting ID for project '%s'", h.project))
}
_, proj, _, err := dbModel.FindLatestVersionWithValidProject(projRefId, false)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding latest version for project '%s'", projRefId))
}
versions, err := data.GetVersionsAndVariants(h.offset, h.limit, proj)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "getting versions and variants"))
}
return gimlet.NewJSONResponse(versions)
}
////////////////////////////////////////////////////////////////////////
//
// POST /rest/v2/projects/{project_id}/attach_to_repo
type attachProjectToRepoHandler struct {
project *dbModel.ProjectRef
user *user.DBUser
}
func makeAttachProjectToRepoHandler() gimlet.RouteHandler {
return &attachProjectToRepoHandler{}
}
func (h *attachProjectToRepoHandler) Factory() gimlet.RouteHandler {
return &attachProjectToRepoHandler{}
}
// Parse fetches the project's identifier from the http request.
func (h *attachProjectToRepoHandler) Parse(ctx context.Context, r *http.Request) error {
projectIdentifier := gimlet.GetVars(r)["project_id"]
h.user = MustHaveUser(ctx)
var err error
h.project, err = data.FindProjectById(projectIdentifier, false, false)
if err != nil {
return errors.Wrapf(err, "finding project '%s'", projectIdentifier)
}
if h.project.UseRepoSettings() {
return errors.New("project is already attached to repo")
}
return nil
}
func (h *attachProjectToRepoHandler) Run(ctx context.Context) gimlet.Responder {
if err := h.project.AttachToRepo(ctx, h.user); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "attaching repo to project"))
}
return gimlet.NewJSONResponse(struct{}{})
}
////////////////////////////////////////////////////////////////////////
//
// POST /rest/v2/projects/{project_id}/detach_from_repo
type detachProjectFromRepoHandler struct {
project *dbModel.ProjectRef
user *user.DBUser
}
func makeDetachProjectFromRepoHandler() gimlet.RouteHandler {
return &detachProjectFromRepoHandler{}
}
func (h *detachProjectFromRepoHandler) Factory() gimlet.RouteHandler {
return &detachProjectFromRepoHandler{}
}
// Parse fetches the project's identifier from the http request.
func (h *detachProjectFromRepoHandler) Parse(ctx context.Context, r *http.Request) error {
projectIdentifier := gimlet.GetVars(r)["project_id"]
h.user = MustHaveUser(ctx)
var err error
h.project, err = data.FindProjectById(projectIdentifier, false, false)
if err != nil {
return errors.Wrapf(err, "finding project '%s'", projectIdentifier)
}
if !h.project.UseRepoSettings() {
return errors.New("project isn't attached to a repo")
}
return nil
}
func (h *detachProjectFromRepoHandler) Run(ctx context.Context) gimlet.Responder {
if err := h.project.DetachFromRepo(h.user); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "detaching repo from project"))
}
return gimlet.NewJSONResponse(struct{}{})
}
////////////////////////////////////////////////////////////////////////
//
// PATCH /rest/v2/projects/{project_id}
type projectIDPatchHandler struct {
project string
user *user.DBUser
newProjectRef *dbModel.ProjectRef
originalProject *dbModel.ProjectRef
apiNewProjectRef *model.APIProjectRef
settings *evergreen.Settings
}
func makePatchProjectByID(settings *evergreen.Settings) gimlet.RouteHandler {
return &projectIDPatchHandler{
settings: settings,
}
}
// Factory creates an instance of the handler.
//
// @Summary Modify a project
// @Description Modify an existing project (restricted to project admins). Will enable webhooks if an enabled project, and enable PR testing and the commit queue if specified. For lists, if there is a complementary "delete" field, then the former field indicates items to be added, while the "delete" field indicates items to be deleted. Otherwise, the given list will overwrite the original list (the only exception is for project variables -- we will ignore any empty project variables to avoid accidentally overwriting private variables).
// @Tags projects
// @Router /projects/{project_id} [patch]
// @Security Api-User || Api-Key
// @Param project_id path string true "the project ID"
// @Param {object} body model.APIProjectRef true "parameters"
// @Success 200 {object} model.APIProjectRef
func (h *projectIDPatchHandler) Factory() gimlet.RouteHandler {
return &projectIDPatchHandler{
settings: h.settings,
}
}
// Parse fetches the project's identifier from the http request.
func (h *projectIDPatchHandler) Parse(ctx context.Context, r *http.Request) error {
h.project = gimlet.GetVars(r)["project_id"]
h.user = MustHaveUser(ctx)
body := utility.NewRequestReader(r)
defer body.Close()
b, err := io.ReadAll(body)
if err != nil {
return errors.Wrap(err, "reading JSON request body")
}
oldProject, err := data.FindProjectById(h.project, false, false)
if err != nil {
return errors.Wrapf(err, "finding original project '%s'", h.project)
}
requestProjectRef := &model.APIProjectRef{}
if err = requestProjectRef.BuildFromService(*oldProject); err != nil {
return errors.Wrap(err, "converting original project to API model")
}
// erase contents so apiNewProjectRef will only be populated with new elements for these fields
requestProjectRef.Admins = nil
requestProjectRef.GitTagAuthorizedUsers = nil
requestProjectRef.GitTagAuthorizedTeams = nil
if err = json.Unmarshal(b, requestProjectRef); err != nil {
return errors.Wrap(err, "unmarshalling modified project settings")
}
projectId := utility.FromStringPtr(requestProjectRef.Id)
if projectId != oldProject.Id {
return gimlet.ErrorResponse{
StatusCode: http.StatusForbidden,
Message: "project ID is immutable",
}
}
newProjectRef, err := requestProjectRef.ToService()
if err != nil {
return errors.Wrap(err, "converting new project to service model")
}
newProjectRef.RepoRefId = oldProject.RepoRefId // this can't be modified by users
h.newProjectRef = newProjectRef
h.originalProject = oldProject
h.apiNewProjectRef = requestProjectRef // needed for the delete fields
return nil
}
// Run updates a project by name.
func (h *projectIDPatchHandler) Run(ctx context.Context) gimlet.Responder {
if h.newProjectRef.IsHidden() {
return gimlet.NewJSONErrorResponse("can't patch a hidden project")
}
if err := h.newProjectRef.ValidateOwnerAndRepo(h.settings.GithubOrgs); err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrap(err, "validating owner and repo"))
}
if h.newProjectRef.Identifier != h.originalProject.Identifier {
if err := h.newProjectRef.ValidateIdentifier(); err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrap(err, "validating project identifier"))
}
}
if err := h.newProjectRef.ValidateEnabledRepotracker(); err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrap(err, "validating project repotracker"))
}
before, err := dbModel.GetProjectSettings(h.newProjectRef)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "getting original project settings for project '%s'", h.newProjectRef.Identifier))
}
adminsToDelete := utility.FromStringPtrSlice(h.apiNewProjectRef.DeleteAdmins)
adminsToAdd := h.newProjectRef.Admins
allAdmins := utility.UniqueStrings(append(h.originalProject.Admins, h.newProjectRef.Admins...)) // get original and new admin
h.newProjectRef.Admins, _ = utility.StringSliceSymmetricDifference(allAdmins, adminsToDelete) // add users that are in allAdmins and not in adminsToDelete
usersToDelete := utility.FromStringPtrSlice(h.apiNewProjectRef.DeleteGitTagAuthorizedUsers)
allAuthorizedUsers := utility.UniqueStrings(append(h.originalProject.GitTagAuthorizedUsers, h.newProjectRef.GitTagAuthorizedUsers...))
h.newProjectRef.GitTagAuthorizedUsers, _ = utility.StringSliceSymmetricDifference(allAuthorizedUsers, usersToDelete)
teamsToDelete := utility.FromStringPtrSlice(h.apiNewProjectRef.DeleteGitTagAuthorizedTeams)
allAuthorizedTeams := utility.UniqueStrings(append(h.originalProject.GitTagAuthorizedTeams, h.newProjectRef.GitTagAuthorizedTeams...))
h.newProjectRef.GitTagAuthorizedTeams, _ = utility.StringSliceSymmetricDifference(allAuthorizedTeams, teamsToDelete)
// If the project ref doesn't use the repo, then this will just be the same as newProjectRef.
// Used to verify that if something is set to nil in the request, we properly validate using the merged project ref.
mergedProjectRef, err := dbModel.GetProjectRefMergedWithRepo(*h.newProjectRef)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "merging project ref '%s' with repo settings", h.newProjectRef.Identifier))
}
if mergedProjectRef.Enabled {
settings, err := evergreen.GetConfig(ctx)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "getting evergreen settings"))
}
_, err = dbModel.ValidateEnabledProjectsLimit(h.newProjectRef.Id, settings, h.originalProject, mergedProjectRef)
if err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrapf(err, "validating project creation for project '%s'", h.newProjectRef.Identifier))
}
}
if h.newProjectRef.Enabled {
var hasHook bool
hasHook, err = dbModel.SetTracksPushEvents(ctx, h.newProjectRef)
if err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrapf(err, "setting project tracks push events for project '%s' in '%s/%s'", h.project, h.newProjectRef.Owner, h.newProjectRef.Repo))
}
var allAliases []model.APIProjectAlias
if mergedProjectRef.AliasesNeeded() {
allAliases, err = data.FindMergedProjectAliases(utility.FromStringPtr(h.apiNewProjectRef.Id), mergedProjectRef.RepoRefId, h.apiNewProjectRef.Aliases, false)
if err != nil {
return gimlet.NewJSONInternalErrorResponse(errors.Wrapf(err, "checking existing patch definitions for project '%s'", h.project))
}
}
// verify enabling PR testing valid
if mergedProjectRef.IsPRTestingEnabled() && !h.originalProject.IsPRTestingEnabled() {
if !hasHook {
return gimlet.MakeJSONErrorResponder(errors.New("cannot enable PR testing in this repo without first enabling GitHub webhooks"))
}
if !hasAliasDefined(allAliases, evergreen.GithubPRAlias) {
return gimlet.MakeJSONErrorResponder(errors.New("cannot enable PR testing without a PR patch definition"))
}
if err = canEnablePRTesting(h.newProjectRef); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "enabling PR testing for project '%s'", h.project))
}
}
// verify enabling github checks is valid
if mergedProjectRef.IsGithubChecksEnabled() && !h.originalProject.IsGithubChecksEnabled() {
if !hasAliasDefined(allAliases, evergreen.GithubChecksAlias) {
return gimlet.MakeJSONErrorResponder(errors.New("cannot enable GitHub checks without a version definition"))
}
}
// verify enabling git tag versions is valid
if mergedProjectRef.IsGitTagVersionsEnabled() && !h.originalProject.IsGitTagVersionsEnabled() {
if !hasAliasDefined(allAliases, evergreen.GitTagAlias) {
return gimlet.MakeJSONErrorResponder(errors.New("cannot enable git tag versions without a version definition"))
}
}
// verify enabling commit queue valid
if mergedProjectRef.CommitQueue.IsEnabled() && !h.originalProject.CommitQueue.IsEnabled() {
if !hasHook {
return gimlet.MakeJSONErrorResponder(errors.New("cannot enable commit queue without first enabling GitHub webhooks"))
}
if !hasAliasDefined(allAliases, evergreen.CommitQueueAlias) {
return gimlet.MakeJSONErrorResponder(errors.New("cannot enable commit queue without a commit queue patch definition"))
}
if err = canEnableCommitQueue(h.newProjectRef); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "enabling commit queue for project '%s'", h.project))
}
}
}
// validate triggers before updating project
catcher := grip.NewSimpleCatcher()
for i := range h.newProjectRef.Triggers {
catcher.Add(h.newProjectRef.Triggers[i].Validate(h.newProjectRef.Id))
}
for i := range h.newProjectRef.PatchTriggerAliases {
h.newProjectRef.PatchTriggerAliases[i], err = dbModel.ValidateTriggerDefinition(h.newProjectRef.PatchTriggerAliases[i], h.newProjectRef.Id)
catcher.Add(err)
}
for _, buildDef := range h.newProjectRef.PeriodicBuilds {
catcher.Wrapf(buildDef.Validate(), "invalid periodic build definition")
}
if catcher.HasErrors() {
return gimlet.MakeJSONErrorResponder(errors.Wrap(catcher.Resolve(), "invalid triggers"))
}
// Validate Parsley filters before updating project.
err = parsley.ValidateFilters(h.newProjectRef.ParsleyFilters)
if err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrap(err, "invalid Parsley filters"))
}
err = dbModel.ValidateBbProject(h.newProjectRef.Id, h.newProjectRef.BuildBaronSettings, &h.newProjectRef.TaskAnnotationSettings.FileTicketWebhook)
if err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrap(err, "validating build baron config"))
}
newRevision := utility.FromStringPtr(h.apiNewProjectRef.Revision)
if newRevision != "" {
if err = dbModel.UpdateProjectRevision(h.project, newRevision); err != nil {
return gimlet.MakeJSONErrorResponder(err)
}
h.newProjectRef.RepotrackerError = &dbModel.RepositoryErrorDetails{
Exists: false,
InvalidRevision: "",
MergeBaseRevision: "",
}
}
var vault cocoa.Vault
if len(h.apiNewProjectRef.DeleteContainerSecrets) != 0 || len(h.apiNewProjectRef.ContainerSecrets) != 0 {
smClient, err := cloud.MakeSecretsManagerClient(ctx, h.settings)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "initializing Secrets Manager client"))
}
defer smClient.Close(ctx)
v, err := cloud.MakeSecretsManagerVault(smClient)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "initializing Secrets Manager vault"))
}
vault = v
}
// This intentionally deletes the container secrets from external storage
// before updating the project ref. Deleting the secrets before updating the
// project ref ensures that the cloud secrets are cleaned up before removing
// references to them in the project ref.
remainingSecretsAfterDeletion, err := data.DeleteContainerSecrets(ctx, vault, h.originalProject, h.apiNewProjectRef.DeleteContainerSecrets)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "deleting container secrets"))
}
var updatedContainerSecrets []dbModel.ContainerSecret
for _, containerSecret := range h.newProjectRef.ContainerSecrets {
if utility.StringSliceContains(h.apiNewProjectRef.DeleteContainerSecrets, containerSecret.Name) {
continue
}
updatedContainerSecrets = append(updatedContainerSecrets, containerSecret)
}
allContainerSecrets, err := dbModel.ValidateContainerSecrets(h.settings, h.newProjectRef.Id, remainingSecretsAfterDeletion, updatedContainerSecrets)
if err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrap(err, "invalid container secrets"))
}
h.newProjectRef.ContainerSecrets = allContainerSecrets
if h.originalProject.Restricted != mergedProjectRef.Restricted {
if mergedProjectRef.IsRestricted() {
err = mergedProjectRef.MakeRestricted()
} else {
err = mergedProjectRef.MakeUnrestricted()
}
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(err)
}
}
// if owner/repo has changed and the project is attached to repo, update scope and repo accordingly
if h.newProjectRef.UseRepoSettings() && h.ownerRepoChanged() {
if err = h.newProjectRef.RemoveFromRepoScope(); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "removing project from old repo scope"))
}
if err = h.newProjectRef.AddToRepoScope(h.user); err != nil { // will re-add using the new owner/repo
return gimlet.MakeJSONInternalErrorResponder(err)
}
}
// complete all updates
if err = h.newProjectRef.Upsert(); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "updating project '%s'", h.newProjectRef.Id))
}
// Under the hood, this is updating the container secrets in the DB project
// ref, but this function's copy of the in-memory project ref won't reflect
// those changes.
if err := data.UpsertContainerSecrets(ctx, vault, allContainerSecrets); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "upserting container secrets"))
}
if err = data.UpdateProjectVars(h.newProjectRef.Id, &h.apiNewProjectRef.Variables, false); err != nil { // destructively modifies h.apiNewProjectRef.Variables
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "updating variables for project '%s'", h.project))
}
if err = data.UpdateProjectAliases(h.newProjectRef.Id, h.apiNewProjectRef.Aliases); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "updating aliases for project '%s'", h.project))
}
if err = dbModel.UpdateAdminRoles(h.newProjectRef, adminsToAdd, adminsToDelete); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "updating admins for project '%s'", h.project))
}
// Don't use Save to delete subscriptions, since we aren't checking the
// delete subscriptions list against the inputted list of subscriptions.
if err = data.SaveSubscriptions(h.newProjectRef.Id, h.apiNewProjectRef.Subscriptions, true); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "saving subscriptions for project '%s'", h.project))
}
toDelete := []string{}
for _, deleteSub := range h.apiNewProjectRef.DeleteSubscriptions {
toDelete = append(toDelete, utility.FromStringPtr(deleteSub))
}
if err = data.DeleteSubscriptions(h.newProjectRef.Id, toDelete); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "deleting subscriptions for project '%s'", h.project))
}
after, err := dbModel.GetProjectSettings(h.newProjectRef)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "getting project settings after update for project '%s'", h.project))
}
if err = dbModel.LogProjectModified(h.newProjectRef.Id, h.user.Username(), before, after); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "logging modification event for project '%s'", h.project))
}
// run the repotracker for the project
if newRevision != "" {
ts := utility.RoundPartOfHour(1).Format(units.TSFormat)
j := units.NewRepotrackerJob(fmt.Sprintf("catchup-%s", ts), h.newProjectRef.Id)
queue := evergreen.GetEnvironment().RemoteQueue()
if err = amboy.EnqueueUniqueJob(ctx, queue, j); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "enqueueing catchup job"))
}
}
return gimlet.NewJSONResponse(struct{}{})
}
func (h projectIDPatchHandler) ownerRepoChanged() bool {
return h.newProjectRef.Owner != h.originalProject.Owner || h.newProjectRef.Repo != h.originalProject.Repo
}
// verify for a given alias that either the user has added a new definition or there is a pre-existing definition
func hasAliasDefined(aliases []model.APIProjectAlias, alias string) bool {
for _, a := range aliases {
if utility.FromStringPtr(a.Alias) == alias {
return true
}
}
return false
}
// canEnableCommitQueue determines if commit queue can be enabled for the given project.
func canEnableCommitQueue(projectRef *dbModel.ProjectRef) error {
if ok, err := projectRef.CanEnableCommitQueue(); err != nil {
return errors.Wrap(err, "checking if commit queue can be enabled")
} else if !ok {
return errors.Errorf("cannot enable commit queue in this repo, must disable in other projects first")
}
return commitqueue.EnsureCommitQueueExistsForProject(projectRef.Id)
}
// canEnablePRTesting determines if PR testing can be enabled for the given project.
func canEnablePRTesting(projectRef *dbModel.ProjectRef) error {
conflicts, err := projectRef.GetGithubProjectConflicts()
if err != nil {
return errors.Wrap(err, "finding project refs with conflicting GitHub settings")
}
if len(conflicts.PRTestingIdentifiers) > 0 {
return errors.Errorf("cannot enable PR testing in this repo, must disable in other projects first")
}
return nil
}
////////////////////////////////////////////////////////////////////////
//
// PUT /rest/v2/projects/{project_id}
type projectIDPutHandler struct {
projectName string
project model.APIProjectRef
body []byte
env evergreen.Environment
}
func makePutProjectByID(env evergreen.Environment) gimlet.RouteHandler {
return &projectIDPutHandler{env: env}
}
// Factory creates an instance of the handler.
//
// @Summary Put a project
// @Description Create a new project with the given project ID. Restricted to super users.
// @Tags projects
// @Router /projects/{project_id} [put]
// @Security Api-User || Api-Key
// @Param project_id path string true "the project ID"
// @Param {object} body model.APIProjectRef false "parameters"
// @Success 200 {object} model.APIProjectRef
func (h *projectIDPutHandler) Factory() gimlet.RouteHandler {
return &projectIDPutHandler{env: h.env}
}
// Parse fetches the distroId and JSON payload from the http request.
func (h *projectIDPutHandler) Parse(ctx context.Context, r *http.Request) error {
h.projectName = gimlet.GetVars(r)["project_id"]
body := utility.NewRequestReader(r)
defer body.Close()
b, err := io.ReadAll(body)
if err != nil {
return errors.Wrap(err, "reading request body")
}
h.body = b
apiProjectRef := model.APIProjectRef{}
if err = json.Unmarshal(h.body, &apiProjectRef); err != nil {
return errors.Wrap(err, "unmarshalling JSON request body into project ref")
}
h.project = apiProjectRef
if utility.FromStringPtr(h.project.Owner) == "" || utility.FromStringPtr(h.project.Repo) == "" {
return errors.New("Owner and repository must not be empty strings")
}
return nil
}
// Run creates a new resource based on the Request-URI and JSON payload and returns a http.StatusCreated (201)
func (h *projectIDPutHandler) Run(ctx context.Context) gimlet.Responder {
p, err := data.FindProjectById(h.projectName, false, false)
if err != nil && err.(gimlet.ErrorResponse).StatusCode != http.StatusNotFound {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding project '%s'", h.projectName))
}
if p != nil {
return gimlet.MakeJSONErrorResponder(errors.Errorf("project with identifier '%s' already exists", h.projectName))
}
dbProjectRef := dbModel.ProjectRef{
Identifier: h.projectName,
Id: utility.FromStringPtr(h.project.Id),
Owner: utility.FromStringPtr(h.project.Owner),
Repo: utility.FromStringPtr(h.project.Repo),
}
responder := gimlet.NewJSONResponse(struct{}{})
if err = responder.SetStatus(http.StatusCreated); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "setting response HTTP status code to %d", http.StatusCreated))
}
u := gimlet.GetUser(ctx).(*user.DBUser)
if created, err := data.CreateProject(ctx, h.env, &dbProjectRef, u); err != nil && !created {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "creating project '%s'", h.projectName))
}
return responder
}
////////////////////////////////////////////////////////////////////////
//
// POST /rest/v2/projects/{project_id}/repotracker
type projectRepotrackerHandler struct {
projectName string
}
func makeRunRepotrackerForProject() gimlet.RouteHandler {
return &projectRepotrackerHandler{}
}
func (h *projectRepotrackerHandler) Factory() gimlet.RouteHandler {
return &projectRepotrackerHandler{}
}
func (h *projectRepotrackerHandler) Parse(ctx context.Context, r *http.Request) error {
h.projectName = gimlet.GetVars(r)["project_id"]
return nil
}
func (h *projectRepotrackerHandler) Run(ctx context.Context) gimlet.Responder {
projectId, err := dbModel.GetIdForProject(h.projectName)
if err != nil {
return gimlet.MakeJSONErrorResponder(errors.Wrapf(err, "getting ID for project '%s'", h.projectName))
}
ts := utility.RoundPartOfHour(1).Format(units.TSFormat)
j := units.NewRepotrackerJob(fmt.Sprintf("rest-%s", ts), projectId)
queue := evergreen.GetEnvironment().RemoteQueue()
if err := amboy.EnqueueUniqueJob(ctx, queue, j); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "enqueueing catchup job"))
}
return gimlet.NewJSONResponse(struct{}{})
}
////////////////////////////////////////////////////////////////////////
//
// DELETE /rest/v2/projects/{project_id}
type projectDeleteHandler struct {
projectName string
}
func makeDeleteProject() gimlet.RouteHandler {
return &projectDeleteHandler{}
}
func (h *projectDeleteHandler) Factory() gimlet.RouteHandler {
return &projectDeleteHandler{}
}
func (h *projectDeleteHandler) Parse(ctx context.Context, r *http.Request) error {
h.projectName = gimlet.GetVars(r)["project_id"]
return nil
}
func (h *projectDeleteHandler) Run(ctx context.Context) gimlet.Responder {
if err := data.HideBranch(h.projectName); err != nil {
return gimlet.MakeJSONInternalErrorResponder(err)
}
return gimlet.NewJSONResponse(struct{}{})
}
////////////////////////////////////////////////////////////////////////
//
// GET /rest/v2/projects/{project_id}
type projectIDGetHandler struct {
projectName string
includeRepo bool
includeProjectConfig bool
}
func makeGetProjectByID() gimlet.RouteHandler {
return &projectIDGetHandler{}
}
// Factory creates an instance of the handler.
//
// @Summary Get a project
// @Description Returns the project (restricted to project admins). Includes public variables, aliases, and subscriptions. Note that private variables are always redacted. If you want to use this to copy project variables, see instead the "Copy Project Variables" route.
// @Tags projects
// @Router /projects/{project_id} [get]
// @Security Api-User || Api-Key
// @Param project_id path string true "the project ID"
// @Param includeRepo query bool false "Setting to true will return the merged result of project and repo level settings. Defaults to false"
// @Param includeProjectConfig query bool false "Setting to true will return the merged result of the project and the config properties set in the project YAML. Defaults to false"
// @Success 200 {object} model.APIProjectRef
func (h *projectIDGetHandler) Factory() gimlet.RouteHandler {
return &projectIDGetHandler{}
}
func (h *projectIDGetHandler) Parse(ctx context.Context, r *http.Request) error {
h.projectName = gimlet.GetVars(r)["project_id"]
h.includeRepo = r.URL.Query().Get("includeRepo") == "true"
h.includeProjectConfig = r.URL.Query().Get("includeProjectConfig") == "true"
return nil
}
func (h *projectIDGetHandler) Run(ctx context.Context) gimlet.Responder {
project, err := data.FindProjectById(h.projectName, h.includeRepo, h.includeProjectConfig)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding project '%s'", h.projectName))
}
if project == nil {
return gimlet.MakeJSONErrorResponder(errors.Errorf("project '%s' not found", h.projectName))
}
projectModel := &model.APIProjectRef{}
if err = projectModel.BuildFromService(*project); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "converting project '%s' to API model", h.projectName))
}
// we pass the repoId through so we don't have to re-look up the project
repoId := ""
if h.includeRepo {
repoId = project.RepoRefId
}
variables, err := data.FindProjectVarsById(project.Id, repoId, true)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding vars for project '%s'", project.Id))
}
projectModel.Variables = *variables
if projectModel.Aliases, err = data.FindMergedProjectAliases(project.Id, repoId, nil, h.includeProjectConfig); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding aliases for project '%s'", project.Id))
}
if projectModel.Subscriptions, err = data.GetSubscriptions(project.Id, event.OwnerTypeProject); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "getting subscriptions for project '%s'", project.Id))
}
return gimlet.NewJSONResponse(projectModel)
}
////////////////////////////////////////////////////////////////////////
//
// GET /rest/v2/projects/{project_id}/versions
const defaultVersionLimit = 20
type getProjectVersionsHandler struct {
projectName string
opts dbModel.GetVersionsOptions
url string
}
func makeGetProjectVersionsHandler(url string) gimlet.RouteHandler {
return &getProjectVersionsHandler{url: url}
}
// Factory creates an instance of the handler.
//
// @Summary Get versions for a project
// @Description Returns a paginated list of recent versions for a project. Parameters should be passed into the JSON body (the route still accepts limit and start as query parameters to support legacy behavior).
// @Tags versions
// @Router /projects/{project_id}/versions [get]
// @Security Api-User || Api-Key
// @Param project_id path string true "the project ID"
// @Param skip query int false "Number of versions to skip."
// @Param limit query int false "The number of versions to be returned per page of pagination. Defaults to 20."
// @Param start query int false "The version order number to start at, for pagination. Will return the versions that are less than (and therefore older) the revision number specified."
// @Param revision_end query int false "Will return the versions that are greater than (and therefore more recent) or equal to revision number specified."
// @Param requester query string false "Returns versions for this requester only. Defaults to gitter_request (caused by git commit, aka the repotracker requester). Can also be set to patch_request, github_pull_request, trigger_request (Project Trigger versions) , merge_test (commit queue patches), and ad_hoc (periodic builds)."
// @Param include_builds query bool false "If set, will return some information for each build in the version."
// @Param by_build_variant query string false "If set, will only include information for this build, and only return versions with this build activated. Must have include_builds set."
// @Param include_tasks query bool false "If set, will return some information for each task in the included builds. This is only allowed if include_builds is set."
// @Param by_task query string false "If set, will only include information for this task, and will only return versions with this task activated. Must have include_tasks set."
// @Success 200 {array} model.APIVersion
func (h *getProjectVersionsHandler) Factory() gimlet.RouteHandler {
return &getProjectVersionsHandler{url: h.url}
}
func (h *getProjectVersionsHandler) Parse(ctx context.Context, r *http.Request) error {
h.projectName = gimlet.GetVars(r)["project_id"]
params := r.URL.Query()
// body is optional
b, _ := io.ReadAll(r.Body)
if len(b) > 0 {
if err := json.Unmarshal(b, &h.opts); err != nil {
return errors.Wrap(err, "unmarshalling JSON request body into version options")
}
}
if h.opts.IncludeTasks && !h.opts.IncludeBuilds {
return errors.New("cannot include tasks without builds")
}
// get some options from the query parameters for legacy usage
limitStr := params.Get("limit")
if limitStr != "" {
limit, err := strconv.Atoi(limitStr)
if err != nil {
return errors.Wrap(err, "invalid limit")
}
h.opts.Limit = limit
}
if h.opts.Limit == 0 {
h.opts.Limit = defaultVersionLimit
}
if h.opts.Limit < 1 {
return errors.New("limit must be a positive integer")
}
startStr := params.Get("start")
if startStr != "" {
startOrder, err := strconv.Atoi(params.Get("start"))
if err != nil {
return errors.Wrap(err, "invalid start query parameter")
}
h.opts.Start = startOrder
}
if h.opts.Start < 0 {
return errors.New("start must be a non-negative integer")
}
if h.opts.RevisionEnd < 0 {
return errors.New("revision_end must be a non-negative integer")
}
requester := params.Get("requester")
if requester != "" {
h.opts.Requester = requester
}
if h.opts.Requester == "" {
h.opts.Requester = evergreen.RepotrackerVersionRequester
}
return nil
}
func (h *getProjectVersionsHandler) Run(ctx context.Context) gimlet.Responder {
versions, err := data.GetProjectVersionsWithOptions(h.projectName, h.opts)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "getting versions for project '%s'", h.projectName))
}
resp, err := gimlet.NewBasicResponder(http.StatusOK, gimlet.JSON, versions)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "constructing response"))
}
if len(versions) >= h.opts.Limit {
err = resp.SetPages(&gimlet.ResponsePages{
Next: &gimlet.Page{
Relation: "next",
LimitQueryParam: "limit",
KeyQueryParam: "start",
BaseURL: h.url,
Key: strconv.Itoa(versions[len(versions)-1].Order),
Limit: h.opts.Limit,
},
})
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "paginating response"))
}
}
return resp
}