Debian Codegraph @

runtimevar/hashivault/hashivault.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package hashivault provides a runtimevar implementation with variables
16 // backed by HashiCorp Vault's KV Secrets Engine.
17 // Use OpenVariable to construct a *runtimevar.Variable.
18 //
19 // # URLs
20 //
21 // For runtimevar.OpenVariable, hashivault registers for the scheme "hashivault".
22 // The default URL opener will dial a Vault server using the environment variables
23 // "VAULT_SERVER_URL" (or "VAULT_ADDR") and "VAULT_SERVER_TOKEN" (or "VAULT_TOKEN").
24 // To customize the URL opener, or for more details on the URL format,
25 // see URLOpener.
26 // See https://gocloud.dev/concepts/urls/ for background information.
27 //
28 // # As
29 //
30 // hashivault exposes the following types for As:
31 // - Snapshot: *api.Secret
32 // - Error: *SecretError, *api.ResponseError
33 package hashivault // import "gocloud.dev/runtimevar/hashivault"
34
35 import (
36 "bytes"
37 "context"
38 "encoding/json"
39 "errors"
40 "fmt"
41 "net/url"
42 "os"
43 "path"
44 "strconv"
45 "sync"
46 "time"
47
48 "github.com/hashicorp/vault/api"
49 "gocloud.dev/gcerrors"
50 "gocloud.dev/internal/gcerr"
51 "gocloud.dev/runtimevar"
52 "gocloud.dev/runtimevar/driver"
53 )
54
55 func init() {
56 runtimevar.DefaultURLMux().RegisterVariable(Scheme, new(defaultDialer))
57 }
58
59 // Scheme is the URL scheme hashivault registers its URLOpener under on runtimevar.DefaultMux.
60 const Scheme = "hashivault"
61
62 // SecretError represents an error from a Vault operation.
63 type SecretError struct {
64 // Code is the error code (e.g., 404 for not found).
65 Code int
66 // Message is the error message.
67 Message string
68 }
69
70 func (e *SecretError) Error() string {
71 return fmt.Sprintf("hashivault: %s (code %d)", e.Message, e.Code)
72 }
73
74 func newNotFoundError(path string) *SecretError {
75 return &SecretError{
76 Code: 404,
77 Message: fmt.Sprintf("secret not found at path %q", path),
78 }
79 }
80
81 func newInvalidDataError(path, reason string) *SecretError {
82 return &SecretError{
83 Code: 400,
84 Message: fmt.Sprintf("invalid data at path %q: %s", path, reason),
85 }
86 }
87
88 // Config is the authentication configuration for the Vault server.
89 type Config struct {
90 // Token is the access token the Vault client uses to talk to the server.
91 // See https://www.vaultproject.io/docs/concepts/tokens.html for more
92 // information.
93 Token string
94 // APIConfig is used to configure the creation of the client.
95 APIConfig api.Config
96 }
97
98 // Dial creates a Vault API client using the provided configuration.
99 func Dial(ctx context.Context, cfg *Config) (*api.Client, error) {
100 if cfg == nil {
101 return nil, errors.New("no auth Config provided")
102 }
103 c, err := api.NewClient(&cfg.APIConfig)
104 if err != nil {
105 return nil, err
106 }
107 if cfg.Token != "" {
108 c.SetToken(cfg.Token)
109 }
110 return c, nil
111 }
112
113 func getVaultURL() (string, error) {
114 if url := os.Getenv("VAULT_SERVER_URL"); url != "" {
115 return url, nil
116 }
117 if url := os.Getenv("VAULT_ADDR"); url != "" {
118 return url, nil
119 }
120 return "", errors.New("neither VAULT_SERVER_URL nor VAULT_ADDR environment variables are set")
121 }
122
123 func getVaultToken() string {
124 if token := os.Getenv("VAULT_SERVER_TOKEN"); token != "" {
125 return token
126 }
127 if token := os.Getenv("VAULT_TOKEN"); token != "" {
128 return token
129 }
130 return ""
131 }
132
133 type defaultDialer struct {
134 init sync.Once
135 opener *URLOpener
136 err error
137 }
138
139 func (o *defaultDialer) OpenVariableURL(ctx context.Context, u *url.URL) (*runtimevar.Variable, error) {
140 o.init.Do(func() {
141 serverURL, err := getVaultURL()
142 if err != nil {
143 o.err = err
144 return
145 }
146 token := getVaultToken()
147 cfg := Config{Token: token, APIConfig: api.Config{Address: serverURL}}
148 client, err := Dial(ctx, &cfg)
149 if err != nil {
150 o.err = fmt.Errorf("failed to Dial default Vault server at %q: %v", serverURL, err)
151 return
152 }
153 o.opener = &URLOpener{Client: client}
154 })
155 if o.err != nil {
156 return nil, fmt.Errorf("open variable %v: %v", u, o.err)
157 }
158 return o.opener.OpenVariableURL(ctx, u)
159 }
160
161 // URLOpener opens Vault URLs like "hashivault://myapp/config".
162 //
163 // The URL host+path are used as the secret path.
164 //
165 // The following query parameters are supported:
166 // - decoder: The decoder to use. Defaults to runtimevar.BytesDecoder.
167 // See runtimevar.DecoderByName for supported values.
168 // - wait: The poll interval, in time.ParseDuration formats. Defaults to 30s.
169 // - engine_version: The KV engine version (1 or 2). Defaults to 2.
170 // - mount: The KV mount path. Defaults to "secret".
171 type URLOpener struct {
172 // Client must be non-nil.
173 Client *api.Client
174
175 // Decoder specifies the decoder to use if one is not specified in the URL.
176 // Defaults to runtimevar.BytesDecoder.
177 Decoder *runtimevar.Decoder
178
179 // Options specifies the options to pass to OpenVariable.
180 Options Options
181 }
182
183 // OpenVariableURL opens a hashivault Variable for u.
184 func (o *URLOpener) OpenVariableURL(ctx context.Context, u *url.URL) (*runtimevar.Variable, error) {
185 q := u.Query()
186
187 decoderName := q.Get("decoder")
188 q.Del("decoder")
189 decoder, err := runtimevar.DecoderByName(ctx, decoderName, o.Decoder)
190 if err != nil {
191 return nil, fmt.Errorf("open variable %v: invalid decoder: %v", u, err)
192 }
193
194 opts := o.Options
195
196 if s := q.Get("wait"); s != "" {
197 q.Del("wait")
198 d, err := time.ParseDuration(s)
199 if err != nil {
200 return nil, fmt.Errorf("open variable %v: invalid wait %q: %v", u, s, err)
201 }
202 opts.WaitDuration = d
203 }
204
205 if s := q.Get("engine_version"); s != "" {
206 q.Del("engine_version")
207 v, err := strconv.Atoi(s)
208 if err != nil || (v != 1 && v != 2) {
209 return nil, fmt.Errorf("open variable %v: invalid engine_version %q: must be 1 or 2", u, s)
210 }
211 opts.EngineVersion = v
212 }
213
214 if s := q.Get("mount"); s != "" {
215 q.Del("mount")
216 opts.Mount = s
217 }
218
219 for param := range q {
220 return nil, fmt.Errorf("open variable %v: invalid query parameter %q", u, param)
221 }
222
223 secretPath := path.Join(u.Host, u.Path)
224
225 return OpenVariable(o.Client, secretPath, decoder, &opts)
226 }
227
228 // Options sets options for constructing a *runtimevar.Variable backed by Vault.
229 type Options struct {
230 // WaitDuration controls the rate at which the Vault server is polled.
231 // Defaults to 30 seconds.
232 WaitDuration time.Duration
233
234 // EngineVersion specifies the KV secrets engine version.
235 // Valid values are 1 and 2. Defaults to 2 (modern KV v2).
236 EngineVersion int
237
238 // Mount is the mount path of the KV secrets engine.
239 // Defaults to "secret".
240 Mount string
241 }
242
243 // OpenVariable constructs a *runtimevar.Variable that uses client to read the
244 // variable at the given path from a Vault KV secrets engine.
245 //
246 // The path should be the path to the secret without the mount prefix or
247 // "data" segment (for KV v2). For example, "myapp/config".
248 func OpenVariable(client *api.Client, secretPath string, decoder *runtimevar.Decoder, opts *Options) (*runtimevar.Variable, error) {
249 w, err := newWatcher(client, secretPath, decoder, opts)
250 if err != nil {
251 return nil, err
252 }
253 return runtimevar.New(w), nil
254 }
255
256 func newWatcher(client *api.Client, secretPath string, decoder *runtimevar.Decoder, opts *Options) (driver.Watcher, error) {
257 if opts == nil {
258 opts = &Options{}
259 }
260
261 engineVersion := opts.EngineVersion
262 if engineVersion == 0 {
263 engineVersion = 2
264 }
265 if engineVersion != 1 && engineVersion != 2 {
266 return nil, fmt.Errorf("invalid engine_version %d; must be 1 or 2", engineVersion)
267 }
268
269 mount := opts.Mount
270 if mount == "" {
271 mount = "secret"
272 }
273
274 var fullPath string
275 if engineVersion == 2 {
276 fullPath = path.Join(mount, "data", secretPath)
277 } else {
278 fullPath = path.Join(mount, secretPath)
279 }
280
281 return &watcher{
282 client: client,
283 path: fullPath,
284 decoder: decoder,
285 wait: driver.WaitDuration(opts.WaitDuration),
286 engineVersion: engineVersion,
287 mount: mount,
288 }, nil
289 }
290
291 type state struct {
292 val any
293 raw *api.Secret
294 rawBytes []byte
295 updateTime time.Time
296 err error
297 }
298
299 // Value implements driver.State.Value.
300 func (s *state) Value() (any, error) {
301 return s.val, s.err
302 }
303
304 // UpdateTime implements driver.State.UpdateTime.
305 func (s *state) UpdateTime() time.Time {
306 return s.updateTime
307 }
308
309 // As implements driver.State.As.
310 func (s *state) As(i any) bool {
311 if s.raw == nil {
312 return false
313 }
314 p, ok := i.(**api.Secret)
315 if !ok {
316 return false
317 }
318 *p = s.raw
319 return true
320 }
321
322 func errorState(err error, prevS driver.State) driver.State {
323 s := &state{err: err}
324 if prevS == nil {
325 return s
326 }
327 prev := prevS.(*state)
328 if prev.err == nil {
329 return s
330 }
331 if equivalentError(err, prev.err) {
332 return nil
333 }
334 return s
335 }
336
337 func equivalentError(err1, err2 error) bool {
338 if err1 == err2 || err1.Error() == err2.Error() {
339 return true
340 }
341 var secErr1, secErr2 *SecretError
342 if errors.As(err1, &secErr1) && errors.As(err2, &secErr2) {
343 return secErr1.Code == secErr2.Code
344 }
345 var respErr1, respErr2 *api.ResponseError
346 if errors.As(err1, &respErr1) && errors.As(err2, &respErr2) {
347 return respErr1.StatusCode == respErr2.StatusCode
348 }
349 return false
350 }
351
352 type watcher struct {
353 client *api.Client
354 path string
355 decoder *runtimevar.Decoder
356 wait time.Duration
357 engineVersion int
358 mount string
359 }
360
361 // WatchVariable implements driver.WatchVariable.
362 func (w *watcher) WatchVariable(ctx context.Context, prev driver.State) (driver.State, time.Duration) {
363 secret, err := w.client.Logical().ReadWithContext(ctx, w.path)
364 if err != nil {
365 return errorState(err, prev), w.wait
366 }
367
368 if secret == nil {
369 return errorState(newNotFoundError(w.path), prev), w.wait
370 }
371
372 var data map[string]any
373 if w.engineVersion == 2 {
374 dataRaw, ok := secret.Data["data"]
375 if !ok {
376 return errorState(newInvalidDataError(w.path, "no data field in KV v2 response"), prev), w.wait
377 }
378 data, ok = dataRaw.(map[string]any)
379 if !ok {
380 return errorState(newInvalidDataError(w.path, "invalid data format"), prev), w.wait
381 }
382 } else {
383 data = secret.Data
384 }
385
386 var rawBytes []byte
387 if len(data) == 1 {
388 if v, ok := data["value"]; ok {
389 switch val := v.(type) {
390 case string:
391 rawBytes = []byte(val)
392 case []byte:
393 rawBytes = val
394 default:
395 rawBytes, err = json.Marshal(data)
396 if err != nil {
397 return errorState(err, prev), w.wait
398 }
399 }
400 } else {
401 rawBytes, err = json.Marshal(data)
402 if err != nil {
403 return errorState(err, prev), w.wait
404 }
405 }
406 } else {
407 rawBytes, err = json.Marshal(data)
408 if err != nil {
409 return errorState(err, prev), w.wait
410 }
411 }
412
413 if prev != nil {
414 if prevState, ok := prev.(*state); ok && bytes.Equal(rawBytes, prevState.rawBytes) {
415 return nil, w.wait
416 }
417 }
418
419 val, err := w.decoder.Decode(ctx, rawBytes)
420 if err != nil {
421 return errorState(err, prev), w.wait
422 }
423
424 return &state{
425 val: val,
426 raw: secret,
427 rawBytes: rawBytes,
428 updateTime: time.Now(),
429 }, w.wait
430 }
431
432 // Close implements driver.Close.
433 func (w *watcher) Close() error {
434 return nil
435 }
436
437 // ErrorAs implements driver.ErrorAs.
438 func (w *watcher) ErrorAs(err error, i any) bool {
439 var secErr *SecretError
440 if errors.As(err, &secErr) {
441 if p, ok := i.(**SecretError); ok {
442 *p = secErr
443 return true
444 }
445 }
446 var respErr *api.ResponseError
447 if errors.As(err, &respErr) {
448 if p, ok := i.(**api.ResponseError); ok {
449 *p = respErr
450 return true
451 }
452 }
453 return false
454 }
455
456 // ErrorCode implements driver.ErrorCode.
457 func (w *watcher) ErrorCode(err error) gcerrors.ErrorCode {
458 var secErr *SecretError
459 if errors.As(err, &secErr) {
460 switch secErr.Code {
461 case 400:
462 return gcerr.InvalidArgument
463 case 403:
464 return gcerr.PermissionDenied
465 case 404:
466 return gcerr.NotFound
467 case 429, 503:
468 return gcerr.ResourceExhausted
469 case 500, 502:
470 return gcerr.Internal
471 }
472 }
473 var respErr *api.ResponseError
474 if errors.As(err, &respErr) {
475 switch respErr.StatusCode {
476 case 400:
477 return gcerr.InvalidArgument
478 case 403:
479 return gcerr.PermissionDenied
480 case 404:
481 return gcerr.NotFound
482 case 429, 503:
483 return gcerr.ResourceExhausted
484 case 500, 502:
485 return gcerr.Internal
486 }
487 }
488 return gcerr.Unknown
489 }