Debian Codegraph @

runtimevar/hashivault/hashivault_test.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
16
17 import (
18 "context"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "os"
23 "path"
24 "testing"
25 "time"
26
27 "github.com/hashicorp/vault/api"
28 "gocloud.dev/internal/testing/setup"
29 "gocloud.dev/runtimevar"
30 "gocloud.dev/runtimevar/driver"
31 "gocloud.dev/runtimevar/drivertest"
32 )
33
34 // To run these tests against a real Vault server, first run ./localvault.sh.
35 // Then wait a few seconds for the server to be ready.
36
37 const (
38 apiAddress = "http://127.0.0.1:8200"
39 testToken = "faketoken"
40 )
41
42 type harness struct {
43 client *api.Client
44 }
45
46 func (h *harness) MakeWatcher(ctx context.Context, name string, decoder *runtimevar.Decoder) (driver.Watcher, error) {
47 return newWatcher(h.client, name, decoder, nil)
48 }
49
50 func (h *harness) CreateVariable(ctx context.Context, name string, val []byte) error {
51 var data map[string]any
52 if err := json.Unmarshal(val, &data); err != nil {
53 data = map[string]any{"value": string(val)}
54 }
55 _, err := h.client.Logical().Write(path.Join("secret/data", name), map[string]any{
56 "data": data,
57 })
58 return err
59 }
60
61 func (h *harness) UpdateVariable(ctx context.Context, name string, val []byte) error {
62 return h.CreateVariable(ctx, name, val)
63 }
64
65 func (h *harness) DeleteVariable(ctx context.Context, name string) error {
66 _, err := h.client.Logical().Delete(path.Join("secret/metadata", name))
67 return err
68 }
69
70 func (h *harness) Close() {}
71
72 func (h *harness) Mutable() bool {
73 return true
74 }
75
76 func newHarness(t *testing.T) (drivertest.Harness, error) {
77 t.Helper()
78
79 if !setup.HasDockerTestEnvironment() {
80 t.Skip("Skipping Vault tests since the Vault server is not available")
81 }
82
83 ctx := context.Background()
84 c, err := Dial(ctx, &Config{
85 Token: testToken,
86 APIConfig: api.Config{
87 Address: apiAddress,
88 },
89 })
90 if err != nil {
91 return nil, err
92 }
93 c.SetClientTimeout(3 * time.Second)
94
95 _, err = c.Sys().Health()
96 if err != nil {
97 return nil, fmt.Errorf("vault server not healthy (run runtimevar/hashivault/localvault.sh): %v", err)
98 }
99
100 return &harness{client: c}, nil
101 }
102
103 func TestConformance(t *testing.T) {
104 drivertest.RunConformanceTests(t, newHarness, []drivertest.AsTest{verifyAs{}})
105 }
106
107 type verifyAs struct{}
108
109 func (verifyAs) Name() string {
110 return "verify As"
111 }
112
113 func (verifyAs) SnapshotCheck(s *runtimevar.Snapshot) error {
114 var secret *api.Secret
115 if !s.As(&secret) {
116 return errors.New("Snapshot.As failed for *api.Secret")
117 }
118 return nil
119 }
120
121 func (verifyAs) ErrorCheck(v *runtimevar.Variable, err error) error {
122 var secErr *SecretError
123 if !v.ErrorAs(err, &secErr) {
124 return errors.New("ErrorAs expected to succeed with *SecretError")
125 }
126 if secErr.Code != 404 {
127 return fmt.Errorf("expected SecretError code 404, got %d", secErr.Code)
128 }
129 return nil
130 }
131
132 func TestNoConfigError(t *testing.T) {
133 if _, err := Dial(context.Background(), nil); err == nil {
134 t.Error("got nil, want no auth Config provided")
135 }
136 }
137
138 func TestEquivalentError(t *testing.T) {
139 err1 := errors.New("error one")
140 err2 := errors.New("error one")
141 err3 := errors.New("error two")
142 respErr404 := &api.ResponseError{StatusCode: 404}
143 respErr403 := &api.ResponseError{StatusCode: 403}
144 secErr404 := &SecretError{Code: 404, Message: "not found"}
145 secErr404b := &SecretError{Code: 404, Message: "also not found"}
146 secErr400 := &SecretError{Code: 400, Message: "bad request"}
147
148 tests := []struct {
149 Err1, Err2 error
150 Want bool
151 }{
152 {Err1: err1, Err2: err2, Want: true},
153 {Err1: err1, Err2: err3, Want: false},
154 {Err1: respErr404, Err2: respErr404, Want: true},
155 {Err1: respErr404, Err2: respErr403, Want: false},
156 {Err1: err1, Err2: respErr404, Want: false},
157 {Err1: secErr404, Err2: secErr404b, Want: true},
158 {Err1: secErr404, Err2: secErr400, Want: false},
159 {Err1: secErr404, Err2: respErr404, Want: false}, // Different error types
160 }
161
162 for _, test := range tests {
163 got := equivalentError(test.Err1, test.Err2)
164 if got != test.Want {
165 t.Errorf("%v vs %v: got %v want %v", test.Err1, test.Err2, got, test.Want)
166 }
167 }
168 }
169
170 func TestWatcherErrorCode(t *testing.T) {
171 ctx := context.Background()
172 client, err := Dial(ctx, &Config{
173 Token: "fake",
174 APIConfig: api.Config{
175 Address: "http://localhost:8200",
176 },
177 })
178 if err != nil {
179 t.Fatal(err)
180 }
181
182 w, err := newWatcher(client, "test", runtimevar.StringDecoder, nil)
183 if err != nil {
184 t.Fatal(err)
185 }
186 defer w.Close()
187
188 codes := []struct {
189 Code int
190 Want string
191 }{
192 {400, "InvalidArgument"},
193 {403, "PermissionDenied"},
194 {404, "NotFound"},
195 {429, "ResourceExhausted"},
196 {500, "Internal"},
197 {502, "Internal"},
198 {503, "ResourceExhausted"},
199 {999, "Unknown"},
200 }
201
202 for _, test := range codes {
203 err := &api.ResponseError{StatusCode: test.Code}
204 code := w.ErrorCode(err)
205 if code.String() != test.Want {
206 t.Errorf("api.ResponseError StatusCode %d: got %v, want %v", test.Code, code, test.Want)
207 }
208 }
209
210 for _, test := range codes {
211 err := &SecretError{Code: test.Code, Message: "test"}
212 code := w.ErrorCode(err)
213 if code.String() != test.Want {
214 t.Errorf("SecretError Code %d: got %v, want %v", test.Code, code, test.Want)
215 }
216 }
217 }
218
219 func TestEngineVersionPaths(t *testing.T) {
220 ctx := context.Background()
221 client, err := Dial(ctx, &Config{
222 Token: "fake",
223 APIConfig: api.Config{
224 Address: "http://localhost:8200",
225 },
226 })
227 if err != nil {
228 t.Fatal(err)
229 }
230
231 tests := []struct {
232 EngineVersion int
233 Mount string
234 SecretPath string
235 WantPath string
236 }{
237 {2, "secret", "myapp/config", "secret/data/myapp/config"},
238 {1, "secret", "myapp/config", "secret/myapp/config"},
239 {2, "kv", "myapp/config", "kv/data/myapp/config"},
240 {1, "kv", "myapp/config", "kv/myapp/config"},
241 {0, "", "test", "secret/data/test"}, // defaults
242 }
243
244 for _, test := range tests {
245 opts := &Options{
246 EngineVersion: test.EngineVersion,
247 Mount: test.Mount,
248 }
249 w, err := newWatcher(client, test.SecretPath, runtimevar.StringDecoder, opts)
250 if err != nil {
251 t.Errorf("newWatcher failed: %v", err)
252 continue
253 }
254 watcher := w.(*watcher)
255 if watcher.path != test.WantPath {
256 t.Errorf("EngineVersion=%d, Mount=%q, SecretPath=%q: got path %q, want %q",
257 test.EngineVersion, test.Mount, test.SecretPath, watcher.path, test.WantPath)
258 }
259 w.Close()
260 }
261 }
262
263 func TestInvalidEngineVersion(t *testing.T) {
264 ctx := context.Background()
265 client, err := Dial(ctx, &Config{
266 Token: "fake",
267 APIConfig: api.Config{
268 Address: "http://localhost:8200",
269 },
270 })
271 if err != nil {
272 t.Fatal(err)
273 }
274
275 _, err = newWatcher(client, "test", runtimevar.StringDecoder, &Options{EngineVersion: 3})
276 if err == nil {
277 t.Error("expected error for invalid engine version")
278 }
279 }
280
281 func fakeConnectionStringInEnv() func() {
282 oldURLVal := os.Getenv("VAULT_SERVER_URL")
283 oldTokenVal := os.Getenv("VAULT_SERVER_TOKEN")
284 os.Setenv("VAULT_SERVER_URL", "http://myvaultserver")
285 os.Setenv("VAULT_SERVER_TOKEN", "faketoken")
286 return func() {
287 os.Setenv("VAULT_SERVER_URL", oldURLVal)
288 os.Setenv("VAULT_SERVER_TOKEN", oldTokenVal)
289 }
290 }
291
292 func alternativeConnectionStringEnvVars() func() {
293 oldURLVal := os.Getenv("VAULT_ADDR")
294 oldTokenVal := os.Getenv("VAULT_TOKEN")
295 os.Setenv("VAULT_ADDR", "http://myalternativevaultserver")
296 os.Setenv("VAULT_TOKEN", "faketoken2")
297 return func() {
298 os.Setenv("VAULT_ADDR", oldURLVal)
299 os.Setenv("VAULT_TOKEN", oldTokenVal)
300 }
301 }
302
303 func unsetConnectionStringEnvVars() func() {
304 oldURLVal := os.Getenv("VAULT_ADDR")
305 oldTokenVal := os.Getenv("VAULT_TOKEN")
306 oldServerURLVal := os.Getenv("VAULT_SERVER_URL")
307 oldServerTokenVal := os.Getenv("VAULT_SERVER_TOKEN")
308 os.Unsetenv("VAULT_ADDR")
309 os.Unsetenv("VAULT_TOKEN")
310 os.Unsetenv("VAULT_SERVER_URL")
311 os.Unsetenv("VAULT_SERVER_TOKEN")
312 return func() {
313 os.Setenv("VAULT_ADDR", oldURLVal)
314 os.Setenv("VAULT_SERVER_URL", oldServerURLVal)
315 os.Setenv("VAULT_TOKEN", oldTokenVal)
316 os.Setenv("VAULT_SERVER_TOKEN", oldServerTokenVal)
317 }
318 }
319
320 func TestGetVaultConnectionDetails(t *testing.T) {
321 t.Run("Test Current Env Vars", func(t *testing.T) {
322 cleanup := fakeConnectionStringInEnv()
323 defer cleanup()
324
325 serverURL, err := getVaultURL()
326 if err != nil {
327 t.Errorf("got unexpected error: %v", err)
328 }
329 if serverURL != "http://myvaultserver" {
330 t.Errorf("expected 'http://myvaultserver': got %q", serverURL)
331 }
332
333 vaultToken := getVaultToken()
334 if vaultToken != "faketoken" {
335 t.Errorf("expected 'faketoken': got %q", vaultToken)
336 }
337 })
338
339 t.Run("Test Alternative Env Vars", func(t *testing.T) {
340 cleanup := alternativeConnectionStringEnvVars()
341 defer cleanup()
342
343 serverURL, err := getVaultURL()
344 if err != nil {
345 t.Errorf("got unexpected error: %v", err)
346 }
347 if serverURL != "http://myalternativevaultserver" {
348 t.Errorf("expected 'http://myalternativevaultserver': got %q", serverURL)
349 }
350
351 vaultToken := getVaultToken()
352 if vaultToken != "faketoken2" {
353 t.Errorf("expected 'faketoken2': got %q", vaultToken)
354 }
355 })
356
357 t.Run("Test Unset Env Vars Throws Error", func(t *testing.T) {
358 cleanup := unsetConnectionStringEnvVars()
359 defer cleanup()
360
361 serverURL, err := getVaultURL()
362 if err == nil {
363 t.Errorf("expected error but got a url: %s", serverURL)
364 }
365
366 vaultToken := getVaultToken()
367 if vaultToken != "" {
368 t.Errorf("expected '': got %q", vaultToken)
369 }
370 })
371 }
372
373 func TestOpenVariableURL(t *testing.T) {
374 cleanup := fakeConnectionStringInEnv()
375 defer cleanup()
376
377 tests := []struct {
378 URL string
379 WantErr bool
380 }{
381 // OK.
382 {"hashivault://myapp/config", false},
383 // OK, setting decoder.
384 {"hashivault://myapp/config?decoder=string", false},
385 // OK, setting wait.
386 {"hashivault://myapp/config?wait=1m", false},
387 // OK, setting engine_version.
388 {"hashivault://myapp/config?engine_version=1", false},
389 {"hashivault://myapp/config?engine_version=2", false},
390 // OK, setting mount.
391 {"hashivault://myapp/config?mount=kv", false},
392 // OK, setting all.
393 {"hashivault://myapp/config?decoder=string&wait=1m&engine_version=2&mount=secret", false},
394 // Invalid decoder.
395 {"hashivault://myapp/config?decoder=notadecoder", true},
396 // Invalid wait.
397 {"hashivault://myapp/config?wait=xx", true},
398 // Invalid engine_version.
399 {"hashivault://myapp/config?engine_version=3", true},
400 {"hashivault://myapp/config?engine_version=abc", true},
401 // Invalid parameter.
402 {"hashivault://myapp/config?param=value", true},
403 }
404
405 ctx := context.Background()
406 for _, test := range tests {
407 t.Run(test.URL, func(t *testing.T) {
408 v, err := runtimevar.OpenVariable(ctx, test.URL)
409 if (err != nil) != test.WantErr {
410 t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr)
411 }
412 if err == nil {
413 if err := v.Close(); err != nil {
414 t.Errorf("%s: got error during close: %v", test.URL, err)
415 }
416 }
417 })
418 }
419 }