forked from siva-chegondi/caddyvault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vaultstorage.go
249 lines (217 loc) · 6.1 KB
/
vaultstorage.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
package caddyvault
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"os"
"strings"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/certmagic"
"github.com/pydio/caddyvault/utils"
)
const (
defaultPrefix = "caddycerts"
dataURL = "data"
metaURL = "metadata"
)
// VaultStorage is a certmagic.Storage implementation for storing for ACME certificates
// inside an Hashicorp Vault server.
type VaultStorage struct {
// API is the vault server address, including scheme, host and port. If it is empty, module looks up for VAULT_ADDR env variable.
API string
// Prefix is the vault server store path. A secret engine **v2** must be created at this path. Defaults to 'caddycerts'.
Prefix string
// Token should generally be passed via the VAULT_TOKEN env variable, but can be set manually here.
Token string
}
func (vs *VaultStorage) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "caddy.storage.vault",
New: func() caddy.Module {
return vs
},
}
}
func init() {
caddy.RegisterModule(&VaultStorage{})
}
func (vs *VaultStorage) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
for d.Next() {
key := d.Val()
var value string
if !d.Args(&value) {
continue
}
switch key {
case "address":
if value != "" {
vs.API = value
}
case "store":
if value != "" {
vs.Prefix = value
}
case "token":
if value != "" {
utils.Token = value
}
}
}
if vs.API == "" {
if a := os.Getenv("VAULT_ADDR"); a != "" {
vs.API = a
} else {
return fmt.Errorf("unable to find Vault address. Make sure to define it in Caddyfile or in VAULT_ADDR env")
}
}
if utils.Token == "" && os.Getenv("VAULT_TOKEN") == "" {
return fmt.Errorf("unable to find Vault token. Make sure to define it in Caddyfile or in VAULT_TOKEN env")
}
return nil
}
func (vs *VaultStorage) Provision(ctx caddy.Context) error {
return nil
}
// CertMagicStorage converts vs to a certmagic.Storage instance.
func (vs *VaultStorage) CertMagicStorage() (certmagic.Storage, error) {
return vs, nil
}
func (vs *VaultStorage) buildURL(u string, key ...string) string {
pref := vs.Prefix
if pref == "" {
pref = defaultPrefix
}
ur := vs.API + "/v1/" + pref + "/" + u + "/"
if len(key) > 0 {
ur += key[0]
}
return ur
}
// List lists certificates
func (vs *VaultStorage) List(ctx context.Context, prefix string, recursive bool) ([]string, error) {
var list []string
if recursive {
list = listPath(vs.buildURL(metaURL), vs.buildURL(dataURL), prefix)
} else {
list = queryPath(vs.buildURL(dataURL), prefix)
}
if len(list) == 0 {
return list, os.ErrNotExist
}
return list, nil
}
// Load retrieves certificate of key
func (vs *VaultStorage) Load(ctx context.Context, key string) ([]byte, error) {
res := utils.QueryStore(vs.buildURL(dataURL, key))
if len(res.Data.Data) == 0 {
return []byte{}, os.ErrNotExist
}
return []byte(res.Data.Data[key].(string)), nil
}
// Store stores certificate with key association
func (vs *VaultStorage) Store(ctx context.Context, key string, value []byte) error {
data := make(map[string]string)
data[key] = string(value)
req := &utils.Request{
Data: data,
}
byteData, _ := json.Marshal(req)
response, err := utils.LoadStore(vs.buildURL(dataURL, key), byteData)
if len(response.Errors) > 0 {
return errors.New("Failed to store, error: " + response.Errors[0])
}
return err
}
// Exists returns existance of certificate with key
func (vs *VaultStorage) Exists(ctx context.Context, key string) bool {
res := utils.QueryStore(vs.buildURL(dataURL, key))
return len(res.Data.Data) > 0 && !res.Data.Metadata.Destroyed
}
// Stat retrieves status of certificate with key param
func (vs *VaultStorage) Stat(ctx context.Context, key string) (certmagic.KeyInfo, error) {
res := utils.QueryStore(vs.buildURL(dataURL, key))
_, err := vs.List(ctx, key, false)
modified, merror := time.Parse(time.RFC3339, res.Data.Metadata.CreatedTime)
return certmagic.KeyInfo{
Key: key,
IsTerminal: err == os.ErrNotExist,
Size: int64(len(res.Data.Data[key].(string))),
Modified: modified,
}, merror
}
/*
Util functions start here
listPath and queryPath
*/
func listPath(listurl, loadurl, prefix string) []string {
var list []string
var res utils.Result
// list all the keys
list = append(list, queryPath(loadurl, prefix)...)
// list all the paths and loop keys
res = utils.ListStore(listurl + prefix)
for _, path := range res.Data.Keys {
list = append(list, listPath(listurl+prefix, loadurl+prefix, "/"+path)...)
}
return list
}
func queryPath(url, prefix string) []string {
var res utils.Result
var list []string
res = utils.QueryStore(url + prefix)
for item := range res.Data.Data {
list = append(list, item)
}
return list
}
// Lock locks operations on certificate with particular key
func (vs *VaultStorage) Lock(c context.Context, key string) error {
key = key + ".lock"
if vs.Exists(c, key) {
if stat, err := vs.Stat(c, key); err == nil {
// check for deadlock, wait for 5 (300s) minutes
if time.Now().Unix()-stat.Modified.Unix() > 60 {
_ = vs.Unlock(c, key)
} else {
return errors.New("Lock already exists")
}
} else {
return err
}
}
return lockSystem(key, vs.buildURL(dataURL, key))
}
// Unlock unlocks operations on certificate data
func (vs *VaultStorage) Unlock(ctx context.Context, key string) error {
if strings.Index(key, ".lock") < 0 {
key = key + ".lock"
}
return vs.Delete(ctx, key)
}
// Delete deletes the certificate from vault.
func (vs *VaultStorage) Delete(ctx context.Context, key string) error {
response, err := utils.DeleteStore(vs.buildURL(metaURL, key))
if len(response.Errors) > 0 {
return errors.New("Failed to delete" + response.Errors[0])
}
return err
}
func lockSystem(key, lockPath string) error {
data := make(map[string]string)
data[key] = "locked"
postBody := utils.Request{
Options: utils.Options{
Cas: 0,
},
Data: data,
}
jsonData, _ := json.Marshal(postBody)
response, err := utils.LoadStore(lockPath, jsonData)
if len(response.Errors) > 0 {
return errors.New("Failed to lock: " + response.Errors[0])
}
return err
}