-
Notifications
You must be signed in to change notification settings - Fork 28
/
secret.go
822 lines (707 loc) · 20.3 KB
/
secret.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
// Copyright (c) 2022 Target Brands, Inc. All rights reserved.
//
// Use of this source code is governed by the LICENSE file in this repository.
package api
import (
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-vela/server/router/middleware/claims"
"github.com/go-vela/server/router/middleware/user"
"github.com/go-vela/server/scm"
"github.com/go-vela/server/secret"
"github.com/go-vela/server/util"
"github.com/go-vela/types/constants"
"github.com/go-vela/types/library"
"github.com/sirupsen/logrus"
)
//
// swagger:operation POST /api/v1/secrets/{engine}/{type}/{org}/{name} secrets CreateSecret
//
// Create a secret
//
// ---
// produces:
// - application/json
// parameters:
// - in: path
// name: engine
// description: Secret engine to create a secret in, eg. "native"
// required: true
// type: string
// - in: path
// name: type
// description: Secret type to create
// enum:
// - org
// - repo
// - shared
// required: true
// type: string
// - in: path
// name: org
// description: Name of the org
// required: true
// type: string
// - in: path
// name: name
// description: Name of the repo if a repo secret, team name if a shared secret, or '*' if an org secret
// required: true
// type: string
// - in: body
// name: body
// description: Payload containing the secret to create
// required: true
// schema:
// "$ref": "#/definitions/Secret"
// security:
// - ApiKeyAuth: []
// responses:
// '200':
// description: Successfully created the secret
// schema:
// "$ref": "#/definitions/Secret"
// '400':
// description: Unable to create the secret
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: Unable to create the secret
// schema:
// "$ref": "#/definitions/Error"
// CreateSecret represents the API handler to
// create a secret in the configured backend.
//
//nolint:funlen // suppress long function error
func CreateSecret(c *gin.Context) {
// capture middleware values
u := user.Retrieve(c)
e := util.PathParameter(c, "engine")
t := util.PathParameter(c, "type")
o := util.PathParameter(c, "org")
n := util.PathParameter(c, "name")
entry := fmt.Sprintf("%s/%s/%s", t, o, n)
// create log fields from API metadata
fields := logrus.Fields{
"engine": e,
"org": o,
"repo": n,
"type": t,
"user": u.GetName(),
}
// check if secret is a shared secret
if strings.EqualFold(t, constants.SecretShared) {
// update log fields from API metadata
fields = logrus.Fields{
"engine": e,
"org": o,
"team": n,
"type": t,
"user": u.GetName(),
}
}
if strings.EqualFold(t, constants.SecretOrg) {
// retrieve org name from SCM
//
// SCM can be case insensitive, causing access retrieval to work
// but Org/Repo != org/repo in Vela. So this check ensures that
// what a user inputs matches the casing we expect in Vela since
// the SCM will have the source of truth for casing.
org, err := scm.FromContext(c).GetOrgName(u, o)
if err != nil {
retErr := fmt.Errorf("unable to retrieve organization %s", o)
util.HandleError(c, http.StatusNotFound, retErr)
return
}
// check if casing is accurate
if org != o {
retErr := fmt.Errorf("unable to retrieve organization %s. Did you mean %s?", o, org)
util.HandleError(c, http.StatusNotFound, retErr)
return
}
}
if strings.EqualFold(t, constants.SecretRepo) {
// retrieve org and repo name from SCM
//
// same story as org secret. SCM has accurate casing.
scmOrg, scmRepo, err := scm.FromContext(c).GetOrgAndRepoName(u, o, n)
if err != nil {
retErr := fmt.Errorf("unable to retrieve repository %s/%s", o, n)
util.HandleError(c, http.StatusNotFound, retErr)
return
}
// check if casing is accurate for org entry
if scmOrg != o {
retErr := fmt.Errorf("unable to retrieve org %s. Did you mean %s?", o, scmOrg)
util.HandleError(c, http.StatusNotFound, retErr)
return
}
// check if casing is accurate for repo entry
if scmRepo != n {
retErr := fmt.Errorf("unable to retrieve repository %s. Did you mean %s?", n, scmRepo)
util.HandleError(c, http.StatusNotFound, retErr)
return
}
}
// update engine logger with API metadata
//
// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#Entry.WithFields
logrus.WithFields(fields).Infof("creating new secret %s for %s service", entry, e)
// capture body from API request
input := new(library.Secret)
err := c.Bind(input)
if err != nil {
retErr := fmt.Errorf("unable to decode JSON for secret %s for %s service: %w", entry, e, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
// reject secrets with solely whitespace characters as its value
trimmed := strings.TrimSpace(input.GetValue())
if len(trimmed) == 0 {
retErr := fmt.Errorf("secret value must contain non-whitespace characters")
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
// update fields in secret object
input.SetOrg(o)
input.SetRepo(n)
input.SetType(t)
input.SetCreatedAt(time.Now().UTC().Unix())
input.SetCreatedBy(u.GetName())
input.SetUpdatedAt(time.Now().UTC().Unix())
input.SetUpdatedBy(u.GetName())
if len(input.GetImages()) > 0 {
input.SetImages(unique(input.GetImages()))
}
if len(input.GetEvents()) > 0 {
input.SetEvents(unique(input.GetEvents()))
}
if len(input.GetEvents()) == 0 {
// set default events to enable for the secret
input.SetEvents([]string{constants.EventPush, constants.EventTag, constants.EventDeploy})
}
if input.AllowCommand == nil {
input.SetAllowCommand(true)
}
// check if secret is a shared secret
if strings.EqualFold(t, constants.SecretShared) {
// update the team instead of repo
input.SetTeam(n)
input.Repo = nil
}
// send API call to create the secret
err = secret.FromContext(c, e).Create(t, o, n, input)
if err != nil {
retErr := fmt.Errorf("unable to create secret %s for %s service: %w", entry, e, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
s, _ := secret.FromContext(c, e).Get(t, o, n, input.GetName())
c.JSON(http.StatusOK, s.Sanitize())
}
//
// swagger:operation GET /api/v1/secrets/{engine}/{type}/{org}/{name} secrets GetSecrets
//
// Retrieve a list of secrets from the configured backend
//
// ---
// produces:
// - application/json
// parameters:
// - in: path
// name: engine
// description: Secret engine to create a secret in, eg. "native"
// required: true
// type: string
// - in: path
// name: type
// description: Secret type to create
// enum:
// - org
// - repo
// - shared
// required: true
// type: string
// - in: path
// name: org
// description: Name of the org
// required: true
// type: string
// - in: path
// name: name
// description: Name of the repo if a repo secret, team name if a shared secret, or '*' if an org secret
// required: true
// type: string
// - in: query
// name: page
// description: The page of results to retrieve
// type: integer
// default: 1
// - in: query
// name: per_page
// description: How many results per page to return
// type: integer
// maximum: 100
// default: 10
// security:
// - ApiKeyAuth: []
// responses:
// '200':
// description: Successfully retrieved the list of secrets
// schema:
// type: array
// items:
// "$ref": "#/definitions/Secret"
// headers:
// X-Total-Count:
// description: Total number of results
// type: integer
// Link:
// description: see https://tools.ietf.org/html/rfc5988
// type: string
// '400':
// description: Unable to retrieve the list of secrets
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: Unable to retrieve the list of secrets
// schema:
// "$ref": "#/definitions/Error"
// GetSecrets represents the API handler to capture
// a list of secrets from the configured backend.
func GetSecrets(c *gin.Context) {
// capture middleware values
u := user.Retrieve(c)
e := util.PathParameter(c, "engine")
t := util.PathParameter(c, "type")
o := util.PathParameter(c, "org")
n := util.PathParameter(c, "name")
var teams []string
// get list of user's teams if type is shared secret and team is '*'
if t == constants.SecretShared && n == "*" {
var err error
teams, err = scm.FromContext(c).ListUsersTeamsForOrg(u, o)
if err != nil {
retErr := fmt.Errorf("unable to get users %s teams for org %s: %w", u.GetName(), o, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
}
entry := fmt.Sprintf("%s/%s/%s", t, o, n)
// create log fields from API metadata
fields := logrus.Fields{
"engine": e,
"org": o,
"repo": n,
"type": t,
"user": u.GetName(),
}
// check if secret is a shared secret
if strings.EqualFold(t, constants.SecretShared) {
// update log fields from API metadata
fields = logrus.Fields{
"engine": e,
"org": o,
"team": n,
"type": t,
"user": u.GetName(),
}
}
// update engine logger with API metadata
//
// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#Entry.WithFields
logrus.WithFields(fields).Infof("reading secrets %s from %s service", entry, e)
// capture page query parameter if present
page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
if err != nil {
retErr := fmt.Errorf("unable to convert page query parameter for %s from %s service: %w", entry, e, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
// capture per_page query parameter if present
perPage, err := strconv.Atoi(c.DefaultQuery("per_page", "10"))
if err != nil {
retErr := fmt.Errorf("unable to convert per_page query parameter for %s from %s service: %w", entry, e, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
// send API call to capture the total number of secrets
total, err := secret.FromContext(c, e).Count(t, o, n, teams)
if err != nil {
retErr := fmt.Errorf("unable to get secret count for %s from %s service: %w", entry, e, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
// ensure per_page isn't above or below allowed values
perPage = util.MaxInt(1, util.MinInt(100, perPage))
// send API call to capture the list of secrets
s, err := secret.FromContext(c, e).List(t, o, n, page, perPage, teams)
if err != nil {
retErr := fmt.Errorf("unable to get secrets for %s from %s service: %w", entry, e, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
// create pagination object
pagination := Pagination{
Page: page,
PerPage: perPage,
Total: total,
}
// set pagination headers
pagination.SetHeaderLink(c)
// variable we want to return
secrets := []*library.Secret{}
// iterate through all secrets
for _, secret := range s {
// https://golang.org/doc/faq#closures_and_goroutines
tmp := secret
// sanitize secret to ensure no value is provided
secrets = append(secrets, tmp.Sanitize())
}
c.JSON(http.StatusOK, secrets)
}
//
// swagger:operation GET /api/v1/secrets/{engine}/{type}/{org}/{name}/{secret} secrets GetSecret
//
// Retrieve a secret from the configured backend
//
// ---
// produces:
// - application/json
// parameters:
// - in: path
// name: engine
// description: Secret engine to create a secret in, eg. "native"
// required: true
// type: string
// - in: path
// name: type
// description: Secret type to create
// enum:
// - org
// - repo
// - shared
// required: true
// type: string
// - in: path
// name: org
// description: Name of the org
// required: true
// type: string
// - in: path
// name: name
// description: Name of the repo if a repo secret, team name if a shared secret, or '*' if an org secret
// required: true
// type: string
// - in: path
// name: secret
// description: Name of the secret
// required: true
// type: string
// security:
// - ApiKeyAuth: []
// responses:
// '200':
// description: Successfully retrieved the secret
// schema:
// "$ref": "#/definitions/Secret"
// '500':
// description: Unable to retrieve the secret
// schema:
// "$ref": "#/definitions/Error"
// GetSecret gets a secret from the provided secrets service.
func GetSecret(c *gin.Context) {
// capture middleware values
cl := claims.Retrieve(c)
u := user.Retrieve(c)
e := util.PathParameter(c, "engine")
t := util.PathParameter(c, "type")
o := util.PathParameter(c, "org")
n := util.PathParameter(c, "name")
s := strings.TrimPrefix(util.PathParameter(c, "secret"), "/")
entry := fmt.Sprintf("%s/%s/%s/%s", t, o, n, s)
// create log fields from API metadata
fields := logrus.Fields{
"engine": e,
"org": o,
"repo": n,
"secret": s,
"type": t,
"user": u.GetName(),
}
// check if secret is a shared secret
if strings.EqualFold(t, constants.SecretShared) {
// update log fields from API metadata
fields = logrus.Fields{
"engine": e,
"org": o,
"secret": s,
"team": n,
"type": t,
"user": u.GetName(),
}
}
// update engine logger with API metadata
//
// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#Entry.WithFields
logrus.WithFields(fields).Infof("reading secret %s from %s service", entry, e)
// send API call to capture the secret
secret, err := secret.FromContext(c, e).Get(t, o, n, s)
if err != nil {
retErr := fmt.Errorf("unable to get secret %s from %s service: %w", entry, e, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
// only allow workers to access the full secret with the value
if strings.EqualFold(cl.TokenType, constants.WorkerBuildTokenType) {
c.JSON(http.StatusOK, secret)
return
}
c.JSON(http.StatusOK, secret.Sanitize())
}
//
// swagger:operation PUT /api/v1/secrets/{engine}/{type}/{org}/{name}/{secret} secrets UpdateSecrets
//
// Update a secret on the configured backend
//
// ---
// produces:
// - application/json
// parameters:
// - in: path
// name: engine
// description: Secret engine to update the secret in, eg. "native"
// required: true
// type: string
// - in: path
// name: type
// description: Secret type to update
// enum:
// - org
// - repo
// - shared
// required: true
// type: string
// - in: path
// name: org
// description: Name of the org
// required: true
// type: string
// - in: path
// name: name
// description: Name of the repo if a repo secret, team name if a shared secret, or '*' if an org secret
// required: true
// type: string
// - in: path
// name: secret
// description: Name of the secret
// required: true
// type: string
// - in: body
// name: body
// description: Payload containing the secret to create
// required: true
// schema:
// "$ref": "#/definitions/Secret"
// security:
// - ApiKeyAuth: []
// responses:
// '200':
// description: Successfully updated the secret
// schema:
// "$ref": "#/definitions/Secret"
// '400':
// description: Unable to update the secret
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: Unable to update the secret
// schema:
// "$ref": "#/definitions/Error"
// UpdateSecret updates a secret for the provided secrets service.
func UpdateSecret(c *gin.Context) {
// capture middleware values
u := user.Retrieve(c)
e := util.PathParameter(c, "engine")
t := util.PathParameter(c, "type")
o := util.PathParameter(c, "org")
n := util.PathParameter(c, "name")
s := strings.TrimPrefix(util.PathParameter(c, "secret"), "/")
entry := fmt.Sprintf("%s/%s/%s/%s", t, o, n, s)
// create log fields from API metadata
fields := logrus.Fields{
"engine": e,
"org": o,
"repo": n,
"secret": s,
"type": t,
"user": u.GetName(),
}
// check if secret is a shared secret
if strings.EqualFold(t, constants.SecretShared) {
// update log fields from API metadata
fields = logrus.Fields{
"engine": e,
"org": o,
"secret": s,
"team": n,
"type": t,
"user": u.GetName(),
}
}
// update engine logger with API metadata
//
// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#Entry.WithFields
logrus.WithFields(fields).Infof("updating secret %s for %s service", entry, e)
// capture body from API request
input := new(library.Secret)
err := c.Bind(input)
if err != nil {
retErr := fmt.Errorf("unable to decode JSON for secret %s for %s service: %w", entry, e, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
// update secret fields if provided
input.SetName(s)
input.SetOrg(o)
input.SetRepo(n)
input.SetType(t)
input.SetUpdatedAt(time.Now().UTC().Unix())
input.SetUpdatedBy(u.GetName())
if input.Images != nil {
// update images if set
input.SetImages(unique(input.GetImages()))
}
if len(input.GetEvents()) > 0 {
input.SetEvents(unique(input.GetEvents()))
}
if input.AllowCommand != nil {
// update allow_command if set
input.SetAllowCommand(input.GetAllowCommand())
}
// check if secret is a shared secret
if strings.EqualFold(t, constants.SecretShared) {
// update the team instead of repo
input.SetTeam(n)
input.Repo = nil
}
// send API call to update the secret
err = secret.FromContext(c, e).Update(t, o, n, input)
if err != nil {
retErr := fmt.Errorf("unable to update secret %s for %s service: %w", entry, e, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
// send API call to capture the updated secret
secret, _ := secret.FromContext(c, e).Get(t, o, n, input.GetName())
c.JSON(http.StatusOK, secret.Sanitize())
}
//
// swagger:operation DELETE /api/v1/secrets/{engine}/{type}/{org}/{name}/{secret} secrets DeleteSecret
//
// Delete a secret from the configured backend
//
// ---
// produces:
// - application/json
// parameters:
// - in: path
// name: engine
// description: Secret engine to delete the secret from, eg. "native"
// required: true
// type: string
// - in: path
// name: type
// description: Secret type to delete
// enum:
// - org
// - repo
// - shared
// required: true
// type: string
// - in: path
// name: org
// description: Name of the org
// required: true
// type: string
// - in: path
// name: name
// description: Name of the repo if a repo secret, team name if a shared secret, or '*' if an org secret
// required: true
// type: string
// - in: path
// name: secret
// description: Name of the secret
// required: true
// type: string
// security:
// - ApiKeyAuth: []
// responses:
// '200':
// description: Successfully deleted the secret
// schema:
// type: string
// '500':
// description: Unable to delete the secret
// schema:
// "$ref": "#/definitions/Error"
// DeleteSecret deletes a secret from the provided secrets service.
func DeleteSecret(c *gin.Context) {
// capture middleware values
u := user.Retrieve(c)
e := util.PathParameter(c, "engine")
t := util.PathParameter(c, "type")
o := util.PathParameter(c, "org")
n := util.PathParameter(c, "name")
s := strings.TrimPrefix(util.PathParameter(c, "secret"), "/")
entry := fmt.Sprintf("%s/%s/%s/%s", t, o, n, s)
// create log fields from API metadata
fields := logrus.Fields{
"engine": e,
"org": o,
"repo": n,
"secret": s,
"type": t,
"user": u.GetName(),
}
// check if secret is a shared secret
if strings.EqualFold(t, constants.SecretShared) {
// update log fields from API metadata
fields = logrus.Fields{
"engine": e,
"org": o,
"secret": s,
"team": n,
"type": t,
"user": u.GetName(),
}
}
// update engine logger with API metadata
//
// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#Entry.WithFields
logrus.WithFields(fields).Infof("deleting secret %s from %s service", entry, e)
// send API call to remove the secret
err := secret.FromContext(c, e).Delete(t, o, n, s)
if err != nil {
retErr := fmt.Errorf("unable to delete secret %s from %s service: %w", entry, e, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
c.JSON(http.StatusOK, fmt.Sprintf("secret %s deleted from %s service", entry, e))
}
// unique is a helper function that takes a slice and
// validates that there are no duplicate entries.
func unique(stringSlice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range stringSlice {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
}