forked from googleapis/google-cloud-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
integration_test.go
5588 lines (5008 loc) · 178 KB
/
integration_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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package storage
import (
"bytes"
"compress/gzip"
"context"
"crypto"
"crypto/md5"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"log"
"math"
"math/rand"
"mime/multipart"
"net/http"
"net/http/httputil"
"os"
"sort"
"strconv"
"strings"
"testing"
"time"
"cloud.google.com/go/httpreplay"
"cloud.google.com/go/iam"
"cloud.google.com/go/iam/apiv1/iampb"
"cloud.google.com/go/internal/testutil"
"cloud.google.com/go/internal/uid"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/googleapis/gax-go/v2/apierror"
"golang.org/x/oauth2/google"
"google.golang.org/api/googleapi"
"google.golang.org/api/iterator"
itesting "google.golang.org/api/iterator/testing"
"google.golang.org/api/option"
"google.golang.org/api/transport"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type skipTransportTestKey string
const (
testPrefix = "go-integration-test"
replayFilename = "storage.replay"
// TODO(jba): move to testutil, factor out from firestore/integration_test.go.
envFirestoreProjID = "GCLOUD_TESTS_GOLANG_FIRESTORE_PROJECT_ID"
envFirestorePrivateKey = "GCLOUD_TESTS_GOLANG_FIRESTORE_KEY"
grpcTestPrefix = "golang-grpc-test"
)
var (
record = flag.Bool("record", false, "record RPCs")
uidSpace *uid.Space
uidSpaceObjects *uid.Space
bucketName string
grpcBucketName string
// Use our own random number generator to isolate the sequence of random numbers from
// other packages. This makes it possible to use HTTP replay and draw the same sequence
// of numbers as during recording.
rng *rand.Rand
newTestClient func(ctx context.Context, opts ...option.ClientOption) (*Client, error)
replaying bool
testTime time.Time
)
func TestMain(m *testing.M) {
grpc.EnableTracing = true
cleanup := initIntegrationTest()
cleanupEmulatorClients := initEmulatorClients()
exit := m.Run()
if err := cleanup(); err != nil {
// Don't fail the test if cleanup fails.
log.Printf("Post-test cleanup failed: %v", err)
}
if err := cleanupEmulatorClients(); err != nil {
// Don't fail the test if cleanup fails.
log.Printf("Post-test cleanup failed for emulator clients: %v", err)
}
os.Exit(exit)
}
// If integration tests will be run, create a unique bucket for them.
// Also, set newTestClient to handle record/replay.
// Return a cleanup function.
func initIntegrationTest() func() error {
flag.Parse() // needed for testing.Short()
switch {
case testing.Short() && *record:
log.Fatal("cannot combine -short and -record")
return nil
case testing.Short() && httpreplay.Supported() && testutil.CanReplay(replayFilename) && testutil.ProjID() != "":
// go test -short with a replay file will replay the integration tests, if
// the appropriate environment variables have been set.
replaying = true
httpreplay.DebugHeaders()
replayer, err := httpreplay.NewReplayer(replayFilename)
if err != nil {
log.Fatal(err)
}
var t time.Time
if err := json.Unmarshal(replayer.Initial(), &t); err != nil {
log.Fatal(err)
}
initUIDsAndRand(t)
newTestClient = func(ctx context.Context, _ ...option.ClientOption) (*Client, error) {
hc, err := replayer.Client(ctx) // no creds needed
if err != nil {
return nil, err
}
return NewClient(ctx, option.WithHTTPClient(hc))
}
log.Printf("replaying from %s", replayFilename)
return func() error { return replayer.Close() }
case testing.Short():
// go test -short without a replay file skips the integration tests.
if testutil.CanReplay(replayFilename) && testutil.ProjID() != "" {
log.Print("replay not supported for Go versions before 1.8")
}
newTestClient = nil
return func() error { return nil }
default: // Run integration tests against a real backend.
now := time.Now().UTC()
initUIDsAndRand(now)
var cleanup func() error
if *record && httpreplay.Supported() {
// Remember the time for replay.
nowBytes, err := json.Marshal(now)
if err != nil {
log.Fatal(err)
}
recorder, err := httpreplay.NewRecorder(replayFilename, nowBytes)
if err != nil {
log.Fatalf("could not record: %v", err)
}
newTestClient = func(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
hc, err := recorder.Client(ctx, opts...)
if err != nil {
return nil, err
}
return NewClient(ctx, option.WithHTTPClient(hc))
}
cleanup = func() error {
err1 := cleanupBuckets()
err2 := recorder.Close()
if err1 != nil {
return err1
}
return err2
}
log.Printf("recording to %s", replayFilename)
} else {
if *record {
log.Print("record not supported for Go versions before 1.8")
}
newTestClient = NewClient
cleanup = cleanupBuckets
}
ctx := context.Background()
client, err := newTestClient(ctx)
if err != nil {
log.Fatalf("NewClient: %v", err)
}
if client == nil {
return func() error { return nil }
}
defer client.Close()
if err := client.Bucket(bucketName).Create(ctx, testutil.ProjID(), nil); err != nil {
log.Fatalf("creating bucket %q: %v", bucketName, err)
}
if err := client.Bucket(grpcBucketName).Create(ctx, testutil.ProjID(), nil); err != nil {
log.Fatalf("creating bucket %q: %v", grpcBucketName, err)
}
return cleanup
}
}
func initUIDsAndRand(t time.Time) {
uidSpace = uid.NewSpace("", &uid.Options{Time: t, Short: true})
bucketName = testPrefix + uidSpace.New()
uidSpaceObjects = uid.NewSpace("obj", &uid.Options{Time: t})
grpcBucketName = grpcTestPrefix + uidSpace.New()
// Use our own random source, to avoid other parts of the program taking
// random numbers from the global source and putting record and replay
// out of sync.
rng = testutil.NewRand(t)
testTime = t
}
// testConfig returns the Client used to access GCS. testConfig skips
// the current test if credentials are not available or when being run
// in Short mode.
func testConfig(ctx context.Context, t *testing.T, opts ...option.ClientOption) *Client {
if testing.Short() && !replaying {
t.Skip("Integration tests skipped in short mode")
}
client, err := newTestClient(ctx, opts...)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
if client == nil {
t.Skip("Integration tests skipped. See CONTRIBUTING.md for details")
}
return client
}
// testConfigGPRC returns a gRPC-based client to access GCS. testConfigGRPC
// skips the curent test when being run in Short mode.
func testConfigGRPC(ctx context.Context, t *testing.T, opts ...option.ClientOption) (gc *Client) {
if testing.Short() {
t.Skip("Integration tests skipped in short mode")
}
gc, err := newGRPCClient(ctx, opts...)
if err != nil {
t.Fatalf("newHybridClient: %v", err)
}
return
}
// initTransportClients initializes Storage clients for each supported transport.
func initTransportClients(ctx context.Context, t *testing.T, opts ...option.ClientOption) map[string]*Client {
withJSON := append(opts, WithJSONReads())
return map[string]*Client{
"http": testConfig(ctx, t, opts...),
"grpc": testConfigGRPC(ctx, t, opts...),
// TODO: remove jsonReads when support for XML reads is dropped
"jsonReads": testConfig(ctx, t, withJSON...),
}
}
// multiTransportTest initializes fresh clients for each transport, then runs
// given testing function using each transport-specific client, supplying the
// test function with the sub-test instance, the context it was given, the name
// of an existing bucket to use, a bucket name to use for bucket creation, and
// the client to use.
func multiTransportTest(ctx context.Context, t *testing.T,
test func(*testing.T, context.Context, string, string, *Client),
opts ...option.ClientOption) {
for transport, client := range initTransportClients(ctx, t, opts...) {
t.Run(transport, func(t *testing.T) {
t.Cleanup(func() {
client.Close()
})
if reason := ctx.Value(skipTransportTestKey(transport)); reason != nil {
t.Skip("transport", fmt.Sprintf("%q", transport), "explicitly skipped:", reason)
}
bucket := bucketName
prefix := testPrefix
if transport == "grpc" {
bucket = grpcBucketName
prefix = grpcTestPrefix
}
test(t, ctx, bucket, prefix, client)
})
}
}
func TestIntegration_BucketCreateDelete(t *testing.T) {
ctx := skipJSONReads(context.Background(), "no reads in test")
multiTransportTest(ctx, t, func(t *testing.T, ctx context.Context, _ string, prefix string, client *Client) {
projectID := testutil.ProjID()
labels := map[string]string{
"l1": "v1",
"empty": "",
}
lifecycle := Lifecycle{
Rules: []LifecycleRule{{
Action: LifecycleAction{
Type: SetStorageClassAction,
StorageClass: "NEARLINE",
},
Condition: LifecycleCondition{
AgeInDays: 10,
Liveness: Archived,
CreatedBefore: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
MatchesStorageClasses: []string{"STANDARD"},
NumNewerVersions: 3,
},
}, {
Action: LifecycleAction{
Type: SetStorageClassAction,
StorageClass: "ARCHIVE",
},
Condition: LifecycleCondition{
CustomTimeBefore: time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC),
DaysSinceCustomTime: 20,
Liveness: Live,
MatchesStorageClasses: []string{"STANDARD"},
},
}, {
Action: LifecycleAction{
Type: DeleteAction,
},
Condition: LifecycleCondition{
DaysSinceNoncurrentTime: 30,
Liveness: Live,
NoncurrentTimeBefore: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
MatchesStorageClasses: []string{"NEARLINE"},
NumNewerVersions: 10,
},
}, {
Action: LifecycleAction{
Type: DeleteAction,
},
Condition: LifecycleCondition{
AgeInDays: 10,
MatchesPrefix: []string{"testPrefix"},
MatchesSuffix: []string{"testSuffix"},
NumNewerVersions: 3,
},
}, {
Action: LifecycleAction{
Type: DeleteAction,
},
Condition: LifecycleCondition{
AllObjects: true,
},
}},
}
// testedAttrs are the bucket attrs directly compared in this test
type testedAttrs struct {
StorageClass string
VersioningEnabled bool
LocationType string
Labels map[string]string
Location string
Lifecycle Lifecycle
CustomPlacementConfig *CustomPlacementConfig
}
for _, test := range []struct {
name string
attrs *BucketAttrs
wantAttrs testedAttrs
}{
{
name: "no attrs",
attrs: nil,
wantAttrs: testedAttrs{
StorageClass: "STANDARD",
VersioningEnabled: false,
LocationType: "multi-region",
Location: "US",
},
},
{
name: "with attrs",
attrs: &BucketAttrs{
StorageClass: "NEARLINE",
VersioningEnabled: true,
Labels: labels,
Lifecycle: lifecycle,
Location: "SOUTHAMERICA-EAST1",
},
wantAttrs: testedAttrs{
StorageClass: "NEARLINE",
VersioningEnabled: true,
Labels: labels,
Location: "SOUTHAMERICA-EAST1",
LocationType: "region",
Lifecycle: lifecycle,
},
},
{
name: "dual-region",
attrs: &BucketAttrs{
Location: "US",
CustomPlacementConfig: &CustomPlacementConfig{
DataLocations: []string{"US-EAST1", "US-WEST1"},
},
},
wantAttrs: testedAttrs{
Location: "US",
LocationType: "dual-region",
StorageClass: "STANDARD",
CustomPlacementConfig: &CustomPlacementConfig{
DataLocations: []string{"US-EAST1", "US-WEST1"},
},
},
},
} {
t.Run(test.name, func(t *testing.T) {
newBucketName := prefix + uidSpace.New()
b := client.Bucket(newBucketName)
if err := b.Create(ctx, projectID, test.attrs); err != nil {
t.Fatalf("bucket create: %v", err)
}
gotAttrs, err := b.Attrs(ctx)
if err != nil {
t.Fatalf("bucket attrs: %v", err)
}
// All newly created buckets should conform to the following:
if gotAttrs.MetaGeneration != 1 {
t.Errorf("metageneration: got %d, should be 1", gotAttrs.MetaGeneration)
}
if gotAttrs.ProjectNumber == 0 {
t.Errorf("got a zero ProjectNumber")
}
// Test specific wanted bucket attrs
if gotAttrs.VersioningEnabled != test.wantAttrs.VersioningEnabled {
t.Errorf("versioning enabled: got %t, want %t", gotAttrs.VersioningEnabled, test.wantAttrs.VersioningEnabled)
}
if got, want := gotAttrs.Labels, test.wantAttrs.Labels; !testutil.Equal(got, want) {
t.Errorf("labels: got %v, want %v", got, want)
}
if diff := cmp.Diff(gotAttrs.Lifecycle, test.wantAttrs.Lifecycle); diff != "" {
t.Errorf("lifecycle: diff got vs. want: %v", diff)
}
if gotAttrs.LocationType != test.wantAttrs.LocationType {
t.Errorf("location type: got %s, want %s", gotAttrs.LocationType, test.wantAttrs.LocationType)
}
if gotAttrs.StorageClass != test.wantAttrs.StorageClass {
t.Errorf("storage class: got %s, want %s", gotAttrs.StorageClass, test.wantAttrs.StorageClass)
}
if gotAttrs.Location != test.wantAttrs.Location {
t.Errorf("location: got %s, want %s", gotAttrs.Location, test.wantAttrs.Location)
}
if got, want := gotAttrs.CustomPlacementConfig, test.wantAttrs.CustomPlacementConfig; !testutil.Equal(got, want) {
t.Errorf("customPlacementConfig: \ngot\t%v\nwant\t%v", got, want)
}
// Delete the bucket and check that the deletion was succesful
if err := b.Delete(ctx); err != nil {
t.Fatalf("bucket delete: %v", err)
}
_, err = b.Attrs(ctx)
if err != ErrBucketNotExist {
t.Fatalf("expected ErrBucketNotExist, got %v", err)
}
})
}
})
}
func TestIntegration_BucketLifecycle(t *testing.T) {
ctx := skipJSONReads(context.Background(), "no reads in test")
multiTransportTest(ctx, t, func(t *testing.T, ctx context.Context, _ string, prefix string, client *Client) {
h := testHelper{t}
wantLifecycle := Lifecycle{
Rules: []LifecycleRule{
{
Action: LifecycleAction{Type: AbortIncompleteMPUAction},
Condition: LifecycleCondition{AgeInDays: 30},
},
{
Action: LifecycleAction{Type: DeleteAction},
Condition: LifecycleCondition{AllObjects: true},
},
},
}
bucket := client.Bucket(prefix + uidSpace.New())
// Create bucket with lifecycle rules
h.mustCreate(bucket, testutil.ProjID(), &BucketAttrs{
Lifecycle: wantLifecycle,
})
defer h.mustDeleteBucket(bucket)
attrs := h.mustBucketAttrs(bucket)
if !testutil.Equal(attrs.Lifecycle, wantLifecycle) {
t.Fatalf("got %v, want %v", attrs.Lifecycle, wantLifecycle)
}
// Remove lifecycle rules
ua := BucketAttrsToUpdate{Lifecycle: &Lifecycle{}}
attrs = h.mustUpdateBucket(bucket, ua, attrs.MetaGeneration)
if !testutil.Equal(attrs.Lifecycle, Lifecycle{}) {
t.Fatalf("got %v, want %v", attrs.Lifecycle, Lifecycle{})
}
// Update bucket with a lifecycle rule
ua = BucketAttrsToUpdate{Lifecycle: &wantLifecycle}
attrs = h.mustUpdateBucket(bucket, ua, attrs.MetaGeneration)
if !testutil.Equal(attrs.Lifecycle, wantLifecycle) {
t.Fatalf("got %v, want %v", attrs.Lifecycle, wantLifecycle)
}
})
}
func TestIntegration_BucketUpdate(t *testing.T) {
ctx := skipJSONReads(context.Background(), "no reads in test")
multiTransportTest(ctx, t, func(t *testing.T, ctx context.Context, _ string, prefix string, client *Client) {
h := testHelper{t}
b := client.Bucket(prefix + uidSpace.New())
h.mustCreate(b, testutil.ProjID(), nil)
defer h.mustDeleteBucket(b)
attrs := h.mustBucketAttrs(b)
if attrs.VersioningEnabled {
t.Fatal("bucket should not have versioning by default")
}
if len(attrs.Labels) > 0 {
t.Fatal("bucket should not have labels initially")
}
// Turn on versioning, add some labels.
ua := BucketAttrsToUpdate{VersioningEnabled: true}
ua.SetLabel("l1", "v1")
ua.SetLabel("empty", "")
attrs = h.mustUpdateBucket(b, ua, attrs.MetaGeneration)
if !attrs.VersioningEnabled {
t.Fatal("should have versioning now")
}
wantLabels := map[string]string{
"l1": "v1",
"empty": "",
}
if !testutil.Equal(attrs.Labels, wantLabels) {
t.Fatalf("add labels: got %v, want %v", attrs.Labels, wantLabels)
}
// Turn off versioning again; add and remove some more labels.
ua = BucketAttrsToUpdate{VersioningEnabled: false}
ua.SetLabel("l1", "v2") // update
ua.SetLabel("new", "new") // create
ua.DeleteLabel("empty") // delete
ua.DeleteLabel("absent") // delete non-existent
attrs = h.mustUpdateBucket(b, ua, attrs.MetaGeneration)
if attrs.VersioningEnabled {
t.Fatal("should have versioning off")
}
wantLabels = map[string]string{
"l1": "v2",
"new": "new",
}
if !testutil.Equal(attrs.Labels, wantLabels) {
t.Fatalf("got %v, want %v", attrs.Labels, wantLabels)
}
// Configure a lifecycle
wantLifecycle := Lifecycle{
Rules: []LifecycleRule{
{
Action: LifecycleAction{Type: "Delete"},
Condition: LifecycleCondition{
AgeInDays: 30,
MatchesPrefix: []string{"testPrefix"},
MatchesSuffix: []string{"testSuffix"},
},
},
},
}
ua = BucketAttrsToUpdate{Lifecycle: &wantLifecycle}
attrs = h.mustUpdateBucket(b, ua, attrs.MetaGeneration)
if !testutil.Equal(attrs.Lifecycle, wantLifecycle) {
t.Fatalf("got %v, want %v", attrs.Lifecycle, wantLifecycle)
}
// Check that StorageClass has "STANDARD" value for unset field by default
// before passing new value.
wantStorageClass := "STANDARD"
if !testutil.Equal(attrs.StorageClass, wantStorageClass) {
t.Fatalf("got %v, want %v", attrs.StorageClass, wantStorageClass)
}
wantStorageClass = "NEARLINE"
ua = BucketAttrsToUpdate{StorageClass: wantStorageClass}
attrs = h.mustUpdateBucket(b, ua, attrs.MetaGeneration)
if !testutil.Equal(attrs.StorageClass, wantStorageClass) {
t.Fatalf("got %v, want %v", attrs.StorageClass, wantStorageClass)
}
})
}
func TestIntegration_BucketPolicyOnly(t *testing.T) {
ctx := skipJSONReads(context.Background(), "no reads in test")
multiTransportTest(ctx, t, func(t *testing.T, ctx context.Context, _ string, prefix string, client *Client) {
h := testHelper{t}
bkt := client.Bucket(prefix + uidSpace.New())
h.mustCreate(bkt, testutil.ProjID(), nil)
defer h.mustDeleteBucket(bkt)
// Insert an object with custom ACL.
o := bkt.Object("bucketPolicyOnly")
defer func() {
if err := o.Delete(ctx); err != nil {
log.Printf("failed to delete test object: %v", err)
}
}()
wc := o.NewWriter(ctx)
wc.ContentType = "text/plain"
h.mustWrite(wc, []byte("test"))
a := o.ACL()
aclEntity := ACLEntity("user-test@example.com")
err := a.Set(ctx, aclEntity, RoleReader)
if err != nil {
t.Fatalf("set ACL failed: %v", err)
}
// Enable BucketPolicyOnly.
ua := BucketAttrsToUpdate{BucketPolicyOnly: &BucketPolicyOnly{Enabled: true}}
attrs := h.mustUpdateBucket(bkt, ua, h.mustBucketAttrs(bkt).MetaGeneration)
if got, want := attrs.BucketPolicyOnly.Enabled, true; got != want {
t.Fatalf("got %v, want %v", got, want)
}
if got := attrs.BucketPolicyOnly.LockedTime; got.IsZero() {
t.Fatal("got a zero time value, want a populated value")
}
// Confirm BucketAccessControl returns error, since we cannot get legacy ACL
// for a bucket that has uniform bucket-level access.
// Metadata updates may be delayed up to 10s. Since we expect an error from
// this call, we retry on a nil error until we get the non-retryable error
// that we are expecting.
ctxWithTimeout, cancelCtx := context.WithTimeout(ctx, time.Second*10)
b := bkt.Retryer(WithErrorFunc(retryOnNilAndTransientErrs))
_, err = b.ACL().List(ctxWithTimeout)
cancelCtx()
if err == nil {
t.Errorf("ACL.List: expected bucket ACL list to fail")
}
// Confirm ObjectAccessControl returns error, for same reason as above.
ctxWithTimeout, cancelCtx = context.WithTimeout(ctx, time.Second*10)
_, err = o.Retryer(WithErrorFunc(retryOnNilAndTransientErrs)).ACL().List(ctxWithTimeout)
cancelCtx()
if err == nil {
t.Errorf("ACL.List: expected object ACL list to fail")
}
// Disable BucketPolicyOnly.
ua = BucketAttrsToUpdate{BucketPolicyOnly: &BucketPolicyOnly{Enabled: false}}
attrs = h.mustUpdateBucket(bkt, ua, attrs.MetaGeneration)
if got, want := attrs.BucketPolicyOnly.Enabled, false; got != want {
t.Fatalf("attrs.BucketPolicyOnly.Enabled: got %v, want %v", got, want)
}
// Check that the object ACL rules are the same.
// Metadata updates may be delayed up to 10s. Before that, we can get a 400
// indicating that uniform bucket-level access is still enabled in HTTP.
// We need to retry manually as GRPC will not error but provide empty ACL.
var acl []ACLRule
err = retry(ctx, func() error {
var err error
acl, err = o.ACL().List(ctx)
if err != nil {
return fmt.Errorf("ACL.List: object ACL list failed: %v", err)
}
return nil
}, func() error {
if !containsACLRule(acl, entityRoleACL{aclEntity, RoleReader}) {
return fmt.Errorf("containsACL: expected ACL %v to include custom ACL entity %v", acl, entityRoleACL{aclEntity, RoleReader})
}
return nil
})
if err != nil {
t.Fatal(err)
}
})
}
func TestIntegration_UniformBucketLevelAccess(t *testing.T) {
ctx := skipJSONReads(context.Background(), "no reads in test")
multiTransportTest(ctx, t, func(t *testing.T, ctx context.Context, _ string, prefix string, client *Client) {
h := testHelper{t}
bkt := client.Bucket(prefix + uidSpace.New())
h.mustCreate(bkt, testutil.ProjID(), nil)
defer h.mustDeleteBucket(bkt)
// Insert an object with custom ACL.
o := bkt.Object("uniformBucketLevelAccess")
defer func() {
if err := o.Delete(ctx); err != nil {
log.Printf("failed to delete test object: %v", err)
}
}()
wc := o.NewWriter(ctx)
wc.ContentType = "text/plain"
h.mustWrite(wc, []byte("test"))
a := o.ACL()
aclEntity := ACLEntity("user-test@example.com")
err := a.Set(ctx, aclEntity, RoleReader)
if err != nil {
t.Fatalf("set ACL failed: %v", err)
}
// Enable UniformBucketLevelAccess.
ua := BucketAttrsToUpdate{UniformBucketLevelAccess: &UniformBucketLevelAccess{Enabled: true}}
attrs := h.mustUpdateBucket(bkt, ua, h.mustBucketAttrs(bkt).MetaGeneration)
if got, want := attrs.UniformBucketLevelAccess.Enabled, true; got != want {
t.Fatalf("got %v, want %v", got, want)
}
if got := attrs.UniformBucketLevelAccess.LockedTime; got.IsZero() {
t.Fatal("got a zero time value, want a populated value")
}
// Confirm BucketAccessControl returns error.
// We retry on nil to account for propagation delay in metadata update.
ctxWithTimeout, cancelCtx := context.WithTimeout(ctx, time.Second*10)
b := bkt.Retryer(WithErrorFunc(retryOnNilAndTransientErrs))
_, err = b.ACL().List(ctxWithTimeout)
cancelCtx()
if err == nil {
t.Errorf("ACL.List: expected bucket ACL list to fail")
}
// Confirm ObjectAccessControl returns error.
ctxWithTimeout, cancelCtx = context.WithTimeout(ctx, time.Second*10)
_, err = o.Retryer(WithErrorFunc(retryOnNilAndTransientErrs)).ACL().List(ctxWithTimeout)
cancelCtx()
if err == nil {
t.Errorf("ACL.List: expected object ACL list to fail")
}
// Disable UniformBucketLevelAccess.
ua = BucketAttrsToUpdate{UniformBucketLevelAccess: &UniformBucketLevelAccess{Enabled: false}}
attrs = h.mustUpdateBucket(bkt, ua, attrs.MetaGeneration)
if got, want := attrs.UniformBucketLevelAccess.Enabled, false; got != want {
t.Fatalf("got %v, want %v", got, want)
}
// Metadata updates may be delayed up to 10s. Before that, we can get a 400
// indicating that uniform bucket-level access is still enabled in HTTP.
// We need to retry manually as GRPC will not error but provide empty ACL.
var acl []ACLRule
err = retry(ctx, func() error {
var err error
acl, err = o.ACL().List(ctx)
if err != nil {
return fmt.Errorf("ACL.List: object ACL list failed: %v", err)
}
return nil
}, func() error {
if !containsACLRule(acl, entityRoleACL{aclEntity, RoleReader}) {
return fmt.Errorf("containsACL: expected ACL %v to include custom ACL entity %v", acl, entityRoleACL{aclEntity, RoleReader})
}
return nil
})
if err != nil {
t.Fatal(err)
}
})
}
func TestIntegration_PublicAccessPrevention(t *testing.T) {
ctx := skipJSONReads(context.Background(), "no reads in test")
multiTransportTest(ctx, t, func(t *testing.T, ctx context.Context, _ string, prefix string, client *Client) {
h := testHelper{t}
// Create a bucket with PublicAccessPrevention enforced.
bkt := client.Bucket(prefix + uidSpace.New())
h.mustCreate(bkt, testutil.ProjID(), &BucketAttrs{PublicAccessPrevention: PublicAccessPreventionEnforced})
defer h.mustDeleteBucket(bkt)
// Making bucket public should fail.
policy, err := bkt.IAM().V3().Policy(ctx)
if err != nil {
t.Fatalf("fetching bucket IAM policy: %v", err)
}
policy.Bindings = append(policy.Bindings, &iampb.Binding{
Role: "roles/storage.objectViewer",
Members: []string{iam.AllUsers},
})
if err := bkt.IAM().V3().SetPolicy(ctx, policy); err == nil {
t.Error("SetPolicy: expected adding AllUsers policy to bucket should fail")
}
// Making object public via ACL should fail.
o := bkt.Object("publicAccessPrevention")
defer func() {
if err := o.Delete(ctx); err != nil {
log.Printf("failed to delete test object: %v", err)
}
}()
wc := o.NewWriter(ctx)
wc.ContentType = "text/plain"
h.mustWrite(wc, []byte("test"))
a := o.ACL()
if err := a.Set(ctx, AllUsers, RoleReader); err == nil {
t.Error("ACL.Set: expected adding AllUsers ACL to object should fail")
}
// Update PAP setting to inherited should work and not affect UBLA setting.
attrs, err := bkt.Update(ctx, BucketAttrsToUpdate{PublicAccessPrevention: PublicAccessPreventionInherited})
if err != nil {
t.Fatalf("updating PublicAccessPrevention failed: %v", err)
}
if attrs.PublicAccessPrevention != PublicAccessPreventionInherited {
t.Errorf("updating PublicAccessPrevention: got %s, want %s", attrs.PublicAccessPrevention, PublicAccessPreventionInherited)
}
if attrs.UniformBucketLevelAccess.Enabled || attrs.BucketPolicyOnly.Enabled {
t.Error("updating PublicAccessPrevention changed UBLA setting")
}
// Now, making object public or making bucket public should succeed. Run with
// retry because ACL settings may take time to propagate.
retrier := func(err error) bool {
// Once ACL settings propagate, PAP should no longer be enforced and the call will succeed.
// In the meantime, while PAP is enforced, trying to set ACL results in:
// - FailedPrecondition for gRPC
// - condition not met (412) for HTTP
return ShouldRetry(err) || status.Code(err) == codes.FailedPrecondition || extractErrCode(err) == http.StatusPreconditionFailed
}
ctxWithTimeout, cancelCtx := context.WithTimeout(ctx, time.Second*10)
a = o.Retryer(WithErrorFunc(retrier), WithPolicy(RetryAlways)).ACL()
err = a.Set(ctxWithTimeout, AllUsers, RoleReader)
cancelCtx()
if err != nil {
t.Errorf("ACL.Set: making object public failed: %v", err)
}
policy, err = bkt.IAM().V3().Policy(ctx)
if err != nil {
t.Fatalf("fetching bucket IAM policy: %v", err)
}
policy.Bindings = append(policy.Bindings, &iampb.Binding{
Role: "roles/storage.objectViewer",
Members: []string{iam.AllUsers},
})
if err := bkt.IAM().V3().SetPolicy(ctx, policy); err != nil {
t.Errorf("SetPolicy: making bucket public failed: %v", err)
}
// Updating UBLA should not affect PAP setting.
attrs, err = bkt.Update(ctx, BucketAttrsToUpdate{UniformBucketLevelAccess: &UniformBucketLevelAccess{Enabled: true}})
if err != nil {
t.Fatalf("updating UBLA failed: %v", err)
}
if !attrs.UniformBucketLevelAccess.Enabled {
t.Error("updating UBLA: got UBLA not enabled, want enabled")
}
if attrs.PublicAccessPrevention != PublicAccessPreventionInherited {
t.Errorf("updating UBLA: got %s, want %s", attrs.PublicAccessPrevention, PublicAccessPreventionInherited)
}
})
}
func TestIntegration_Autoclass(t *testing.T) {
ctx := skipJSONReads(context.Background(), "no reads in test")
multiTransportTest(ctx, t, func(t *testing.T, ctx context.Context, _ string, prefix string, client *Client) {
h := testHelper{t}
// Create a bucket with Autoclass enabled.
bkt := client.Bucket(prefix + uidSpace.New())
h.mustCreate(bkt, testutil.ProjID(), &BucketAttrs{Autoclass: &Autoclass{Enabled: true}})
defer h.mustDeleteBucket(bkt)
// Get Autoclass configuration from bucket attrs.
attrs, err := bkt.Attrs(ctx)
if err != nil {
t.Fatalf("get bucket attrs failed: %v", err)
}
var toggleTime time.Time
if attrs != nil && attrs.Autoclass != nil {
if got, want := attrs.Autoclass.Enabled, true; got != want {
t.Errorf("attr.Autoclass.Enabled = %v, want %v", got, want)
}
if toggleTime = attrs.Autoclass.ToggleTime; toggleTime.IsZero() {
t.Error("got a zero time value, want a populated value")
}
}
// Disable Autoclass on the bucket.
ua := BucketAttrsToUpdate{Autoclass: &Autoclass{Enabled: false}}
attrs = h.mustUpdateBucket(bkt, ua, attrs.MetaGeneration)
if got, want := attrs.Autoclass.Enabled, false; got != want {
t.Errorf("attr.Autoclass.Enabled = %v, want %v", got, want)
}
latestToggleTime := attrs.Autoclass.ToggleTime
if latestToggleTime.IsZero() {
t.Error("got a zero time value, want a populated value")
}
if latestToggleTime.Before(toggleTime) {
t.Error("latestToggleTime should be newer than bucket creation toggleTime")
}
})
}
func TestIntegration_ConditionalDelete(t *testing.T) {
ctx := skipJSONReads(context.Background(), "no reads in test")
multiTransportTest(ctx, t, func(t *testing.T, ctx context.Context, bucket string, _ string, client *Client) {
h := testHelper{t}
o := client.Bucket(bucket).Object("conddel")
wc := o.NewWriter(ctx)
wc.ContentType = "text/plain"
h.mustWrite(wc, []byte("foo"))
gen := wc.Attrs().Generation
metaGen := wc.Attrs().Metageneration
if err := o.Generation(gen - 1).Delete(ctx); err == nil {
t.Fatalf("Unexpected successful delete with Generation")
}
if err := o.If(Conditions{MetagenerationMatch: metaGen + 1}).Delete(ctx); err == nil {
t.Fatalf("Unexpected successful delete with IfMetaGenerationMatch")
}
if err := o.If(Conditions{MetagenerationNotMatch: metaGen}).Delete(ctx); err == nil {
t.Fatalf("Unexpected successful delete with IfMetaGenerationNotMatch")
}
if err := o.Generation(gen).Delete(ctx); err != nil {
t.Fatalf("final delete failed: %v", err)
}
})
}
func TestIntegration_ObjectsRangeReader(t *testing.T) {
multiTransportTest(context.Background(), t, func(t *testing.T, ctx context.Context, bucket string, _ string, client *Client) {
bkt := client.Bucket(bucket)
objName := uidSpaceObjects.New()
obj := bkt.Object(objName)
contents := []byte("Hello, world this is a range request")
w := obj.If(Conditions{DoesNotExist: true}).NewWriter(ctx)
if _, err := w.Write(contents); err != nil {
t.Errorf("Failed to write contents: %v", err)
}
if err := w.Close(); err != nil {
t.Errorf("Failed to close writer: %v", err)
}
last5s := []struct {
name string
start int64
length int64
}{
{name: "negative offset", start: -5, length: -1},
{name: "offset with specified length", start: int64(len(contents)) - 5, length: 5},
{name: "offset and read till end", start: int64(len(contents)) - 5, length: -1},
}
for _, last5 := range last5s {
t.Run(last5.name, func(t *testing.T) {
wantBuf := contents[len(contents)-5:]
r, err := obj.NewRangeReader(ctx, last5.start, last5.length)
if err != nil {
t.Fatalf("Failed to make range read: %v", err)
}
defer r.Close()
if got, want := r.Attrs.StartOffset, int64(len(contents))-5; got != want {
t.Errorf("StartOffset mismatch, got %d want %d", got, want)
}
gotBuf := &bytes.Buffer{}
nr, _ := io.Copy(gotBuf, r)
if got, want := nr, int64(5); got != want {
t.Errorf("Body length mismatch, got %d want %d", got, want)
} else if diff := cmp.Diff(gotBuf.String(), string(wantBuf)); diff != "" {
t.Errorf("Content read does not match - got(-),want(+):\n%s", diff)
}
})
}
})
}
func TestIntegration_ObjectReadChunksGRPC(t *testing.T) {
multiTransportTest(skipHTTP("gRPC implementation specific test"), t, func(t *testing.T, ctx context.Context, bucket string, _ string, client *Client) {
h := testHelper{t}
// Use a larger blob to test chunking logic. This is a little over 5MB.
content := bytes.Repeat([]byte("a"), 5<<20)