-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolve.go
79 lines (65 loc) · 1.7 KB
/
resolve.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/reeveci/reeve-lib/schema"
)
func (p *VaultPlugin) Resolve(env []string) (map[string]schema.Env, error) {
result := make(map[string]schema.Env, len(env))
secrets := make(map[string]map[string]interface{}, len(env))
for _, key := range env {
parts := strings.Split(strings.Trim(key, "/"), "/")
var path, field string
if len(parts) == 1 {
path = key
field = "value"
} else {
path = strings.Join(parts[:len(parts)-1], "/")
field = parts[len(parts)-1]
}
secret, ok := secrets[path]
if !ok {
secret = fetchSecret(p, path)
secrets[path] = secret
}
if secret == nil {
continue
}
if value, ok := secret[field].(string); ok {
result[key] = schema.Env{
Value: value,
Priority: p.Priority,
Secret: !p.NoSecret,
}
}
}
return result, nil
}
func fetchSecret(p *VaultPlugin, path string) map[string]interface{} {
url := fmt.Sprintf("%s/v1/%s/data/%s", p.Url, strings.Trim(p.Path, "/"), url.PathEscape(path))
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
p.Log.Error(fmt.Sprintf(`fetching secret "%s" failed - %s`, path, err))
return nil
}
req.Header.Set("X-Vault-Token", p.Token)
resp, err := p.http.Do(req)
if err != nil {
p.Log.Error(fmt.Sprintf(`fetching secret "%s" failed - %s`, path, err))
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil
}
var secretResponse SecretResponse
err = json.NewDecoder(resp.Body).Decode(&secretResponse)
if err != nil {
p.Log.Error(fmt.Sprintf(`error parsing vault response for secret "%s" - %s`, path, err))
return nil
}
return secretResponse.Data.Data
}