forked from hashicorp/vault-plugin-secrets-kv
/
path_data.go
457 lines (383 loc) · 12.8 KB
/
path_data.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package kv
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/locksutil"
"github.com/hashicorp/vault/sdk/logical"
"github.com/mitchellh/mapstructure"
)
// pathConfig returns the path configuration for CRUD operations on the backend
// configuration.
func pathData(b *versionedKVBackend) *framework.Path {
return &framework.Path{
Pattern: "data/" + framework.MatchAllRegex("path"),
Fields: map[string]*framework.FieldSchema{
"path": {
Type: framework.TypeString,
Description: "Location of the secret.",
},
"version": {
Type: framework.TypeInt,
Description: "If provided during a read, the value at the version number will be returned",
},
"options": {
Type: framework.TypeMap,
Description: `Options for writing a KV entry.
Set the "cas" value to use a Check-And-Set operation. If not set the write will
be allowed. If set to 0 a write will only be allowed if the key doesn’t exist.
If the index is non-zero the write will only be allowed if the key’s current
version matches the version specified in the cas parameter.`,
},
"data": {
Type: framework.TypeMap,
Description: "The contents of the data map will be stored and returned on read.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.upgradeCheck(b.pathDataWrite()),
logical.CreateOperation: b.upgradeCheck(b.pathDataWrite()),
logical.ReadOperation: b.upgradeCheck(b.pathDataRead()),
logical.DeleteOperation: b.upgradeCheck(b.pathDataDelete()),
},
ExistenceCheck: b.dataExistenceCheck(),
HelpSynopsis: dataHelpSyn,
HelpDescription: dataHelpDesc,
}
}
func (b *versionedKVBackend) dataExistenceCheck() framework.ExistenceFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
key := data.Get("path").(string)
meta, err := b.getKeyMetadata(ctx, req.Storage, key)
if err != nil {
// If we are returning a readonly error it means we are attempting
// to write the policy for the first time. This means no data exists
// yet and we can safely return false here.
if strings.Contains(err.Error(), logical.ErrReadOnly.Error()) {
return false, nil
}
return false, err
}
return meta != nil, nil
}
}
// pathDataRead handles read commands to a kv entry
func (b *versionedKVBackend) pathDataRead() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
key := data.Get("path").(string)
lock := locksutil.LockForKey(b.locks, key)
lock.RLock()
defer lock.RUnlock()
meta, err := b.getKeyMetadata(ctx, req.Storage, key)
if err != nil {
return nil, err
}
if meta == nil {
return nil, nil
}
verNum := meta.CurrentVersion
verParam := data.Get("version").(int)
if verParam > 0 {
verNum = uint64(verParam)
}
// If there is no version with that number, return
vm := meta.Versions[verNum]
if vm == nil {
return nil, nil
}
resp := &logical.Response{
Data: map[string]interface{}{
"data": nil,
"metadata": map[string]interface{}{
"version": verNum,
"created_time": ptypesTimestampToString(vm.CreatedTime),
"deletion_time": ptypesTimestampToString(vm.DeletionTime),
"destroyed": vm.Destroyed,
},
},
}
// If the version has been deleted return metadata with a 404
if vm.DeletionTime != nil {
deletionTime, err := ptypes.Timestamp(vm.DeletionTime)
if err != nil {
return nil, err
}
if deletionTime.Before(time.Now()) {
return logical.RespondWithStatusCode(resp, req, http.StatusNotFound)
}
}
// If the version has been destroyed return metadata with a 404
if vm.Destroyed {
return logical.RespondWithStatusCode(resp, req, http.StatusNotFound)
}
versionKey, err := b.getVersionKey(ctx, key, verNum, req.Storage)
if err != nil {
return nil, err
}
raw, err := req.Storage.Get(ctx, versionKey)
if err != nil {
return nil, err
}
if raw == nil {
return nil, errors.New("could not find version data")
}
version := &Version{}
if err := proto.Unmarshal(raw.Value, version); err != nil {
return nil, err
}
vData := map[string]interface{}{}
if err := json.Unmarshal(version.Data, &vData); err != nil {
return nil, err
}
resp.Data["data"] = vData
return resp, nil
}
}
// pathDataWrite handles create and update commands to a kv entry
func (b *versionedKVBackend) pathDataWrite() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
key := data.Get("path").(string)
if key == "" {
return logical.ErrorResponse("missing path"), nil
}
config, err := b.config(ctx, req.Storage)
if err != nil {
return nil, err
}
// Parse data, this can happen before the lock so we can fail early if
// not set.
var marshaledData []byte
{
dataRaw, ok := data.GetOk("data")
if !ok {
return logical.ErrorResponse("no data provided"), logical.ErrInvalidRequest
}
marshaledData, err = json.Marshal(dataRaw.(map[string]interface{}))
if err != nil {
return nil, err
}
}
lock := locksutil.LockForKey(b.locks, key)
lock.Lock()
defer lock.Unlock()
meta, err := b.getKeyMetadata(ctx, req.Storage, key)
if err != nil {
return nil, err
}
if meta == nil {
meta = &KeyMetadata{
Key: key,
Versions: map[uint64]*VersionMetadata{},
}
}
// Parse options
{
var casRaw interface{}
var casOk bool
optionsRaw, ok := data.GetOk("options")
if ok {
options := optionsRaw.(map[string]interface{})
// Verify the CAS parameter is valid.
casRaw, casOk = options["cas"]
}
switch {
case casOk:
var cas int
if err := mapstructure.WeakDecode(casRaw, &cas); err != nil {
return logical.ErrorResponse("error parsing check-and-set parameter"), logical.ErrInvalidRequest
}
if uint64(cas) != meta.CurrentVersion {
return logical.ErrorResponse("check-and-set parameter did not match the current version"), logical.ErrInvalidRequest
}
case config.CasRequired, meta.CasRequired:
return logical.ErrorResponse("check-and-set parameter required for this call"), logical.ErrInvalidRequest
}
}
// Create a version key for the new version
versionKey, err := b.getVersionKey(ctx, key, meta.CurrentVersion+1, req.Storage)
if err != nil {
return nil, err
}
version := &Version{
Data: marshaledData,
CreatedTime: ptypes.TimestampNow(),
}
ctime, err := ptypes.Timestamp(version.CreatedTime)
if err != nil {
return logical.ErrorResponse("unexpected error converting %T(%v) to time.Time: %v", version.CreatedTime, version.CreatedTime, err), logical.ErrInvalidRequest
}
if !config.IsDeleteVersionAfterDisabled() {
if dtime, ok := deletionTime(ctime, deleteVersionAfter(config), deleteVersionAfter(meta)); ok {
dt, err := ptypes.TimestampProto(dtime)
if err != nil {
return logical.ErrorResponse("error setting deletion_time: converting %v to protobuf: %v", dtime, err), logical.ErrInvalidRequest
}
version.DeletionTime = dt
}
}
buf, err := proto.Marshal(version)
if err != nil {
return nil, err
}
// Write the new version
if err := req.Storage.Put(ctx, &logical.StorageEntry{
Key: versionKey,
Value: buf,
}); err != nil {
return nil, err
}
vm, versionToDelete := meta.AddVersion(version.CreatedTime, version.DeletionTime, config.MaxVersions)
err = b.writeKeyMetadata(ctx, req.Storage, meta)
if err != nil {
return nil, err
}
// We create the response here so we can add warnings to it below.
resp := &logical.Response{
Data: map[string]interface{}{
"version": meta.CurrentVersion,
"created_time": ptypesTimestampToString(vm.CreatedTime),
"deletion_time": ptypesTimestampToString(vm.DeletionTime),
"destroyed": vm.Destroyed,
},
}
// Cleanup the version data that is past max version.
if versionToDelete > 0 {
// Create a list of version keys to delete. We will delete from the
// back of the array so we can delete the oldest versions
// first. If there is an error deleting one of the keys we can
// ensure the rest will be deleted on the next go around.
var versionKeysToDelete []string
for i := versionToDelete; i > 0; i-- {
versionKey, err := b.getVersionKey(ctx, key, i, req.Storage)
if err != nil {
resp.AddWarning(fmt.Sprintf("Error occured when cleaning up old versions, these will be cleaned up on next write: %s", err))
return resp, nil
}
// We intentionally do not return these errors here. If the get
// or delete fail they will be cleaned up on the next write.
v, err := req.Storage.Get(ctx, versionKey)
if err != nil {
resp.AddWarning(fmt.Sprintf("Error occured when cleaning up old versions, these will be cleaned up on next write: %s", err))
return resp, nil
}
if v == nil {
break
}
// append to the end of the list
versionKeysToDelete = append(versionKeysToDelete, versionKey)
}
// Walk the list backwards deleting the oldest versions first. This
// allows us to continue the cleanup on next write if an error
// occurs during one of the deletes.
for i := len(versionKeysToDelete) - 1; i >= 0; i-- {
err := req.Storage.Delete(ctx, versionKeysToDelete[i])
if err != nil {
resp.AddWarning(fmt.Sprintf("Error occured when cleaning up old versions, these will be cleaned up on next write: %s", err))
break
}
}
}
return resp, nil
}
}
func (b *versionedKVBackend) pathDataDelete() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
key := data.Get("path").(string)
lock := locksutil.LockForKey(b.locks, key)
lock.Lock()
defer lock.Unlock()
meta, err := b.getKeyMetadata(ctx, req.Storage, key)
if err != nil {
return nil, err
}
if meta == nil {
return nil, nil
}
// If there is no latest version, or the latest version is already
// deleted or destroyed return
lv := meta.Versions[meta.CurrentVersion]
if lv == nil || lv.Destroyed {
return nil, nil
}
if lv.DeletionTime != nil {
deletionTime, err := ptypes.Timestamp(lv.DeletionTime)
if err != nil {
return nil, err
}
if deletionTime.Before(time.Now()) {
return nil, nil
}
}
lv.DeletionTime = ptypes.TimestampNow()
err = b.writeKeyMetadata(ctx, req.Storage, meta)
if err != nil {
return nil, err
}
return nil, nil
}
}
// AddVersion adds a version to the key metadata and moves the sliding window of
// max versions. It returns the newly added version and the version to delete
// from storage.
func (k *KeyMetadata) AddVersion(createdTime, deletionTime *timestamp.Timestamp, configMaxVersions uint32) (*VersionMetadata, uint64) {
if k.Versions == nil {
k.Versions = map[uint64]*VersionMetadata{}
}
vm := &VersionMetadata{
CreatedTime: createdTime,
DeletionTime: deletionTime,
}
k.CurrentVersion++
k.Versions[k.CurrentVersion] = vm
k.UpdatedTime = createdTime
if k.CreatedTime == nil {
k.CreatedTime = createdTime
}
var maxVersions uint32
switch {
case max(k.MaxVersions, configMaxVersions) > 0:
maxVersions = max(k.MaxVersions, configMaxVersions)
default:
maxVersions = defaultMaxVersions
}
if uint32(k.CurrentVersion-k.OldestVersion) >= maxVersions {
versionToDelete := k.CurrentVersion - uint64(maxVersions)
// We need to do a loop here in the event that max versions has
// changed and we need to delete more than one entry.
for i := k.OldestVersion; i < versionToDelete+1; i++ {
delete(k.Versions, i)
}
k.OldestVersion = versionToDelete + 1
return vm, versionToDelete
}
return vm, 0
}
func max(a, b uint32) uint32 {
if b > a {
return b
}
return a
}
const dataHelpSyn = `Write, Read, and Delete data in the Key-Value Store.`
const dataHelpDesc = `
This path takes a key name and based on the opperation stores, retreives or
deletes versions of data.
If a write operation is used the endpoint takes an options object and a data
object. The options object is used to pass some options to the write command and
the data object is encrypted and stored in the storage backend. Each write
operation for a key creates a new version and does not overwrite the previous
data.
A read operation will return the latest version for a key unless the "version"
parameter is set, then it returns the version at that number.
Delete operations are a soft delete. They will mark the latest version as
deleted, but the underlying data will not be fully removed. Delete operations
can be undone.
`