Debian Codegraph @

runtimevar/gcpsecretmanager/gcpsecretmanager_test.go

raw
1 // Copyright 2020 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 gcpsecretmanager
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "testing"
22
23 secretmanager "cloud.google.com/go/secretmanager/apiv1"
24 "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
25 "gocloud.dev/internal/gcerr"
26 "gocloud.dev/internal/testing/setup"
27 "gocloud.dev/runtimevar"
28 "gocloud.dev/runtimevar/driver"
29 "gocloud.dev/runtimevar/drivertest"
30 "google.golang.org/api/option"
31 "google.golang.org/grpc/codes"
32 "google.golang.org/grpc/status"
33 )
34
35 // This constant records the project used for the last --record.
36 // If you want to use --record mode,
37 // 1. Update this constant to your GCP project ID.
38 // 2. Ensure that the "Secret Manager API" is enabled for your project.
39 // TODO(issue #300): Use Terraform to get this.
40 const projectID = "go-cloud-test-216917"
41
42 func secretKey(secretID string) string {
43 return "projects/" + projectID + "/secrets/" + secretID
44 }
45
46 type harness struct {
47 client *secretmanager.Client
48 closer func()
49 }
50
51 func newHarness(t *testing.T) (drivertest.Harness, error) {
52 t.Helper()
53
54 ctx := context.Background()
55 conn, done := setup.NewGCPgRPCConn(ctx, t, "secretmanager.googleapis.com:443", "runtimevar")
56
57 client, err := secretmanager.NewClient(ctx, option.WithGRPCConn(conn))
58 if err != nil {
59 return nil, err
60 }
61
62 return &harness{
63 client: client,
64 closer: func() {
65 _ = client.Close()
66 done()
67 },
68 }, nil
69 }
70
71 func (h *harness) MakeWatcher(_ context.Context, name string, decoder *runtimevar.Decoder) (driver.Watcher, error) {
72 return newWatcher(h.client, secretKey(name), decoder, nil)
73 }
74
75 func (h *harness) CreateVariable(ctx context.Context, name string, val []byte) error {
76 _, err := h.client.CreateSecret(ctx, &secretmanagerpb.CreateSecretRequest{
77 Parent: "projects/" + projectID,
78 SecretId: name,
79 Secret: &secretmanagerpb.Secret{
80 Replication: &secretmanagerpb.Replication{
81 Replication: &secretmanagerpb.Replication_Automatic_{
82 Automatic: &secretmanagerpb.Replication_Automatic{},
83 },
84 },
85 Labels: map[string]string{
86 "project": "runtimevar",
87 },
88 },
89 })
90 if err != nil {
91 return err
92 }
93
94 // Add initial secret version.
95 _, err = h.client.AddSecretVersion(ctx, &secretmanagerpb.AddSecretVersionRequest{
96 Parent: secretKey(name),
97 Payload: &secretmanagerpb.SecretPayload{Data: val},
98 })
99
100 return err
101 }
102
103 func (h *harness) UpdateVariable(ctx context.Context, name string, val []byte) error {
104 _, err := h.client.AddSecretVersion(ctx, &secretmanagerpb.AddSecretVersionRequest{
105 Parent: secretKey(name),
106 Payload: &secretmanagerpb.SecretPayload{Data: val},
107 })
108
109 return err
110 }
111
112 func (h *harness) DeleteVariable(ctx context.Context, name string) error {
113 return h.client.DeleteSecret(ctx, &secretmanagerpb.DeleteSecretRequest{Name: secretKey(name)})
114 }
115
116 func (h *harness) Close() {
117 h.closer()
118 }
119
120 func (h *harness) Mutable() bool { return true }
121
122 func TestConformance(t *testing.T) {
123 drivertest.RunConformanceTests(t, newHarness, []drivertest.AsTest{verifyAs{}})
124 }
125
126 type verifyAs struct{}
127
128 func (verifyAs) Name() string {
129 return "verify As"
130 }
131
132 func (verifyAs) SnapshotCheck(s *runtimevar.Snapshot) error {
133 var v *secretmanagerpb.AccessSecretVersionResponse
134 if !s.As(&v) {
135 return errors.New("Snapshot.As failed")
136 }
137 return nil
138 }
139
140 func (verifyAs) ErrorCheck(v *runtimevar.Variable, err error) error {
141 var s *status.Status
142 if !v.ErrorAs(err, &s) {
143 return errors.New("runtimevar.ErrorAs failed")
144 }
145 return nil
146 }
147
148 // Secretmanager-specific tests.
149
150 func TestEquivalentError(t *testing.T) {
151 tests := []struct {
152 Err1, Err2 error
153 Want bool
154 }{
155 {Err1: errors.New("not grpc"), Err2: errors.New("not grpc"), Want: true},
156 {Err1: errors.New("not grpc"), Err2: errors.New("not grpc but different")},
157 {Err1: errors.New("not grpc"), Err2: status.Errorf(codes.Internal, "fail")},
158 {Err1: status.Errorf(codes.Internal, "fail"), Err2: status.Errorf(codes.InvalidArgument, "fail")},
159 {Err1: status.Errorf(codes.Internal, "fail"), Err2: status.Errorf(codes.Internal, "fail"), Want: true},
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 TestNoConnectionError(t *testing.T) {
171 ctx := context.Background()
172 creds, err := setup.FakeGCPCredentials(ctx)
173 if err != nil {
174 t.Fatal(err)
175 }
176
177 // Connect to the Secret Manager service.
178 client, cleanup, err := Dial(ctx, creds.TokenSource)
179 if err != nil {
180 t.Fatal(err)
181 }
182 defer cleanup()
183
184 key := SecretKey("gcp-project-id", "secret-name")
185 v, err := OpenVariable(client, key, nil, nil)
186 if err != nil {
187 t.Fatal(err)
188 }
189 defer func() {
190 if err := v.Close(); err != nil {
191 t.Error(err)
192 }
193 }()
194
195 _, err = v.Watch(ctx)
196 if err == nil {
197 t.Error("got nil want error")
198 }
199 }
200
201 func TestOpenVariable(t *testing.T) {
202 cleanup := setup.FakeGCPDefaultCredentials(t)
203 defer cleanup()
204
205 tests := []struct {
206 URL string
207 WantErr bool
208 }{
209 // OK.
210 {"gcpsecretmanager://projects/myproject/secrets/mysecret", false},
211 // OK, hierarchical key name.
212 {"gcpsecretmanager://projects/myproject/secrets/mysecret2", false},
213 // OK, setting decoder.
214 {"gcpsecretmanager://projects/myproject/secrets/mysecret?decoder=string", false},
215 // Missing projects prefix.
216 {"gcpsecretmanager://project/myproject/secrets/mysecret", true},
217 // Missing project.
218 {"gcpsecretmanager://projects//secrets/mysecret", true},
219 // Missing configs.
220 {"gcpsecretmanager://projects/myproject/mysecret", true},
221 // Missing secretID with trailing slash.
222 {"gcpsecretmanager://projects/myproject/secrets/", true},
223 // Missing secretID.
224 {"gcpsecretmanager://projects/myproject/secrets", true},
225 // Invalid decoder.
226 {"gcpsecretmanager://projects/myproject/secrets/mysecret?decoder=notadecoder", true},
227 // Invalid param.
228 {"gcpsecretmanager://projects/myproject/secrets/mysecret?param=value", true},
229 // Setting wait.
230 {"gcpsecretmanager://projects/myproject/secrets/mysecret?wait=1m", false},
231 // Invalid wait.
232 {"gcpsecretmanager://projects/myproject/secrets/mysecret?wait=xx", true},
233 }
234
235 ctx := context.Background()
236 for _, test := range tests {
237 if err := openVariable(ctx, test.URL); (err != nil) != test.WantErr {
238 t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr)
239 }
240 }
241 }
242
243 func openVariable(ctx context.Context, URL string) (err error) {
244 var v *runtimevar.Variable
245 v, err = runtimevar.OpenVariable(ctx, URL)
246 defer func() {
247 if v == nil {
248 return
249 }
250
251 if closeErr := v.Close(); closeErr != nil {
252 if grpcErr, ok := closeErr.(*gcerr.Error); ok && grpcErr.Code != gcerr.Canceled {
253 err = fmt.Errorf("close failed: %v. prev error: %v", closeErr, err)
254 }
255 }
256 }()
257
258 return err
259 }