-
Notifications
You must be signed in to change notification settings - Fork 25
/
backend_test.go
94 lines (77 loc) · 2.27 KB
/
backend_test.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
package gcpauth
import (
"context"
"os"
"strings"
"testing"
"github.com/hashicorp/go-gcp-common/gcputil"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/sdk/helper/authmetadata"
"github.com/hashicorp/vault/sdk/logical"
)
const (
googleCredentialsEnv = "GOOGLE_CREDENTIALS"
)
func testBackend(tb testing.TB) (*GcpAuthBackend, logical.Storage) {
tb.Helper()
config := logical.TestBackendConfig()
config.StorageView = new(logical.InmemStorage)
config.Logger = hclog.NewNullLogger()
b, err := Factory(context.Background(), config)
if err != nil {
tb.Fatal(err)
}
return b.(*GcpAuthBackend), config.StorageView
}
// testBackendWithCreds returns a new backend pre-populated with the
// credentials from the environment in the configuration.
func testBackendWithCreds(tb testing.TB) (*GcpAuthBackend, logical.Storage, *gcputil.GcpCredentials) {
tb.Helper()
creds := testCredentials(tb)
b, storage := testBackend(tb)
ctx := context.Background()
entry, err := logical.StorageEntryJSON("config", &gcpConfig{
Credentials: creds,
GCEAuthMetadata: authmetadata.NewHandler(gceAuthMetadataFields),
IAMAuthMetadata: authmetadata.NewHandler(iamAuthMetadataFields),
})
if err != nil {
tb.Fatal(err)
}
if err := storage.Put(ctx, entry); err != nil {
tb.Fatal(err)
}
return b, storage, creds
}
func testCredentials(tb testing.TB) *gcputil.GcpCredentials {
tb.Helper()
creds := os.Getenv(googleCredentialsEnv)
if creds == "" {
tb.Fatalf("%s must be set to JSON string of valid Google credentials file", googleCredentialsEnv)
}
credentials, err := gcputil.Credentials(creds)
if err != nil {
tb.Fatalf("valid Google credentials JSON could not be read from %s env variable: %v", googleCredentialsEnv, err)
}
return credentials
}
// testFieldValidation verifies the given path has field validation.
func testFieldValidation(tb testing.TB, op logical.Operation, pth string) {
tb.Helper()
b, storage := testBackend(tb)
ctx := context.Background()
_, err := b.HandleRequest(ctx, &logical.Request{
Storage: storage,
Operation: op,
Path: pth,
Data: map[string]interface{}{
"literally-never-a-key": true,
},
})
if err == nil {
tb.Fatal("expected error")
}
if !strings.Contains(err.Error(), "unknown field") {
tb.Error(err)
}
}