-
Notifications
You must be signed in to change notification settings - Fork 28
/
get.go
95 lines (78 loc) · 2.48 KB
/
get.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
// SPDX-License-Identifier: Apache-2.0
package vault
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/vault/api"
"github.com/sirupsen/logrus"
"github.com/go-vela/types/constants"
"github.com/go-vela/types/library"
)
// Get captures a secret.
func (c *client) Get(ctx context.Context, sType, org, name, path string) (s *library.Secret, err error) {
// create log fields from secret metadata
fields := logrus.Fields{
"org": org,
"repo": name,
"secret": path,
"type": sType,
}
// check if secret is a shared secret
if strings.EqualFold(sType, constants.SecretShared) {
// update log fields from secret metadata
fields = logrus.Fields{
"org": org,
"team": name,
"secret": path,
"type": sType,
}
}
c.Logger.WithFields(fields).Tracef("getting vault %s secret %s for %s/%s", sType, path, org, name)
//nolint:ineffassign,staticcheck // ignore false positive
vault := new(api.Secret)
// capture the secret from the Vault service
switch sType {
case constants.SecretOrg:
vault, err = c.getOrg(org, path)
case constants.SecretRepo:
vault, err = c.getRepo(org, name, path)
case constants.SecretShared:
vault, err = c.getShared(org, name, path)
default:
return nil, fmt.Errorf("invalid secret type: %v", sType)
}
if err != nil {
return nil, err
}
return secretFromVault(vault), nil
}
// getOrg is a helper function to capture
// the org secret for the provided path.
func (c *client) getOrg(org, path string) (*api.Secret, error) {
return c.get(fmt.Sprintf("%s/%s/%s/%s", c.config.Prefix, constants.SecretOrg, org, path))
}
// getRepo is a helper function to capture
// the repo secret for the provided path.
func (c *client) getRepo(org, repo, path string) (*api.Secret, error) {
return c.get(fmt.Sprintf("%s/%s/%s/%s/%s", c.config.Prefix, constants.SecretRepo, org, repo, path))
}
// getShared is a helper function to capture
// the shared secret for the provided path.
func (c *client) getShared(org, team, path string) (*api.Secret, error) {
return c.get(fmt.Sprintf("%s/%s/%s/%s/%s", c.config.Prefix, constants.SecretShared, org, team, path))
}
// get is a helper function to capture
// the secret for the provided path.
func (c *client) get(path string) (*api.Secret, error) {
// send API call to capture the secret
vault, err := c.Vault.Logical().Read(path)
if err != nil {
return nil, err
}
// return nil if secret does not exist
if vault == nil {
return nil, fmt.Errorf("secret %s does not exist", path)
}
return vault, nil
}