Debian Codegraph @

internal/testing/setup/setup.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 setup // import "gocloud.dev/internal/testing/setup"
16
17 import (
18 "context"
19 "flag"
20 "net/http"
21 "os"
22 "path/filepath"
23 "testing"
24 "time"
25
26 awsv2 "github.com/aws/aws-sdk-go-v2/aws"
27 awsv2config "github.com/aws/aws-sdk-go-v2/config"
28 awsv2creds "github.com/aws/aws-sdk-go-v2/credentials"
29
30 "gocloud.dev/gcp"
31 "gocloud.dev/internal/useragent"
32
33 "github.com/google/go-replayers/grpcreplay"
34 "github.com/google/go-replayers/httpreplay"
35 hrgoog "github.com/google/go-replayers/httpreplay/google"
36 "golang.org/x/oauth2/google"
37 "google.golang.org/api/option"
38 "google.golang.org/grpc"
39 grpccreds "google.golang.org/grpc/credentials"
40 "google.golang.org/grpc/credentials/oauth"
41 )
42
43 // Record is true iff the tests are being run in "record" mode.
44 var Record = flag.Bool("record", false, "whether to run tests against cloud resources and record the interactions")
45
46 // FakeGCPCredentials gets fake GCP credentials.
47 func FakeGCPCredentials(ctx context.Context) (*google.Credentials, error) {
48 return google.CredentialsFromJSON(ctx, []byte(`{"type": "service_account", "project_id": "my-project-id"}`))
49 }
50
51 func awsV2Config(ctx context.Context, region string, client *http.Client) (awsv2.Config, error) {
52 // Provide fake creds if running in replay mode.
53 var creds awsv2.CredentialsProvider
54 if !*Record {
55 creds = awsv2creds.NewStaticCredentialsProvider("FAKE_KEY", "FAKE_SECRET", "FAKE_SESSION")
56 }
57 return awsv2config.LoadDefaultConfig(
58 ctx,
59 awsv2config.WithHTTPClient(client),
60 awsv2config.WithRegion(region),
61 awsv2config.WithCredentialsProvider(creds),
62 awsv2config.WithRetryer(func() awsv2.Retryer { return awsv2.NopRetryer{} }),
63 )
64 }
65
66 // NewRecordReplayClient creates a new http.Client for tests. This client's
67 // activity is being either recorded to files (when *Record is set) or replayed
68 // from files. rf is a modifier function that will be invoked with the address
69 // of the httpreplay.Recorder object used to obtain the client; this function
70 // can mutate the recorder to add service-specific header filters, for example.
71 // An initState is returned for tests that need a state to have deterministic
72 // results, for example, a seed to generate random sequences.
73 func NewRecordReplayClient(ctx context.Context, t *testing.T, rf func(r *httpreplay.Recorder)) (c *http.Client, cleanup func(), initState int64) {
74 t.Helper()
75
76 httpreplay.DebugHeaders()
77 path := filepath.Join("testdata", t.Name()+".replay")
78 if *Record {
79 t.Logf("Recording into golden file %s", path)
80 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
81 t.Fatal(err)
82 }
83 state := time.Now()
84 b, _ := state.MarshalBinary()
85 rec, err := httpreplay.NewRecorder(path, b)
86 if err != nil {
87 t.Fatal(err)
88 }
89 rf(rec)
90 cleanup = func() {
91 if err := rec.Close(); err != nil {
92 t.Fatal(err)
93 }
94 }
95
96 return rec.Client(), cleanup, state.UnixNano()
97 }
98 t.Logf("Replaying from golden file %s", path)
99 rep, err := httpreplay.NewReplayer(path)
100 if err != nil {
101 t.Fatal(err)
102 }
103 recState := new(time.Time)
104 if err := recState.UnmarshalBinary(rep.Initial()); err != nil {
105 t.Fatal(err)
106 }
107 return rep.Client(), func() { rep.Close() }, recState.UnixNano()
108 }
109
110 // NewAWSv2Config creates a new aws.Config for testing against AWS.
111 // If the test is in --record mode, the test will call out to AWS, and the
112 // results are recorded in a replay file.
113 // Otherwise, the session reads a replay file and runs the test as a replay,
114 // which never makes an outgoing HTTP call and uses fake credentials.
115 // An initState is returned for tests that need a state to have deterministic
116 // results, for example, a seed to generate random sequences.
117 //
118 // If scrubBody is true, the entire HTTP POST body is cleared for matching,
119 // so the tests will rely entirely on ordering and headers.
120 func NewAWSv2Config(ctx context.Context, t *testing.T, region string, scrubBody bool) (cfg awsv2.Config, rt http.RoundTripper, cleanup func(), initState int64) {
121 t.Helper()
122
123 client, cleanup, state := NewRecordReplayClient(ctx, t, func(r *httpreplay.Recorder) {
124 r.RemoveQueryParams("X-Amz-Credential", "X-Amz-Signature", "X-Amz-Security-Token")
125 r.RemoveRequestHeaders("Authorization", "Duration", "X-Amz-Security-Token")
126 r.ClearHeaders("Amz-Sdk-Invocation-Id")
127 r.ClearHeaders("X-Amz-Date")
128 r.ClearQueryParams("X-Amz-Date")
129 r.ClearHeaders("User-Agent") // AWS includes the Go version
130 // The MessageAttributes parameter is a map, and so the values are
131 // in randomized order, so we can't match against them. Just scrub
132 // them and rely on the ordering.
133 r.ScrubBody("MessageAttributes.*")
134 if scrubBody {
135 r.ScrubBody(".*")
136 }
137 })
138 cfg, err := awsV2Config(ctx, region, client)
139 if err != nil {
140 t.Fatal(err)
141 }
142 return cfg, client.Transport, cleanup, state
143 }
144
145 // NewGCPClient creates a new HTTPClient for testing against GCP.
146 //
147 // If the test is in --record mode, the client will call out to GCP, and the
148 // results are recorded in a replay file.
149 // Otherwise, the session reads a replay file and runs the test as a replay,
150 // which never makes an outgoing HTTP call and uses fake credentials.
151 func NewGCPClient(ctx context.Context, t *testing.T) (client *gcp.HTTPClient, rt http.RoundTripper, done func()) {
152 t.Helper()
153
154 c, cleanup, _ := NewRecordReplayClient(ctx, t, func(r *httpreplay.Recorder) {
155 r.ClearQueryParams("Expires")
156 r.ClearQueryParams("Signature")
157 r.ClearHeaders("Expires")
158 r.ClearHeaders("Signature")
159 r.ClearHeaders("X-Goog-Gcs-Idempotency-Token")
160 r.ClearHeaders("User-Agent")
161 })
162 transport := c.Transport
163 if *Record {
164 creds, err := gcp.DefaultCredentials(ctx)
165 if err != nil {
166 t.Fatalf("failed to get default credentials: %v", err)
167 }
168 c, err = hrgoog.RecordClient(ctx, c, option.WithTokenSource(gcp.CredentialsTokenSource(creds)))
169 if err != nil {
170 t.Fatal(err)
171 }
172 }
173 return &gcp.HTTPClient{Client: *c}, transport, cleanup
174 }
175
176 // NewGCPgRPCConn creates a new connection for testing against GCP via gRPC.
177 //
178 // If the test is in --record mode, the client will call out to GCP, and the
179 // results are recorded in a replay file.
180 // Otherwise, the session reads a replay file and runs the test as a replay,
181 // which never makes an outgoing RPC and uses fake credentials.
182 func NewGCPgRPCConn(ctx context.Context, t *testing.T, endPoint, api string) (*grpc.ClientConn, func()) {
183 t.Helper()
184
185 filename := t.Name() + ".replay"
186 if *Record {
187 opts, done := newGCPRecordDialOptions(t, filename)
188 opts = append(opts, useragent.GRPCDialOption(api))
189 // Add credentials for real RPCs.
190 creds, err := gcp.DefaultCredentials(ctx)
191 if err != nil {
192 t.Fatal(err)
193 }
194 opts = append(opts, grpc.WithTransportCredentials(grpccreds.NewClientTLSFromCert(nil, "")))
195 opts = append(opts, grpc.WithPerRPCCredentials(oauth.TokenSource{TokenSource: gcp.CredentialsTokenSource(creds)}))
196 conn, err := grpc.DialContext(ctx, endPoint, opts...)
197 if err != nil {
198 t.Fatal(err)
199 }
200 return conn, done
201 }
202 rep, done := newGCPReplayer(t, filename)
203 conn, err := rep.Connection()
204 if err != nil {
205 t.Fatal(err)
206 }
207 return conn, done
208 }
209
210 // NewAzureTestBlobClient creates a new connection for testing against Azure Blob.
211 func NewAzureTestBlobClient(ctx context.Context, t *testing.T) (*http.Client, func()) {
212 t.Helper()
213
214 client, cleanup, _ := NewRecordReplayClient(ctx, t, func(r *httpreplay.Recorder) {
215 r.RemoveQueryParams("se", "sig", "st")
216 r.RemoveQueryParams("X-Ms-Date")
217 r.ClearQueryParams("blockid")
218 r.ClearHeaders("X-Ms-Date")
219 r.ClearHeaders("X-Ms-Version")
220 r.ClearHeaders("User-Agent") // includes the full Go version
221 // Yes, it's true, Azure does not appear to be internally
222 // consistent about casing for BLock(l|L)ist.
223 r.ScrubBody("<Block(l|L)ist><Latest>.*</Latest></Block(l|L)ist>")
224 })
225 return client, cleanup
226 }
227
228 // NewAzureKeyVaultTestClient creates a *http.Client for Azure KeyVault test
229 // recordings.
230 func NewAzureKeyVaultTestClient(ctx context.Context, t *testing.T) (*http.Client, func()) {
231 t.Helper()
232
233 client, cleanup, _ := NewRecordReplayClient(ctx, t, func(r *httpreplay.Recorder) {
234 r.RemoveQueryParams("se", "sig")
235 r.RemoveQueryParams("X-Ms-Date")
236 r.ClearHeaders("X-Ms-Date")
237 r.ClearHeaders("User-Agent") // includes the full Go version
238 })
239 return client, cleanup
240 }
241
242 // FakeGCPDefaultCredentials sets up the environment with fake GCP credentials.
243 // It returns a cleanup function.
244 func FakeGCPDefaultCredentials(t *testing.T) func() {
245 t.Helper()
246
247 const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
248 jsonCred := []byte(`{"client_id": "foo.apps.googleusercontent.com", "client_secret": "bar", "refresh_token": "baz", "type": "authorized_user"}`)
249
250 f, err := os.CreateTemp(t.TempDir(), "fake-gcp-creds")
251 if err != nil {
252 t.Fatal(err)
253 }
254 if err := os.WriteFile(f.Name(), jsonCred, 0o666); err != nil {
255 t.Fatal(err)
256 }
257
258 t.Setenv(envVar, f.Name())
259 return func() {
260 t.Log("fake gcp default credentials done")
261 }
262 }
263
264 // newGCPRecordDialOptions return grpc.DialOptions that are to be appended to a
265 // GRPC dial request. These options allow a recorder to intercept RPCs and save
266 // RPCs to the file at filename, or read the RPCs from the file and return them.
267 func newGCPRecordDialOptions(t *testing.T, filename string) (opts []grpc.DialOption, done func()) {
268 t.Helper()
269
270 path := filepath.Join("testdata", filename)
271 os.MkdirAll(filepath.Dir(path), os.ModePerm)
272 t.Logf("Recording into golden file %s", path)
273 r, err := grpcreplay.NewRecorder(path, nil)
274 if err != nil {
275 t.Fatal(err)
276 }
277 opts = r.DialOptions()
278 done = func() {
279 if err := r.Close(); err != nil {
280 t.Errorf("unable to close recorder: %v", err)
281 }
282 }
283 return opts, done
284 }
285
286 // newGCPReplayer returns a Replayer for GCP gRPC connections, as well as a function
287 // to call when done with the Replayer.
288 func newGCPReplayer(t *testing.T, filename string) (*grpcreplay.Replayer, func()) {
289 t.Helper()
290
291 path := filepath.Join("testdata", filename)
292 t.Logf("Replaying from golden file %s", path)
293 r, err := grpcreplay.NewReplayer(path, nil)
294 if err != nil {
295 t.Fatal(err)
296 }
297 done := func() {
298 if err := r.Close(); err != nil {
299 t.Errorf("unable to close recorder: %v", err)
300 }
301 }
302 return r, done
303 }
304
305 // HasDockerTestEnvironment returns true when either:
306 // 1) Not on Github Actions.
307 // 2) On Github's Linux environment, where Docker is available.
308 func HasDockerTestEnvironment() bool {
309 s := os.Getenv("RUNNER_OS")
310 return s == "" || s == "Linux"
311 }