-
Notifications
You must be signed in to change notification settings - Fork 432
/
vault.go
337 lines (286 loc) · 8.45 KB
/
vault.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
package services
import (
"context"
"encoding/json"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
errors "github.com/rotisserie/eris"
"github.com/onsi/gomega"
"github.com/solo-io/gloo/test/services/utils"
"github.com/solo-io/gloo/test/testutils"
"github.com/solo-io/solo-kit/pkg/utils/protoutils"
v1 "github.com/solo-io/gloo/projects/gloo/pkg/api/v1"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega/gexec"
)
const (
DefaultHost = "127.0.0.1"
DefaultPort = 8200
DefaultVaultToken = "root"
vaultDockerImage = "hashicorp/vault:1.13.3"
vaultBinaryName = "vault"
)
type VaultFactory struct {
vaultPath string
tmpdir string
useTls bool
basePort uint32
}
// NewVaultFactory returns a VaultFactory
func NewVaultFactory() (*VaultFactory, error) {
tmpdir, err := os.MkdirTemp(os.Getenv("HELPER_TMP"), "vault")
if err != nil {
return nil, err
}
binaryPath, err := utils.GetBinary(utils.GetBinaryParams{
Filename: vaultBinaryName,
DockerImage: vaultDockerImage,
DockerPath: "/bin/vault",
EnvKey: testutils.VaultBinary,
TmpDir: tmpdir,
})
if err != nil {
return nil, err
}
return &VaultFactory{
vaultPath: binaryPath,
tmpdir: tmpdir,
basePort: DefaultPort,
}, nil
}
func (vf *VaultFactory) Clean() error {
if vf == nil {
return nil
}
if vf.tmpdir != "" {
os.RemoveAll(vf.tmpdir)
}
return nil
}
type VaultInstance struct {
vaultpath string
tmpdir string
cmd *exec.Cmd
session *gexec.Session
token string
hostname string
port uint32
useTls bool
customCfg string
}
func (vf *VaultFactory) MustVaultInstance() *VaultInstance {
vaultInstance, err := vf.NewVaultInstance()
gomega.Expect(err).NotTo(gomega.HaveOccurred())
return vaultInstance
}
func (vf *VaultFactory) NewVaultInstance() (*VaultInstance, error) {
// try to get an executable from docker...
tmpdir, err := os.MkdirTemp(os.Getenv("HELPER_TMP"), "vault")
if err != nil {
return nil, err
}
return &VaultInstance{
vaultpath: vf.vaultPath,
tmpdir: tmpdir,
useTls: false, // this is not used currently but we know we will need to support it soon
token: DefaultVaultToken,
hostname: DefaultHost,
port: vf.basePort,
}, nil
}
func (i *VaultInstance) Run(ctx context.Context) error {
go func() {
// Ensure the VaultInstance is cleaned up when the Run context is completed
<-ctx.Done()
i.Clean()
}()
devCmd := "-dev"
if i.useTls {
devCmd = "-dev-tls"
}
cmd := exec.Command(i.vaultpath,
"server",
// https://www.vaultproject.io/docs/concepts/dev-server
devCmd,
fmt.Sprintf("-dev-root-token-id=%s", i.token),
fmt.Sprintf("-dev-listen-address=%s", i.Host()),
)
cmd.Dir = i.tmpdir
cmd.Stdout = ginkgo.GinkgoWriter
cmd.Stderr = ginkgo.GinkgoWriter
session, err := gexec.Start(cmd, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter)
if err != nil {
return err
}
i.cmd = cmd
i.session = session
return i.waitForVaultToBeRunning()
}
func (i *VaultInstance) waitForVaultToBeRunning() error {
pingInterval := time.Tick(time.Millisecond * 100)
pingDuration := time.Second * 5
pingEndpoint := fmt.Sprintf("%s:%d", i.hostname, i.port)
ctx, cancel := context.WithTimeout(context.Background(), pingDuration)
defer cancel()
for {
select {
case <-ctx.Done():
return errors.Errorf("timed out waiting for vault on %s", pingEndpoint)
case <-pingInterval:
conn, _ := net.Dial("tcp", pingEndpoint)
if conn != nil {
conn.Close()
return nil
}
continue
}
}
}
func (i *VaultInstance) Token() string {
return i.token
}
func (i *VaultInstance) Address() string {
scheme := "http"
if i.useTls {
scheme = "https"
}
return fmt.Sprintf("%s://%s", scheme, i.Host())
}
func (i *VaultInstance) Host() string {
return fmt.Sprintf("%s:%d", i.hostname, i.port)
}
func (i *VaultInstance) EnableSecretEngine(secretEngine string) error {
_, err := i.Exec("secrets", "enable", "-version=2", fmt.Sprintf("-path=%s", secretEngine), "kv")
return err
}
func (i *VaultInstance) addAdminPolicy() error {
tmpFileName := filepath.Join(i.tmpdir, "policy.json")
err := os.WriteFile(tmpFileName, []byte(`{"path":{"*":{"capabilities":["create","read","update","delete","list","patch","sudo"]}}}`), 0666)
if err != nil {
return err
}
_, err = i.Exec("policy", "write", "admin", tmpFileName)
return err
}
func (i *VaultInstance) addAuthRole(awsAuthRole string) error {
_, err := i.Exec("write", "auth/aws/role/vault-role", "auth_type=iam", fmt.Sprintf("bound_iam_principal_arn=%s", awsAuthRole), "policies=admin")
return err
}
func (i *VaultInstance) EnableAWSCredentialsAuthMethod(settings *v1.Settings_VaultSecrets, awsAuthRole string) error {
// Enable the AWS auth method
_, err := i.Exec("auth", "enable", "aws")
if err != nil {
return err
}
// Add our admin policy
err = i.addAdminPolicy()
if err != nil {
return err
}
// Configure the AWS auth method with the creds provided
_, err = i.Exec("write", "auth/aws/config/client", fmt.Sprintf("secret_key=%s", settings.GetAws().GetSecretAccessKey()), fmt.Sprintf("access_key=%s", settings.GetAws().GetAccessKeyId()))
if err != nil {
return err
}
// Configure the Vault role to align with the provided AWS role
err = i.addAuthRole(awsAuthRole)
if err != nil {
return err
}
return nil
}
func (i *VaultInstance) EnableAWSSTSAuthMethod(awsAuthRole, serverIdHeader, stsRegion string) error {
// Enable the AWS auth method
_, err := i.Exec("auth", "enable", "aws")
if err != nil {
return err
}
// Add our admin policy
err = i.addAdminPolicy()
if err != nil {
return err
}
// Configure the AWS auth method with the sts endpoint and server id header set
stsEndpoint := fmt.Sprintf("https://sts.%s.amazonaws.com", stsRegion)
_, err = i.Exec("write", "auth/aws/config/client", fmt.Sprintf("iam_server_id_header_value=%s", serverIdHeader), fmt.Sprintf("sts_endpoint=%s", stsEndpoint), fmt.Sprintf("sts_region=%s", stsRegion))
if err != nil {
return err
}
// Configure the Vault role to align with the provided AWS role
err = i.addAuthRole(awsAuthRole)
if err != nil {
return err
}
return nil
}
// WriteSecret persists a Secret in Vault
func (i *VaultInstance) WriteSecret(secret *v1.Secret) error {
requestBuilder := testutils.DefaultRequestBuilder().
WithPostBody(i.getVaultSecretPayload(secret)).
WithPath(i.getVaultSecretPath(secret)).
WithHostname(i.hostname).
WithPort(i.port).
WithHeader("X-Vault-Token", i.token)
_, err := testutils.DefaultHttpClient.Do(requestBuilder.Build())
return err
}
// getVaultSecretPayload converts a Gloo secret into a string representing the data that will be pushed to Vault
// Mirrors the functionality in: https://github.com/solo-io/solo-kit/blob/9b38e31e4ba879b94dd5ebd925471d0c8f363565/pkg/api/v1/clients/vault/resource_client.go#L47
func (i *VaultInstance) getVaultSecretPayload(secret *v1.Secret) string {
values := make(map[string]interface{})
data, err := protoutils.MarshalMap(secret)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "can marshal secret into map")
values["data"] = data
vaultSecretBytes, err := json.Marshal(values)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "can unmarshal map into bytes")
return string(vaultSecretBytes)
}
// getVaultSecretPath returns the path where a Gloo secret will be persisted in Vault
// Mirrors the functionality in: https://github.com/solo-io/solo-kit/blob/9b38e31e4ba879b94dd5ebd925471d0c8f363565/pkg/api/v1/clients/vault/resource_client.go#L335
func (i *VaultInstance) getVaultSecretPath(secret *v1.Secret) string {
return fmt.Sprintf("v1/secret/data/gloo/gloo.solo.io/v1/Secret/%s/%s",
secret.GetMetadata().GetNamespace(), secret.GetMetadata().GetName())
}
func (i *VaultInstance) Binary() string {
return i.vaultpath
}
func (i *VaultInstance) Clean() {
if i == nil {
return
}
if i.session != nil {
i.session.Kill()
}
if i.cmd != nil && i.cmd.Process != nil {
i.cmd.Process.Kill()
}
if i.tmpdir != "" {
_ = os.RemoveAll(i.tmpdir)
}
}
func (i *VaultInstance) Exec(args ...string) (string, error) {
cmd := exec.Command(i.vaultpath, args...)
cmd.Dir = i.tmpdir
cmd.Env = os.Environ()
// disable DEBUG=1 from getting through to nomad
for e, pair := range cmd.Env {
if strings.HasPrefix(pair, "DEBUG") {
cmd.Env = append(cmd.Env[:e], cmd.Env[e+1:]...)
break
}
}
cmd.Env = append(
cmd.Env,
fmt.Sprintf("VAULT_TOKEN=%s", i.Token()),
fmt.Sprintf("VAULT_ADDR=%s", i.Address()))
out, err := cmd.CombinedOutput()
if err != nil {
err = fmt.Errorf("%s (%v)", out, err)
}
return string(out), err
}