Debian Codegraph @

blob/s3blob/s3blob_test.go

raw
1 // Copyright 2018 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 s3blob
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "net/http"
22 "net/url"
23 "testing"
24
25 "github.com/aws/aws-sdk-go-v2/aws"
26 awscfg "github.com/aws/aws-sdk-go-v2/config"
27 s3manager "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
28 "github.com/aws/aws-sdk-go-v2/service/s3"
29 "github.com/aws/aws-sdk-go-v2/service/s3/types"
30 "github.com/aws/smithy-go"
31 gcaws "gocloud.dev/aws"
32 "gocloud.dev/blob"
33 "gocloud.dev/blob/driver"
34 "gocloud.dev/blob/drivertest"
35 "gocloud.dev/internal/testing/setup"
36 )
37
38 // These constants record the region & bucket used for the last --record.
39 // If you want to use --record mode,
40 // 1. Create a bucket in your AWS project from the S3 management console.
41 //
42 // https://s3.console.aws.amazon.com/s3/home.
43 //
44 // 2. Update this constant to your bucket name.
45 // TODO(issue #300): Use Terraform to provision a bucket, and get the bucket
46 //
47 // name from the Terraform output instead (saving a copy of it for replay).
48 const (
49 bucketName = "go-cloud-testing-2"
50 region = "us-west-1"
51 )
52
53 type harness struct {
54 client *s3.Client
55 opts *Options
56 rt http.RoundTripper
57 closer func()
58 }
59
60 func newHarness(ctx context.Context, t *testing.T) (drivertest.Harness, error) {
61 t.Helper()
62
63 cfg, rt, done, _ := setup.NewAWSv2Config(ctx, t, region, false)
64 return &harness{client: s3.NewFromConfig(cfg), opts: nil, rt: rt, closer: done}, nil
65 }
66
67 func newHarnessUsingLegacyList(ctx context.Context, t *testing.T) (drivertest.Harness, error) {
68 t.Helper()
69
70 cfg, rt, done, _ := setup.NewAWSv2Config(ctx, t, region, false)
71 return &harness{client: s3.NewFromConfig(cfg), opts: &Options{UseLegacyList: true}, rt: rt, closer: done}, nil
72 }
73
74 func (h *harness) HTTPClient() *http.Client {
75 return &http.Client{Transport: h.rt}
76 }
77
78 func (h *harness) MakeDriver(ctx context.Context) (driver.Bucket, error) {
79 return openBucket(ctx, h.client, bucketName, h.opts)
80 }
81
82 func (h *harness) MakeDriverForNonexistentBucket(ctx context.Context) (driver.Bucket, error) {
83 return openBucket(ctx, h.client, "go-cdk-bucket-does-not-exist", h.opts)
84 }
85
86 func (h *harness) Close() {
87 h.closer()
88 }
89
90 func TestConformance(t *testing.T) {
91 drivertest.RunConformanceTests(t, newHarness, []drivertest.AsTest{verifyContentLanguage{usingLegacyList: false}})
92 }
93
94 func TestConformanceUsingLegacyList(t *testing.T) {
95 drivertest.RunConformanceTests(t, newHarnessUsingLegacyList, []drivertest.AsTest{verifyContentLanguage{usingLegacyList: true}})
96 }
97
98 func BenchmarkS3blob(b *testing.B) {
99 ctx := context.Background()
100 cfg, err := awscfg.LoadDefaultConfig(ctx)
101 if err != nil {
102 b.Fatal(err)
103 }
104 client := s3.NewFromConfig(cfg)
105 bkt, err := OpenBucket(ctx, client, bucketName, nil)
106 if err != nil {
107 b.Fatal(err)
108 }
109 drivertest.RunBenchmarks(b, bkt)
110 }
111
112 const language = "nl"
113
114 // verifyContentLanguage uses As to access the underlying AWS types and
115 // read/write the ContentLanguage field.
116 type verifyContentLanguage struct {
117 usingLegacyList bool
118 }
119
120 func (verifyContentLanguage) Name() string {
121 return "verify ContentLanguage can be written and read through As"
122 }
123
124 func (v verifyContentLanguage) BucketCheck(b *blob.Bucket) error {
125 var client *s3.Client
126 if !b.As(&client) {
127 return errors.New("Bucket.As failed")
128 }
129 return nil
130 }
131
132 func (v verifyContentLanguage) ErrorCheck(b *blob.Bucket, err error) error {
133 var e smithy.APIError
134 if !b.ErrorAs(err, &e) {
135 return errors.New("blob.ErrorAs failed")
136 }
137 return nil
138 }
139
140 func (v verifyContentLanguage) BeforeRead(as func(any) bool) error {
141 var (
142 req *s3.GetObjectInput
143 opts *[]func(*s3.Options)
144 )
145 if !as(&req) || !as(&opts) {
146 return errors.New("BeforeRead As failed")
147 }
148 return nil
149 }
150
151 func (v verifyContentLanguage) BeforeWrite(as func(any) bool) error {
152 var (
153 req *s3.PutObjectInput
154 uploader *s3manager.Uploader
155 )
156 if !as(&req) || !as(&uploader) {
157 return errors.New("Writer.As failed for PutObjectInput")
158 }
159 req.ContentLanguage = aws.String(language)
160 var u *s3manager.Uploader
161 if !as(&u) {
162 return errors.New("Writer.As failed for Uploader")
163 }
164 return nil
165 }
166
167 func (v verifyContentLanguage) BeforeCopy(as func(any) bool) error {
168 var in *s3.CopyObjectInput
169 if !as(&in) {
170 return errors.New("BeforeCopy.As failed")
171 }
172 return nil
173 }
174
175 func (v verifyContentLanguage) BeforeList(as func(any) bool) error {
176 if v.usingLegacyList {
177 var req *s3.ListObjectsInput
178 if !as(&req) {
179 return errors.New("List.As failed")
180 }
181 } else {
182 var (
183 list *s3.ListObjectsV2Input
184 opts *[]func(*s3.Options)
185 )
186 if !as(&list) || !as(&opts) {
187 return errors.New("List.As failed")
188 }
189 return nil
190 }
191 return nil
192 }
193
194 func (v verifyContentLanguage) BeforeSign(as func(any) bool) error {
195 var (
196 get *s3.GetObjectInput
197 put *s3.PutObjectInput
198 del *s3.DeleteObjectInput
199 )
200 if as(&get) || as(&put) || as(&del) {
201 return nil
202 }
203 return errors.New("BeforeSign.As failed")
204 }
205
206 func (v verifyContentLanguage) AttributesCheck(attrs *blob.Attributes) error {
207 var hoo s3.HeadObjectOutput
208 if !attrs.As(&hoo) {
209 return errors.New("Attributes.As returned false")
210 }
211 if got := *hoo.ContentLanguage; got != language {
212 return fmt.Errorf("got %q want %q", got, language)
213 }
214 return nil
215 }
216
217 func (v verifyContentLanguage) ReaderCheck(r *blob.Reader) error {
218 var goo s3.GetObjectOutput
219 if !r.As(&goo) {
220 return errors.New("Reader.As returned false")
221 }
222 if got := *goo.ContentLanguage; got != language {
223 return fmt.Errorf("got %q want %q", got, language)
224 }
225 return nil
226 }
227
228 func (v verifyContentLanguage) ListObjectCheck(o *blob.ListObject) error {
229 if o.IsDir {
230 var commonPrefix types.CommonPrefix
231 if !o.As(&commonPrefix) {
232 return errors.New("ListObject.As for directory returned false")
233 }
234 return nil
235 }
236 var obj types.Object
237 if !o.As(&obj) {
238 return errors.New("ListObject.As for object returned false")
239 }
240 if obj.Key == nil || o.Key != *obj.Key {
241 return errors.New("ListObject.As for object returned a different item")
242 }
243 return nil
244 }
245
246 func TestOpenBucket(t *testing.T) {
247 tests := []struct {
248 description string
249 bucketName string
250 nilClient bool
251 want string
252 wantErr bool
253 }{
254 {
255 description: "empty bucket name results in error",
256 wantErr: true,
257 },
258 {
259 description: "nil client results in error",
260 bucketName: "foo",
261 nilClient: true,
262 wantErr: true,
263 },
264 {
265 description: "success",
266 bucketName: "foo",
267 want: "foo",
268 },
269 }
270
271 ctx := context.Background()
272 for _, test := range tests {
273 t.Run(test.description, func(t *testing.T) {
274 var client *s3.Client
275 if !test.nilClient {
276 cfg, _, done, _ := setup.NewAWSv2Config(ctx, t, region, false)
277 defer done()
278 client = s3.NewFromConfig(cfg)
279 }
280
281 // Create driver impl.
282 drv, err := openBucket(ctx, client, test.bucketName, nil)
283 if (err != nil) != test.wantErr {
284 t.Errorf("got err %v want error %v", err, test.wantErr)
285 }
286 if err == nil && drv != nil && drv.name != test.want {
287 t.Errorf("got %q want %q", drv.name, test.want)
288 }
289
290 // Create portable type.
291 b, err := OpenBucket(ctx, client, test.bucketName, nil)
292 if b != nil {
293 defer b.Close()
294 }
295 if (err != nil) != test.wantErr {
296 t.Errorf("got err %v want error %v", err, test.wantErr)
297 }
298 })
299 }
300 }
301
302 func TestOpenBucketFromURL(t *testing.T) {
303 tests := []struct {
304 URL string
305 WantErr bool
306 }{
307 // OK.
308 {"s3://mybucket", false},
309 // OK, setting region.
310 {"s3://mybucket?region=us-west1", false},
311 // OK, use KMS Server Side Encryption
312 {"s3://mybucket?ssetype=aws:kms&kmskeyid=arn:aws:us-east-1:12345:key/1-a-2-b", false},
313 // OK, use S3 Transfer acceleration and dual stack endpoints
314 {"s3://mybucket?accelerate=true&dualstack=true", false},
315 // OK, use FIPS endpoints
316 {"s3://mybucket?fips=true", false},
317 // OK, use S3 Transfer accleration and dual stack endpoints
318 {"s3://mybucket?accelerate=true&dualstack=true", false},
319 // OK, use use_path_style
320 {"s3://mybucket?use_path_style=true", false},
321 // OK, use s3ForcePathStyle
322 {"s3://mybucket?s3ForcePathStyle=true", false},
323 // OK, use disable_https
324 {"s3://mybucket?disable_https=true", false},
325 // OK, use FIPS endpoints
326 {"s3://mybucket?fips=true", false},
327 // OK, use anonymous.
328 {"s3://mybucket?anonymous=true", false},
329 // OK, use request checksum calculation when_supported
330 {"s3://mybucket?request_checksum_calculation=when_supported", false},
331 // OK, use request checksum calculation when_required
332 {"s3://mybucket?request_checksum_calculation=when_required", false},
333 // OK, use response checksum validation when_supported
334 {"s3://mybucket?response_checksum_validation=when_supported", false},
335 // OK, use response checksum validation when_required
336 {"s3://mybucket?response_checksum_validation=when_required", false},
337 // OK, use both checksum parameters
338 {"s3://mybucket?request_checksum_calculation=when_required&response_checksum_validation=when_supported", false},
339 // OK, case insensitive checksum parameters
340 {"s3://mybucket?request_checksum_calculation=WHEN_SUPPORTED&response_checksum_validation=When_Required", false},
341 // Invalid request checksum value
342 {"s3://mybucket?request_checksum_calculation=invalid", true},
343 // Invalid response checksum value
344 {"s3://mybucket?response_checksum_validation=invalid", true},
345 // Empty request checksum value
346 {"s3://mybucket?request_checksum_calculation=", true},
347 // Empty response checksum value
348 {"s3://mybucket?response_checksum_validation=", true},
349 // Invalid accelerate
350 {"s3://mybucket?accelerate=bogus", true},
351 // Invalid FIPS
352 {"s3://mybucket?fips=bogus", true},
353 // Invalid dualstack
354 {"s3://mybucket?dualstack=bad", true},
355 // Invalid ssetype
356 {"s3://mybucket?ssetype=aws:notkmsoraes&kmskeyid=arn:aws:us-east-1:12345:key/1-a-2-b", true},
357 // Invalid parameter together with a valid one.
358 {"s3://mybucket?profile=main&param=value", true},
359 // Invalid use_path_style
360 {"s3://mybucket?usePathStyle=bad", true},
361 // Invalid disable_https
362 {"s3://mybucket?usePathStyle=bad", true},
363 // Invalid parameter.
364 {"s3://mybucket?param=value", true},
365 }
366
367 ctx := context.Background()
368 for _, test := range tests {
369 b, err := blob.OpenBucket(ctx, test.URL)
370 if b != nil {
371 defer b.Close()
372 }
373 if (err != nil) != test.WantErr {
374 t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr)
375 }
376 }
377 }
378
379 func TestChecksumConfigurationPassthrough(t *testing.T) {
380 // Test that checksum configuration from URL parameters is properly passed through
381 // to the S3 bucket options
382 tests := []struct {
383 name string
384 url string
385 wantRequestChecksumCalculation aws.RequestChecksumCalculation
386 wantErr bool
387 }{
388 {
389 name: "request checksum when_supported",
390 url: "s3://mybucket?request_checksum_calculation=when_supported",
391 wantRequestChecksumCalculation: aws.RequestChecksumCalculationWhenSupported,
392 },
393 {
394 name: "request checksum when_required",
395 url: "s3://mybucket?request_checksum_calculation=when_required",
396 wantRequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
397 },
398 {
399 name: "case insensitive",
400 url: "s3://mybucket?request_checksum_calculation=WHEN_SUPPORTED",
401 wantRequestChecksumCalculation: aws.RequestChecksumCalculationWhenSupported,
402 },
403 {
404 name: "invalid value",
405 url: "s3://mybucket?request_checksum_calculation=invalid",
406 wantErr: true,
407 },
408 }
409
410 ctx := context.Background()
411 for _, test := range tests {
412 t.Run(test.name, func(t *testing.T) {
413 // Parse the URL to extract the bucket name and query parameters
414 u, err := url.Parse(test.url)
415 if err != nil {
416 t.Fatalf("failed to parse URL: %v", err)
417 }
418
419 // Create a mock AWS config with the query parameters
420 cfg, err := awscfg.LoadDefaultConfig(ctx)
421 if err != nil {
422 t.Fatalf("failed to load AWS config: %v", err)
423 }
424
425 // Apply URL parameters to the config
426 cfg, err = gcaws.V2ConfigFromURLParams(ctx, u.Query())
427 if (err != nil) != test.wantErr {
428 t.Errorf("got err %v want error %v", err, test.wantErr)
429 return
430 }
431 if err != nil {
432 return
433 }
434
435 // Create URLOpener to test the integration
436 opener := &URLOpener{}
437 bucket, err := opener.OpenBucketURL(ctx, u)
438 if err != nil {
439 t.Fatalf("failed to open bucket: %v", err)
440 }
441 defer bucket.Close()
442
443 // Verify that the checksum configuration was applied
444 // We can't directly access the internal bucket struct, but we can verify
445 // that the configuration was applied to the AWS config
446 if cfg.RequestChecksumCalculation != test.wantRequestChecksumCalculation {
447 t.Errorf("got RequestChecksumCalculation %v, want %v",
448 cfg.RequestChecksumCalculation, test.wantRequestChecksumCalculation)
449 }
450 })
451 }
452 }
453
454 func TestToServerSideEncryptionType(t *testing.T) {
455 tests := []struct {
456 value string
457 sseType types.ServerSideEncryption
458 expectedError error
459 }{
460 // OK.
461 {"AES256", types.ServerSideEncryptionAes256, nil},
462 // OK, KMS
463 {"aws:kms", types.ServerSideEncryptionAwsKms, nil},
464 // OK, KMS
465 {"aws:kms:dsse", types.ServerSideEncryptionAwsKmsDsse, nil},
466 // OK, AES256 mixed case
467 {"Aes256", types.ServerSideEncryptionAes256, nil},
468 // Invalid SSE type
469 {"invalid", "", fmt.Errorf("'invalid' is not a valid value for %q", sseTypeParamKey)},
470 }
471
472 for _, test := range tests {
473 sseType, err := toServerSideEncryptionType(test.value)
474 if ((err != nil) != (test.expectedError != nil)) && err.Error() != test.expectedError.Error() {
475 t.Errorf("%s: got error \"%v\", want error \"%v\"", test.value, err, test.expectedError)
476 }
477 if sseType != test.sseType {
478 t.Errorf("%s: got type %v, want type %v", test.value, sseType, test.sseType)
479 }
480 }
481 }