/
passthrough.go
331 lines (280 loc) · 9.17 KB
/
passthrough.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package kv
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/hashicorp/go-secure-stdlib/parseutil"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/jsonutil"
"github.com/hashicorp/vault/sdk/helper/wrapping"
"github.com/hashicorp/vault/sdk/logical"
)
// PassthroughBackendFactory returns a PassthroughBackend
// with leases switched off
func PassthroughBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
return LeaseSwitchedPassthroughBackend(ctx, conf, false)
}
// LeasedPassthroughBackendFactory returns a PassthroughBackend
// with leases switched on
func LeasedPassthroughBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
return LeaseSwitchedPassthroughBackend(ctx, conf, true)
}
// LeaseSwitchedPassthroughBackend returns a PassthroughBackend
// with leases switched on or off
func LeaseSwitchedPassthroughBackend(ctx context.Context, conf *logical.BackendConfig, leases bool) (logical.Backend, error) {
b := &PassthroughBackend{
generateLeases: leases,
}
backend := &framework.Backend{
BackendType: logical.TypeLogical,
Help: strings.TrimSpace(passthroughHelp),
PathsSpecial: &logical.Paths{
SealWrapStorage: []string{
"*",
},
},
Paths: []*framework.Path{
{
Pattern: framework.MatchAllRegex("path"),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixKVv1,
},
Fields: map[string]*framework.FieldSchema{
"path": {
Type: framework.TypeString,
Description: "Location of the secret.",
},
},
TakesArbitraryInput: true,
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.handleRead(),
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "read",
},
Responses: map[int][]framework.Response{
http.StatusOK: {{
Description: http.StatusText(http.StatusOK),
Fields: nil, // dynamic fields
}},
},
},
logical.CreateOperation: &framework.PathOperation{
Callback: b.handleWrite(),
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "write",
},
Responses: map[int][]framework.Response{
http.StatusNoContent: {{
Description: http.StatusText(http.StatusNoContent),
}},
},
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.handleWrite(),
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "write",
},
Responses: map[int][]framework.Response{
http.StatusNoContent: {{
Description: http.StatusText(http.StatusNoContent),
}},
},
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.handleDelete(),
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "delete",
},
Responses: map[int][]framework.Response{
http.StatusNoContent: {{
Description: http.StatusText(http.StatusNoContent),
}},
},
},
logical.ListOperation: &framework.PathOperation{
Callback: b.handleList(),
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "list",
},
},
},
ExistenceCheck: b.handleExistenceCheck(),
HelpSynopsis: strings.TrimSpace(passthroughHelpSynopsis),
HelpDescription: strings.TrimSpace(passthroughHelpDescription),
},
},
Secrets: []*framework.Secret{
{
Type: "kv",
Renew: b.handleRead(),
Revoke: func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
// This is a no-op
return nil, nil
},
},
},
}
if conf == nil {
return nil, fmt.Errorf("configuration passed into backend is nil")
}
backend.Setup(ctx, conf)
b.Backend = backend
return b, nil
}
// PassthroughBackend is used storing secrets directly into the physical
// backend. The secrets are encrypted in the durable storage and custom TTL
// information can be specified, but otherwise this backend doesn't do anything
// fancy.
type PassthroughBackend struct {
*framework.Backend
generateLeases bool
}
func (b *PassthroughBackend) handleExistenceCheck() framework.ExistenceFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
key := data.Get("path").(string)
out, err := req.Storage.Get(ctx, key)
if err != nil {
return false, fmt.Errorf("existence check failed: %w", err)
}
return out != nil, nil
}
}
func (b *PassthroughBackend) handleRead() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
key := data.Get("path").(string)
// Read the path
out, err := req.Storage.Get(ctx, key)
if err != nil {
return nil, fmt.Errorf("read failed: %w", err)
}
// Fast-path the no data case
if out == nil {
return nil, nil
}
// Decode the data
var rawData map[string]interface{}
if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil {
return nil, fmt.Errorf("json decoding failed: %w", err)
}
var resp *logical.Response
if b.generateLeases {
// Generate the response
resp = b.Secret("kv").Response(rawData, nil)
resp.Secret.Renewable = false
} else {
resp = &logical.Response{
Secret: &logical.Secret{},
Data: rawData,
}
}
// Ensure seal wrapping is carried through if the response is
// response-wrapped
if out.SealWrap {
if resp.WrapInfo == nil {
resp.WrapInfo = &wrapping.ResponseWrapInfo{}
}
resp.WrapInfo.SealWrap = out.SealWrap
}
// Check if there is a ttl key
ttlDuration := b.System().DefaultLeaseTTL()
ttlRaw, ok := rawData["ttl"]
if !ok {
ttlRaw, ok = rawData["lease"]
}
if ok {
dur, err := parseutil.ParseDurationSecond(ttlRaw)
if err == nil {
ttlDuration = dur
}
if b.generateLeases {
resp.Secret.Renewable = true
}
}
resp.Secret.TTL = ttlDuration
return resp, nil
}
}
func (b *PassthroughBackend) handleWrite() 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
}
// Check that some fields are given
if len(req.Data) == 0 {
return logical.ErrorResponse("missing data fields"), nil
}
// JSON encode the data
buf, err := json.Marshal(req.Data)
if err != nil {
return nil, fmt.Errorf("json encoding failed: %w", err)
}
// Write out a new key
entry := &logical.StorageEntry{
Key: key,
Value: buf,
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, fmt.Errorf("failed to write: %w", err)
}
kvEvent(ctx, b.Backend, "write", key, key, true, 1)
return nil, nil
}
}
func (b *PassthroughBackend) handleDelete() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
key := data.Get("path").(string)
// Delete the key at the request path
if err := req.Storage.Delete(ctx, key); err != nil {
return nil, err
}
kvEvent(ctx, b.Backend, "delete", key, "", true, 1)
return nil, nil
}
}
func (b *PassthroughBackend) handleList() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
// Right now we only handle directories, so ensure it ends with /; however,
// some physical backends may not handle the "/" case properly, so only add
// it if we're not listing the root
path := data.Get("path").(string)
if path != "" && !strings.HasSuffix(path, "/") {
path = path + "/"
}
// List the keys at the prefix given by the request
keys, err := req.Storage.List(ctx, path)
if err != nil {
return nil, err
}
// Generate the response
return logical.ListResponse(keys), nil
}
}
const passthroughHelp = `
The kv backend reads and writes arbitrary secrets to the backend.
The secrets are encrypted/decrypted by Vault: they are never stored
unencrypted in the backend and the backend never has an opportunity to
see the unencrypted value.
TTLs can be set on a per-secret basis. These TTLs will be sent down
when that secret is read, and it is assumed that some outside process will
revoke and/or replace the secret at that path.
`
const passthroughHelpSynopsis = `
Pass-through secret storage to the storage backend, allowing you to
read/write arbitrary data into secret storage.
`
const passthroughHelpDescription = `
The pass-through backend reads and writes arbitrary data into secret storage,
encrypting it along the way.
A TTL can be specified when writing with the "ttl" field. If given, the
duration of leases returned by this backend will be set to this value. This
can be used as a hint from the writer of a secret to the consumer of a secret
that the consumer should re-read the value before the TTL has expired.
However, any revocation must be handled by the user of this backend; the lease
duration does not affect the provided data in any way.
`