aboutsummaryrefslogtreecommitdiff
path: root/vault/client.go
blob: d1a6d143a244de45bacac4c8b8f25bedbe1b2cbd (plain)
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
package vault

import (
	"context"
	"fmt"
	"os"
	"path"
	"sync"
	"time"

	"github.com/hashicorp/vault/api"
	"github.com/hashicorp/vault/api/auth/approle"
	"github.com/mitchellh/mapstructure"
)

type VaultClient interface {
	LoginApproleEnv(c context.Context) error
	LoginApprole(c context.Context, roleId string, secretId string) error

	DbStaticCredential(c context.Context, suffix string) (*VaultUsernamePassword, error)
	DbCredential(c context.Context, suffix string) (*VaultUsernamePassword, error)

	KV(c context.Context, suffix string, out interface{}) (*VaultSecret, error)
	KVApiKey(c context.Context, suffix string) (*VaultApiKey, error)
	KVCredential(c context.Context, suffix string) (*VaultUsernamePassword, error)

	Destroy(HasSecret)
	Run(ctx context.Context, wg *sync.WaitGroup) error
}

type HasSecret interface {
	VaultSecret() *VaultSecret
}

// VaultSecret is an opaque reference to a secret from Vault. It is
// meant to be given to the Destroy function to check-in and destroy
// unneeded credentials. Everything returned from the client has a
// VaultSecret and implements HasSecret for that purpose. If the
// credential is not renewable then destroying it is a no-op.
type VaultSecret struct {
	s *api.Secret
	n string
}

func (s *VaultSecret) VaultSecret() *VaultSecret {
	return s
}

type VaultApiKey struct {
	Key string `json:"key"`
	s   *VaultSecret
}

func (k *VaultApiKey) VaultSecret() *VaultSecret {
	return k.s
}

type VaultUsernamePassword struct {
	Username string `json:"username"`
	Password string `json:"password"`
	s        *VaultSecret
}

func (k *VaultUsernamePassword) VaultSecret() *VaultSecret {
	return k.s
}

type Renewal struct {
	RenewedAt time.Time
	Name      string
}

type vaultClient struct {
	sync.Mutex
	c           *api.Client
	lc          *api.Logical
	wg          *sync.WaitGroup
	watcherDone chan error
	watchers    map[string]*api.LifetimeWatcher
	renewInfo   chan *Renewal
}

// NewClientEnv is a convenience function to create a new VaultClient
// based on the environment.
//
// The following environment variables are used and must be present:
//
//   VAULT_ADDR - URL to Vault server (of form https://host:port/)
//
func NewClientEnv(renewInfo chan *Renewal) (VaultClient, error) {
	vaultHost := os.Getenv("VAULT_ADDR")
	if vaultHost == "" {
		return nil, fmt.Errorf("NewClientEnv: VAULT_ADDR is not set in environment")
	}

	vc, err := NewVaultClient(vaultHost, renewInfo)
	if err != nil {
		return nil, fmt.Errorf("NewClientEnv: error creating client %w", err)
	}

	return vc, nil
}

func NewVaultClient(host string, renewInfo chan *Renewal) (VaultClient, error) {
	cfg := api.DefaultConfig()
	cfg.Address = host

	c, err := api.NewClient(cfg)
	if err != nil {
		return nil, err
	}

	return &vaultClient{
		c:           c,
		lc:          c.Logical(),
		renewInfo:   renewInfo,
		watcherDone: make(chan error, 10),
		watchers:    map[string]*api.LifetimeWatcher{},
	}, nil
}

func (c *vaultClient) watchWatcher(w *api.LifetimeWatcher, name string) {
	c.wg.Add(1)
	defer c.wg.Done()

	for {
		select {
		case err := <-w.DoneCh():
			if err != nil {
				c.watcherDone <- err
			}
			return
		case r := <-w.RenewCh():
			// Report this so consumers can do their own reporting, if not
			// provided we just read this to drain the chan and throw it away.
			if c.renewInfo != nil {
				c.renewInfo <- &Renewal{
					Name:      name,
					RenewedAt: r.RenewedAt,
				}
			}
		}
	}
}

func (c *vaultClient) addWatcher(name string, s *api.Secret) error {
	w, err := c.c.NewLifetimeWatcher(&api.LifetimeWatcherInput{
		Secret: s,
	})
	if err != nil {
		return err
	}

	c.Lock()
	c.watchers[name] = w
	c.Unlock()

	go w.Start()
	go c.watchWatcher(w, name)

	return nil
}

