-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathreadSecret.go
74 lines (59 loc) · 1.8 KB
/
readSecret.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
package vault
import (
"encoding/json"
"fmt"
"strings"
)
const keyNotFound = "the key '%s' was not found in the path '%s': %v"
const secretNotFound = "the secret '%s' was not found: %v"
// ReadSecret from Vault
func (client *API) ReadSecret(path string) (map[string]interface{}, error) {
secretValues, err := client.Client.Logical().Read(path)
if secretValues == nil {
return nil, fmt.Errorf(secretNotFound, path, err)
}
secretData := secretValues.Data["data"]
if secretData == nil {
secretData = secretValues.Data
}
// Will append data to path and retry if "data" is empty and warnings is present
// if path contains data and warnings an error is returned
if fmt.Sprintf("%s", secretValues.Data) == fmt.Sprintf("%s", make(map[string]interface{})) {
if len(secretValues.Warnings) > 0 {
splitPath := strings.Split(path, "/")
if splitPath[1] == "data" {
return nil, fmt.Errorf("%s", strings.Join(secretValues.Warnings, ","))
}
appendData := []string{splitPath[0], "data"}
pathWithData := append(appendData, splitPath[1:]...)
return client.ReadSecret(strings.Join(pathWithData, "/"))
}
return nil, fmt.Errorf("no data recieved")
}
b, err := json.Marshal(secretData)
if err != nil {
return nil, err
}
var f interface{}
err = json.Unmarshal(b, &f)
if err != nil {
return nil, fmt.Errorf("unable to unmarshal response from Vault")
}
myMap := f.(map[string]interface{})
return myMap, nil
}
// ReadSecretKey from Vault
func (client *API) ReadSecretKey(path string, key string) (interface{}, error) {
secret, err := client.ReadSecret(path)
if secret == nil {
return "", fmt.Errorf(keyNotFound, key, path, err)
}
if err != nil {
return "", err
}
secretKey := secret[key]
if secretKey == nil {
return "", fmt.Errorf(keyNotFound, key, path, err)
}
return secretKey, nil
}