-
Notifications
You must be signed in to change notification settings - Fork 592
/
vault.go
280 lines (252 loc) · 8.32 KB
/
vault.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
package config
import (
"io/ioutil"
"os"
"regexp"
"strings"
"github.com/SAP/jenkins-library/pkg/config/interpolation"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/vault"
"github.com/hashicorp/vault/api"
)
const (
vaultTestCredentialPath = "vaultTestCredentialPath"
vaultTestCredentialKeys = "vaultTestCredentialKeys"
vaultTestCredentialEnvPrefix = "PIPER_TESTCREDENTIAL_"
)
var (
vaultFilter = []string{
"vaultAppRoleID",
"vaultAppRoleSecreId",
"vaultServerUrl",
"vaultNamespace",
"vaultBasePath",
"vaultPipelineName",
"vaultPath",
"skipVault",
"vaultDisableOverwrite",
vaultTestCredentialPath,
vaultTestCredentialKeys,
}
// VaultSecretFileDirectory holds the directory for the current step run to temporarily store secret files fetched from vault
VaultSecretFileDirectory = ""
)
// VaultCredentials hold all the auth information needed to fetch configuration from vault
type VaultCredentials struct {
AppRoleID string
AppRoleSecretID string
VaultToken string
}
// vaultClient interface for mocking
type vaultClient interface {
GetKvSecret(string) (map[string]string, error)
MustRevokeToken()
}
func (s *StepConfig) mixinVaultConfig(configs ...map[string]interface{}) {
for _, config := range configs {
s.mixIn(config, vaultFilter)
}
}
func getVaultClientFromConfig(config StepConfig, creds VaultCredentials) (vaultClient, error) {
address, addressOk := config.Config["vaultServerUrl"].(string)
// if vault isn't used it's not an error
if !addressOk || creds.VaultToken == "" && (creds.AppRoleID == "" || creds.AppRoleSecretID == "") {
log.Entry().Debug("Skipping fetching secrets from vault since it is not configured")
return nil, nil
}
namespace := ""
// namespaces are only available in vault enterprise so using them should be optional
if config.Config["vaultNamespace"] != nil {
namespace = config.Config["vaultNamespace"].(string)
log.Entry().Debugf("Using vault namespace %s", namespace)
}
var client vaultClient
var err error
clientConfig := &vault.Config{Config: &api.Config{Address: address}, Namespace: namespace}
if creds.VaultToken != "" {
log.Entry().Debugf("Using Vault Token Authentication")
client, err = vault.NewClient(clientConfig, creds.VaultToken)
} else {
log.Entry().Debugf("Using Vaults AppRole Authentication")
client, err = vault.NewClientWithAppRole(clientConfig, creds.AppRoleID, creds.AppRoleSecretID)
}
if err != nil {
return nil, err
}
log.Entry().Infof("Fetching secrets from vault at %s", address)
return client, nil
}
func resolveAllVaultReferences(config *StepConfig, client vaultClient, params []StepParameters) {
for _, param := range params {
if ref := param.GetReference("vaultSecret"); ref != nil {
resolveVaultReference(ref, config, client, param)
}
if ref := param.GetReference("vaultSecretFile"); ref != nil {
resolveVaultReference(ref, config, client, param)
}
}
}
func resolveVaultReference(ref *ResourceReference, config *StepConfig, client vaultClient, param StepParameters) {
vaultDisableOverwrite, _ := config.Config["vaultDisableOverwrite"].(bool)
if _, ok := config.Config[param.Name].(string); vaultDisableOverwrite && ok {
log.Entry().Debugf("Not fetching '%s' from vault since it has already been set", param.Name)
return
}
var secretValue *string
for _, vaultPath := range ref.Paths {
// it should be possible to configure the root path were the secret is stored
vaultPath, ok := interpolation.ResolveString(vaultPath, config.Config)
if !ok {
continue
}
secretValue = lookupPath(client, vaultPath, ¶m)
if secretValue != nil {
log.Entry().Debugf("Resolved param '%s' with vault path '%s'", param.Name, vaultPath)
if ref.Type == "vaultSecret" {
config.Config[param.Name] = *secretValue
} else if ref.Type == "vaultSecretFile" {
filePath, err := createTemporarySecretFile(param.Name, *secretValue)
if err != nil {
log.Entry().WithError(err).Warnf("Couldn't create temporary secret file for '%s'", param.Name)
return
}
config.Config[param.Name] = filePath
}
break
}
}
if secretValue == nil {
log.Entry().Warnf("Could not resolve param '%s' from vault", param.Name)
}
}
// resolve test credential keys and expose as environment variables
func resolveVaultTestCredentials(config *StepConfig, client vaultClient) {
credPath, pathOk := config.Config[vaultTestCredentialPath].(string)
keys := getTestCredentialKeys(config)
if !(pathOk && keys != nil) || credPath == "" || len(keys) == 0 {
log.Entry().Debugf("Not fetching test credentials from vault since they are not (properly) configured")
return
}
lookupPath := make([]string, 3)
lookupPath[0] = "$(vaultPath)/" + credPath
lookupPath[1] = "$(vaultBasePath)/$(vaultPipelineName)/" + credPath
lookupPath[2] = "$(vaultBasePath)/GROUP-SECRETS/" + credPath
for _, path := range lookupPath {
vaultPath, ok := interpolation.ResolveString(path, config.Config)
if !ok {
continue
}
secret, err := client.GetKvSecret(vaultPath)
if err != nil {
log.Entry().WithError(err).Debugf("Couldn't fetch secret at '%s'", vaultPath)
continue
}
if secret == nil {
continue
}
secretsResolved := false
secretsResolved = populateTestCredentialsAsEnvs(secret, keys)
if secretsResolved {
// prevent overwriting resolved secrets
// only allows vault test credentials on one / the same vault path
break
}
}
}
func populateTestCredentialsAsEnvs(secret map[string]string, keys []string) (matched bool) {
for secretKey, secretValue := range secret {
for _, key := range keys {
if secretKey == key {
log.RegisterSecret(secretValue)
envVariable := vaultTestCredentialEnvPrefix + convertEnvVar(secretKey)
log.Entry().Debugf("Exposing test credential '%v' as '%v'", key, envVariable)
os.Setenv(envVariable, secretValue)
matched = true
}
}
}
return
}
func getTestCredentialKeys(config *StepConfig) []string {
keysRaw, ok := config.Config[vaultTestCredentialKeys].([]interface{})
if !ok {
log.Entry().Debugf("Not fetching test credentials from vault since they are not (properly) configured")
return nil
}
keys := make([]string, 0, len(keysRaw))
for _, keyRaw := range keysRaw {
key, ok := keyRaw.(string)
if !ok {
log.Entry().Warnf("%s is needs to be an array of strings", vaultTestCredentialKeys)
return nil
}
keys = append(keys, key)
}
return keys
}
// converts to a valid environment variable string
func convertEnvVar(s string) string {
r := strings.ToUpper(s)
r = strings.ReplaceAll(r, "-", "_")
reg, err := regexp.Compile("[^a-zA-Z0-9_]*")
if err != nil {
log.Entry().Debugf("could not compile regex of convertEnvVar: %v", err)
}
replacedString := reg.ReplaceAllString(r, "")
return replacedString
}
// RemoveVaultSecretFiles removes all secret files that have been created during execution
func RemoveVaultSecretFiles() {
if VaultSecretFileDirectory != "" {
os.RemoveAll(VaultSecretFileDirectory)
}
}
func createTemporarySecretFile(namePattern string, content string) (string, error) {
if VaultSecretFileDirectory == "" {
var err error
VaultSecretFileDirectory, err = ioutil.TempDir("", "vault")
if err != nil {
return "", err
}
}
file, err := ioutil.TempFile(VaultSecretFileDirectory, namePattern)
if err != nil {
return "", err
}
defer file.Close()
_, err = file.WriteString(content)
if err != nil {
return "", err
}
return file.Name(), nil
}
func lookupPath(client vaultClient, path string, param *StepParameters) *string {
log.Entry().Debugf("Trying to resolve vault parameter '%s' at '%s'", param.Name, path)
secret, err := client.GetKvSecret(path)
if err != nil {
log.Entry().WithError(err).Warnf("Couldn't fetch secret at '%s'", path)
return nil
}
if secret == nil {
return nil
}
field := secret[param.Name]
if field != "" {
log.RegisterSecret(field)
return &field
}
log.Entry().Debugf("Secret did not contain a field name '%s'", param.Name)
// try parameter aliases
for _, alias := range param.Aliases {
log.Entry().Debugf("Trying alias field name '%s'", alias.Name)
field := secret[alias.Name]
if field != "" {
log.RegisterSecret(field)
if alias.Deprecated {
log.Entry().WithField("package", "SAP/jenkins-library/pkg/config").Warningf("DEPRECATION NOTICE: old step config key '%s' used in vault. Please switch to '%s'!", alias.Name, param.Name)
}
return &field
}
}
return nil
}