func (c *vaultClient) read(ctx context.Context, prefix, suffix string) (*api.Secret, string, error) {
	key := path.Join(prefix, suffix)

	s, err := c.lc.ReadWithContext(ctx, key)
	if err != nil {
		return nil, "", err
	}

	if s.Renewable {
		return s, key, c.addWatcher(key, s)
	}

	return s, key, nil
}

func (c *vaultClient) stop() {
	c.Lock()
	defer c.Unlock()

	for _, w := range c.watchers {
		w.Stop()
	}
}

func (c *vaultClient) Run(ctx context.Context, wg *sync.WaitGroup) error {
	c.Lock()
	c.wg = wg
	c.Unlock()

	c.wg.Add(1)
	defer c.wg.Done()

	for {
		select {
		case <-ctx.Done():
			c.stop()
			return nil
		case err := <-c.watcherDone:
			c.stop()
			return err
		}
	}
}

func (c *vaultClient) Destroy(s HasSecret) {
	vs := s.VaultSecret()
	if vs == nil || vs.n == "" || vs.s == nil {
		return
	}

	c.Lock()
	defer c.Unlock()

	if w, ok := c.watchers[vs.n]; ok {
		delete(c.watchers, vs.n)
		w.Stop()
	}

	// TODO: Delete dynamic credentials like DB sessions from Vault

	// Drop references to the secret so that even if the client holds on to
	// it we free the RAM.
	vs.s = nil
	vs.n = ""
}

func (c *vaultClient) LoginApprole(ctx context.Context, roleId string, secretId string) error {
	a, err := approle.NewAppRoleAuth(roleId, &approle.SecretID{FromString: secretId})
	if err != nil {
		return err
	}

	s, err := c.c.Auth().Login(ctx, a)
	if err != nil {
		return err
	}

	// This credential can not be destroyed like the others
	return c.addWatcher("login", s)
}

func (c *vaultClient) DbStaticCredential(ctx context.Context, suffix string) (*VaultUsernamePassword, error) {
	s, k, err := c.read(ctx, "database/static-creds", suffix)
	if err != nil {
		return nil, err
	}

	var d VaultUsernamePassword
	if err = mapstructure.Decode(s.Data, &d); err != nil {
		return nil, err
	}

	d.s = &VaultSecret{s: s, n: k}

	return &d, nil
}

func (c *vaultClient) DbCredential(ctx context.Context, suffix string) (*VaultUsernamePassword, error) {
	s, k, err := c.read(ctx, "database/creds", suffix)
	if err != nil {
		return nil, err
	}

	var d VaultUsernamePassword
	if err = mapstructure.Decode(s.Data, &d); err != nil {
		return nil, err
	}

	d.s = &VaultSecret{s: s, n: k}

	return &d, nil
}

func (c *vaultClient) KV(ctx context.Context, suffix string, out interface{}) (*VaultSecret, error) {
	s, k, err := c.read(ctx, "kv/data", suffix)
	if err != nil {
		return nil, err
	}

	if err = mapstructure.Decode(s.Data["data"], out); err != nil {
		return nil, err
	}

	return &VaultSecret{s: s, n: k}, nil
}

func (c *vaultClient) KVApiKey(ctx context.Context, suffix string) (*VaultApiKey, error) {
	var ak VaultApiKey
	s, err := c.KV(ctx, suffix, &ak)
	if err != nil {
		return nil, err
	}

	ak.s = s

	return &ak, nil
}

func (c *vaultClient) KVCredential(ctx context.Context, suffix string) (*VaultUsernamePassword, error) {
	var ak VaultUsernamePassword
	s, err := c.KV(ctx, suffix, &ak)
	if err != nil {
		return nil, err
	}

	ak.s = s

	return &ak, nil
}

// LoginApproleEnv is a convenience function to login using AppRole
// authentication and fetching the role id and secret id from the
// environment.
//
// The following environment variables are used and must be present:
//
//   VAULT_ROLE_ID - Role ID used for Approle authentication
//   VAULT_SECRET_ID - Secret ID used for Approle authentication
//
func (c *vaultClient) LoginApproleEnv(ctx context.Context) error {
	roleId := os.Getenv("VAULT_ROLE_ID")
	if roleId == "" {
		return fmt.Errorf("NewApproleClientEnv: VAULT_ROLE_ID is not set in environment")
	}

	secretId := os.Getenv("VAULT_SECRET_ID")
	if secretId == "" {
		return fmt.Errorf("NewApproleClientEnv: VAULT_SECRET_ID is not set in environment")
	}

	if err := c.LoginApprole(ctx, roleId, secretId); err != nil {
		return fmt.Errorf("NewApproleClientEnv: error logging in to vault %w", err)
	}

	return nil
}