This repository has been archived by the owner on Nov 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathkv2.go
100 lines (82 loc) · 2.21 KB
/
kv2.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
package vault
import (
"encoding/json"
"fmt"
"strings"
hashivault "github.com/hashicorp/vault/api"
)
type SecretMetadata struct {
CreatedTime string `json:"created_time"`
DeletionTime string `json:"deletion_time"`
Version int
Destroyed bool
}
type KV2 struct {
client *hashivault.Client
}
type KV2GetOptions struct {
MountPath string
SecretPath string
UnmarshalInto interface{}
}
type KV2PutOptions struct {
MountPath string
SecretPath string
Secrets map[string]interface{}
}
func (k *KV2) Put(options KV2PutOptions) (*hashivault.Secret, error) {
mountPath := "secret"
if options.MountPath != "" {
mountPath = strings.Trim(options.MountPath, "/")
}
putPath := mountPath + "/data/" + strings.Trim(options.SecretPath, "/")
secret, err := k.write(putPath, options.Secrets)
if err != nil {
return nil, err
}
return secret, nil
}
func (k *KV2) Get(options KV2GetOptions) (*hashivault.Secret, error) {
mountPath := "secret"
if options.MountPath != "" {
mountPath = strings.Trim(options.MountPath, "/")
}
readPath := mountPath + "/data/" + strings.Trim(options.SecretPath, "/")
secret, err := k.read(readPath, map[string][]string{})
if err != nil {
return nil, err
}
if secret == nil {
return nil, fmt.Errorf("No secret found at path: %s/%s", mountPath, options.SecretPath)
}
if options.UnmarshalInto != nil {
dataBytes, err := json.Marshal(secret.Data["data"])
if err != nil {
return nil, err
}
if err := json.Unmarshal(dataBytes, options.UnmarshalInto); err != nil {
return nil, err
}
metadataBytes, err := json.Marshal(secret.Data["metadata"])
if err != nil {
return nil, err
}
if err := json.Unmarshal(metadataBytes, options.UnmarshalInto); err != nil {
return nil, err
}
}
return secret, nil
}
func (k *KV2) write(path string, data map[string]interface{}) (*hashivault.Secret, error) {
normalizedData := map[string]interface{}{
"data": data,
"options": map[string]interface{}{},
}
return k.client.Logical().Write(path, normalizedData)
}
func (k *KV2) read(path string, data map[string][]string) (*hashivault.Secret, error) {
if len(data) == 0 {
return k.client.Logical().Read(path)
}
return k.client.Logical().ReadWithData(path, data)
}