| 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 gcsblob |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"errors" |
| 20 |
"flag" |
| 21 |
"fmt" |
| 22 |
"io" |
| 23 |
"net/http" |
| 24 |
"net/url" |
| 25 |
"os" |
| 26 |
"os/user" |
| 27 |
"path/filepath" |
| 28 |
"testing" |
| 29 |
"time" |
| 30 |
|
| 31 |
"cloud.google.com/go/storage" |
| 32 |
"github.com/google/go-cmp/cmp" |
| 33 |
"gocloud.dev/blob" |
| 34 |
"gocloud.dev/blob/driver" |
| 35 |
"gocloud.dev/blob/drivertest" |
| 36 |
"gocloud.dev/gcerrors" |
| 37 |
"gocloud.dev/gcp" |
| 38 |
"gocloud.dev/internal/testing/setup" |
| 39 |
"google.golang.org/api/googleapi" |
| 40 |
) |
| 41 |
|
| 42 |
const ( |
| 43 |
// These constants capture values that were used during the last -record. |
| 44 |
// |
| 45 |
// If you want to use --record mode, |
| 46 |
// 1. Create a bucket in your GCP project: |
| 47 |
// https://console.cloud.google.com/storage/browser, then "Create Bucket". |
| 48 |
// 2. Update the bucketName constant to your bucket name. |
| 49 |
// 3. Create a service account in your GCP project and update the |
| 50 |
// serviceAccountID constant to it. |
| 51 |
// 4. Download a private key to a .pem file as described here: |
| 52 |
// https://godoc.org/cloud.google.com/go/storage#SignedURLOptions |
| 53 |
// and pass a path to it via the --privatekey flag. |
| 54 |
// TODO(issue #300): Use Terraform to provision a bucket, and get the bucket |
| 55 |
// name from the Terraform output instead (saving a copy of it for replay). |
| 56 |
bucketName = "go-cloud-blob-test-bucket" |
| 57 |
serviceAccountID = "[email protected]" |
| 58 |
) |
| 59 |
|
| 60 |
var pathToPrivateKey = flag.String("privatekey", "", "path to .pem file containing private key (required for --record); defaults to ~/Downloads/gcs-private-key.pem") |
| 61 |
|
| 62 |
type harness struct { |
| 63 |
client *gcp.HTTPClient |
| 64 |
opts *Options |
| 65 |
rt http.RoundTripper |
| 66 |
closer func() |
| 67 |
} |
| 68 |
|
| 69 |
func newHarness(ctx context.Context, t *testing.T) (drivertest.Harness, error) { |
| 70 |
t.Helper() |
| 71 |
|
| 72 |
opts := &Options{GoogleAccessID: serviceAccountID} |
| 73 |
if *setup.Record { |
| 74 |
if *pathToPrivateKey == "" { |
| 75 |
usr, _ := user.Current() |
| 76 |
*pathToPrivateKey = filepath.Join(usr.HomeDir, "Downloads", "gcs-private-key.pem") |
| 77 |
} |
| 78 |
// Use a real private key for signing URLs during -record. |
| 79 |
pk, err := os.ReadFile(*pathToPrivateKey) |
| 80 |
if err != nil { |
| 81 |
t.Fatalf("Couldn't find private key at %v: %v", *pathToPrivateKey, err) |
| 82 |
} |
| 83 |
opts.PrivateKey = pk |
| 84 |
} else { |
| 85 |
// Use a dummy signer in replay mode. |
| 86 |
opts.SignBytes = func(b []byte) ([]byte, error) { return []byte("signed!"), nil } |
| 87 |
} |
| 88 |
client, rt, done := setup.NewGCPClient(ctx, t) |
| 89 |
return &harness{client: client, opts: opts, rt: rt, closer: done}, nil |
| 90 |
} |
| 91 |
|
| 92 |
func (h *harness) HTTPClient() *http.Client { |
| 93 |
return &http.Client{Transport: h.rt} |
| 94 |
} |
| 95 |
|
| 96 |
func (h *harness) MakeDriver(ctx context.Context) (driver.Bucket, error) { |
| 97 |
return openBucket(ctx, h.client, bucketName, h.opts) |
| 98 |
} |
| 99 |
|
| 100 |
func (h *harness) MakeDriverForNonexistentBucket(ctx context.Context) (driver.Bucket, error) { |
| 101 |
return openBucket(ctx, h.client, "bucket-does-not-exist", h.opts) |
| 102 |
} |
| 103 |
|
| 104 |
func (h *harness) Close() { |
| 105 |
h.closer() |
| 106 |
} |
| 107 |
|
| 108 |
func TestConformance(t *testing.T) { |
| 109 |
drivertest.RunConformanceTests(t, newHarness, []drivertest.AsTest{verifyContentLanguage{}}) |
| 110 |
} |
| 111 |
|
| 112 |
func BenchmarkGcsblob(b *testing.B) { |
| 113 |
ctx := context.Background() |
| 114 |
creds, err := gcp.DefaultCredentials(ctx) |
| 115 |
if err != nil { |
| 116 |
b.Fatal(err) |
| 117 |
} |
| 118 |
client, err := gcp.NewHTTPClient(gcp.DefaultTransport(), gcp.CredentialsTokenSource(creds)) |
| 119 |
if err != nil { |
| 120 |
b.Fatal(err) |
| 121 |
} |
| 122 |
bkt, err := OpenBucket(context.Background(), client, bucketName, nil) |
| 123 |
if err != nil { |
| 124 |
b.Fatal(err) |
| 125 |
} |
| 126 |
drivertest.RunBenchmarks(b, bkt) |
| 127 |
} |
| 128 |
|
| 129 |
const language = "nl" |
| 130 |
|
| 131 |
// verifyContentLanguage uses As to access the underlying GCS types and |
| 132 |
// read/write the ContentLanguage field. |
| 133 |
type verifyContentLanguage struct{} |
| 134 |
|
| 135 |
func (verifyContentLanguage) Name() string { |
| 136 |
return "verify ContentLanguage can be written and read through As" |
| 137 |
} |
| 138 |
|
| 139 |
func (verifyContentLanguage) BucketCheck(b *blob.Bucket) error { |
| 140 |
var client *storage.Client |
| 141 |
if !b.As(&client) { |
| 142 |
return errors.New("Bucket.As failed") |
| 143 |
} |
| 144 |
return nil |
| 145 |
} |
| 146 |
|
| 147 |
func (verifyContentLanguage) ErrorCheck(b *blob.Bucket, err error) error { |
| 148 |
// Can't really verify this one because the storage library returns |
| 149 |
// a sentinel error, storage.ErrObjectNotExist, for "not exists" |
| 150 |
// instead of the supported As type googleapi.Error. |
| 151 |
// Call ErrorAs anyway, and expect it to fail. |
| 152 |
var to *googleapi.Error |
| 153 |
if b.ErrorAs(err, &to) { |
| 154 |
return errors.New("expected ErrorAs to fail") |
| 155 |
} |
| 156 |
return nil |
| 157 |
} |
| 158 |
|
| 159 |
func (verifyContentLanguage) BeforeRead(as func(any) bool) error { |
| 160 |
var objp **storage.ObjectHandle |
| 161 |
if !as(&objp) { |
| 162 |
return errors.New("BeforeRead.As failed to get ObjectHandle") |
| 163 |
} |
| 164 |
var sr *storage.Reader |
| 165 |
if !as(&sr) { |
| 166 |
return errors.New("BeforeRead.As failed to get Reader") |
| 167 |
} |
| 168 |
return nil |
| 169 |
} |
| 170 |
|
| 171 |
func (verifyContentLanguage) BeforeWrite(as func(any) bool) error { |
| 172 |
var objp **storage.ObjectHandle |
| 173 |
if !as(&objp) { |
| 174 |
return errors.New("Writer.As failed to get ObjectHandle") |
| 175 |
} |
| 176 |
var sw *storage.Writer |
| 177 |
if !as(&sw) { |
| 178 |
return errors.New("Writer.As failed to get Writer") |
| 179 |
} |
| 180 |
sw.ContentLanguage = language |
| 181 |
return nil |
| 182 |
} |
| 183 |
|
| 184 |
func (verifyContentLanguage) BeforeCopy(as func(any) bool) error { |
| 185 |
var coh *CopyObjectHandles |
| 186 |
if !as(&coh) { |
| 187 |
return errors.New("BeforeCopy.As failed to get CopyObjectHandles") |
| 188 |
} |
| 189 |
var copier *storage.Copier |
| 190 |
if !as(&copier) { |
| 191 |
return errors.New("BeforeCopy.As failed") |
| 192 |
} |
| 193 |
return nil |
| 194 |
} |
| 195 |
|
| 196 |
func (verifyContentLanguage) BeforeList(as func(any) bool) error { |
| 197 |
var q *storage.Query |
| 198 |
if !as(&q) { |
| 199 |
return errors.New("List.As failed") |
| 200 |
} |
| 201 |
// Nothing to do. |
| 202 |
return nil |
| 203 |
} |
| 204 |
|
| 205 |
func (verifyContentLanguage) BeforeSign(as func(any) bool) error { |
| 206 |
var opts *storage.SignedURLOptions |
| 207 |
if !as(&opts) { |
| 208 |
return errors.New("BeforeSign.As failed") |
| 209 |
} |
| 210 |
// Nothing to do. |
| 211 |
return nil |
| 212 |
} |
| 213 |
|
| 214 |
func (verifyContentLanguage) AttributesCheck(attrs *blob.Attributes) error { |
| 215 |
var oa storage.ObjectAttrs |
| 216 |
if !attrs.As(&oa) { |
| 217 |
return errors.New("Attributes.As returned false") |
| 218 |
} |
| 219 |
if got := oa.ContentLanguage; got != language { |
| 220 |
return fmt.Errorf("got %q want %q", got, language) |
| 221 |
} |
| 222 |
return nil |
| 223 |
} |
| 224 |
|
| 225 |
func (verifyContentLanguage) ReaderCheck(r *blob.Reader) error { |
| 226 |
var rr *storage.Reader |
| 227 |
if !r.As(&rr) { |
| 228 |
return errors.New("Reader.As returned false") |
| 229 |
} |
| 230 |
// GCS doesn't return Content-Language via storage.Reader. |
| 231 |
return nil |
| 232 |
} |
| 233 |
|
| 234 |
func (verifyContentLanguage) ListObjectCheck(o *blob.ListObject) error { |
| 235 |
var oa storage.ObjectAttrs |
| 236 |
if !o.As(&oa) { |
| 237 |
return errors.New("ListObject.As returned false") |
| 238 |
} |
| 239 |
if o.IsDir { |
| 240 |
return nil |
| 241 |
} |
| 242 |
if got := oa.ContentLanguage; got != language { |
| 243 |
return fmt.Errorf("got %q want %q", got, language) |
| 244 |
} |
| 245 |
return nil |
| 246 |
} |
| 247 |
|
| 248 |
// GCS-specific unit tests. |
| 249 |
func TestBufferSize(t *testing.T) { |
| 250 |
tests := []struct { |
| 251 |
size int |
| 252 |
want int |
| 253 |
}{ |
| 254 |
{ |
| 255 |
size: 5 * 1024 * 1024, |
| 256 |
want: 5 * 1024 * 1024, |
| 257 |
}, |
| 258 |
{ |
| 259 |
size: 0, |
| 260 |
want: googleapi.DefaultUploadChunkSize, |
| 261 |
}, |
| 262 |
{ |
| 263 |
size: -1024, |
| 264 |
want: 0, |
| 265 |
}, |
| 266 |
} |
| 267 |
for i, test := range tests { |
| 268 |
got := bufferSize(test.size) |
| 269 |
if got != test.want { |
| 270 |
t.Errorf("%d) got buffer size %d, want %d", i, got, test.want) |
| 271 |
} |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
func TestOpenBucket(t *testing.T) { |
| 276 |
tests := []struct { |
| 277 |
description string |
| 278 |
bucketName string |
| 279 |
nilClient bool |
| 280 |
want string |
| 281 |
wantErr bool |
| 282 |
}{ |
| 283 |
{ |
| 284 |
description: "empty bucket name results in error", |
| 285 |
wantErr: true, |
| 286 |
}, |
| 287 |
{ |
| 288 |
description: "nil client results in error", |
| 289 |
bucketName: "foo", |
| 290 |
nilClient: true, |
| 291 |
wantErr: true, |
| 292 |
}, |
| 293 |
{ |
| 294 |
description: "success", |
| 295 |
bucketName: "foo", |
| 296 |
want: "foo", |
| 297 |
}, |
| 298 |
} |
| 299 |
|
| 300 |
ctx := context.Background() |
| 301 |
for _, test := range tests { |
| 302 |
t.Run(test.description, func(t *testing.T) { |
| 303 |
var client *gcp.HTTPClient |
| 304 |
if !test.nilClient { |
| 305 |
var done func() |
| 306 |
client, _, done = setup.NewGCPClient(ctx, t) |
| 307 |
defer done() |
| 308 |
} |
| 309 |
|
| 310 |
// Create driver impl. |
| 311 |
drv, err := openBucket(ctx, client, test.bucketName, nil) |
| 312 |
if (err != nil) != test.wantErr { |
| 313 |
t.Errorf("got err %v want error %v", err, test.wantErr) |
| 314 |
} |
| 315 |
if err == nil && drv != nil && drv.name != test.want { |
| 316 |
t.Errorf("got %q want %q", drv.name, test.want) |
| 317 |
} |
| 318 |
|
| 319 |
// Create portable type. |
| 320 |
b, err := OpenBucket(ctx, client, test.bucketName, nil) |
| 321 |
if b != nil { |
| 322 |
defer b.Close() |
| 323 |
} |
| 324 |
if (err != nil) != test.wantErr { |
| 325 |
t.Errorf("got err %v want error %v", err, test.wantErr) |
| 326 |
} |
| 327 |
}) |
| 328 |
} |
| 329 |
} |
| 330 |
|
| 331 |
// TestBeforeReadNonExistentKey tests using BeforeRead on a nonexistent key. |
| 332 |
func TestBeforeReadNonExistentKey(t *testing.T) { |
| 333 |
ctx := context.Background() |
| 334 |
h, err := newHarness(ctx, t) |
| 335 |
if err != nil { |
| 336 |
t.Fatal(err) |
| 337 |
} |
| 338 |
defer h.Close() |
| 339 |
|
| 340 |
drv, err := h.MakeDriver(ctx) |
| 341 |
if err != nil { |
| 342 |
t.Fatal(err) |
| 343 |
} |
| 344 |
bucket := blob.NewBucket(drv) |
| 345 |
defer bucket.Close() |
| 346 |
|
| 347 |
// Try reading a nonexistent key. |
| 348 |
_, err = bucket.NewReader(ctx, "nonexistent-key", &blob.ReaderOptions{ |
| 349 |
BeforeRead: func(asFunc func(any) bool) error { |
| 350 |
var objp **storage.ObjectHandle |
| 351 |
if !asFunc(&objp) { |
| 352 |
return errors.New("Reader.As failed to get ObjectHandle") |
| 353 |
} |
| 354 |
var rp *storage.Reader |
| 355 |
if asFunc(&rp) { |
| 356 |
return errors.New("Reader.As unexpectedly got storage.Reader") |
| 357 |
} |
| 358 |
return nil |
| 359 |
}, |
| 360 |
}) |
| 361 |
if err == nil || gcerrors.Code(err) != gcerrors.NotFound { |
| 362 |
t.Errorf("got error %v, wanted NotFound for Read", err) |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
// TestPreconditions tests setting of ObjectHandle preconditions via As. |
| 367 |
func TestPreconditions(t *testing.T) { |
| 368 |
const ( |
| 369 |
key = "precondition-key" |
| 370 |
key2 = "precondition-key2" |
| 371 |
content = "hello world" |
| 372 |
) |
| 373 |
|
| 374 |
ctx := context.Background() |
| 375 |
h, err := newHarness(ctx, t) |
| 376 |
if err != nil { |
| 377 |
t.Fatal(err) |
| 378 |
} |
| 379 |
defer h.Close() |
| 380 |
|
| 381 |
drv, err := h.MakeDriver(ctx) |
| 382 |
if err != nil { |
| 383 |
t.Fatal(err) |
| 384 |
} |
| 385 |
bucket := blob.NewBucket(drv) |
| 386 |
defer bucket.Close() |
| 387 |
|
| 388 |
// Try writing with a failing precondition. |
| 389 |
if err := bucket.WriteAll(ctx, key, []byte(content), &blob.WriterOptions{ |
| 390 |
BeforeWrite: func(asFunc func(any) bool) error { |
| 391 |
var objp **storage.ObjectHandle |
| 392 |
if !asFunc(&objp) { |
| 393 |
return errors.New("Writer.As failed to get ObjectHandle") |
| 394 |
} |
| 395 |
// Replace the ObjectHandle with a new one that adds Conditions. |
| 396 |
*objp = (*objp).If(storage.Conditions{GenerationMatch: -999}) |
| 397 |
return nil |
| 398 |
}, |
| 399 |
}); err == nil || gcerrors.Code(err) != gcerrors.FailedPrecondition { |
| 400 |
t.Errorf("got error %v, wanted FailedPrecondition for Write", err) |
| 401 |
} |
| 402 |
|
| 403 |
// Repeat with a precondition that will pass. |
| 404 |
if err := bucket.WriteAll(ctx, key, []byte(content), &blob.WriterOptions{ |
| 405 |
BeforeWrite: func(asFunc func(any) bool) error { |
| 406 |
var objp **storage.ObjectHandle |
| 407 |
if !asFunc(&objp) { |
| 408 |
return errors.New("Writer.As failed to get ObjectHandle") |
| 409 |
} |
| 410 |
// Replace the ObjectHandle with a new one that adds Conditions. |
| 411 |
*objp = (*objp).If(storage.Conditions{DoesNotExist: true}) |
| 412 |
return nil |
| 413 |
}, |
| 414 |
}); err != nil { |
| 415 |
t.Errorf("got error %v, wanted nil", err) |
| 416 |
} |
| 417 |
defer bucket.Delete(ctx, key) |
| 418 |
|
| 419 |
// Try reading with a failing precondition. |
| 420 |
_, err = bucket.NewReader(ctx, key, &blob.ReaderOptions{ |
| 421 |
BeforeRead: func(asFunc func(any) bool) error { |
| 422 |
var objp **storage.ObjectHandle |
| 423 |
if !asFunc(&objp) { |
| 424 |
return errors.New("Reader.As failed to get ObjectHandle") |
| 425 |
} |
| 426 |
// Replace the ObjectHandle with a new one. |
| 427 |
*objp = (*objp).Generation(999999) |
| 428 |
return nil |
| 429 |
}, |
| 430 |
}) |
| 431 |
if err == nil || gcerrors.Code(err) != gcerrors.NotFound { |
| 432 |
t.Errorf("got error %v, wanted NotFound for Read", err) |
| 433 |
} |
| 434 |
|
| 435 |
attrs, err := bucket.Attributes(ctx, key) |
| 436 |
if err != nil { |
| 437 |
t.Fatal(err) |
| 438 |
} |
| 439 |
var oa storage.ObjectAttrs |
| 440 |
if !attrs.As(&oa) { |
| 441 |
t.Fatal("Attributes.As failed") |
| 442 |
} |
| 443 |
generation := oa.Generation |
| 444 |
|
| 445 |
// Repeat with a precondition that will pass. |
| 446 |
reader, err := bucket.NewReader(ctx, key, &blob.ReaderOptions{ |
| 447 |
BeforeRead: func(asFunc func(any) bool) error { |
| 448 |
var objp **storage.ObjectHandle |
| 449 |
if !asFunc(&objp) { |
| 450 |
return errors.New("Reader.As failed to get ObjectHandle") |
| 451 |
} |
| 452 |
// Replace the ObjectHandle with a new one. |
| 453 |
*objp = (*objp).Generation(generation) |
| 454 |
return nil |
| 455 |
}, |
| 456 |
}) |
| 457 |
if err != nil { |
| 458 |
t.Fatal(err) |
| 459 |
} |
| 460 |
defer reader.Close() |
| 461 |
gotBytes, err := io.ReadAll(reader) |
| 462 |
if err != nil { |
| 463 |
t.Fatal(err) |
| 464 |
} |
| 465 |
if got := string(gotBytes); got != content { |
| 466 |
t.Errorf("got %q want %q", got, content) |
| 467 |
} |
| 468 |
|
| 469 |
// Try copying with a failing precondition on Dst. |
| 470 |
err = bucket.Copy(ctx, key2, key, &blob.CopyOptions{ |
| 471 |
BeforeCopy: func(asFunc func(any) bool) error { |
| 472 |
var coh *CopyObjectHandles |
| 473 |
if !asFunc(&coh) { |
| 474 |
return errors.New("Copy.As failed to get CopyObjectHandles") |
| 475 |
} |
| 476 |
// Replace the dst ObjectHandle with a new one. |
| 477 |
coh.Dst = coh.Dst.If(storage.Conditions{GenerationMatch: -999}) |
| 478 |
return nil |
| 479 |
}, |
| 480 |
}) |
| 481 |
if err == nil || gcerrors.Code(err) != gcerrors.FailedPrecondition { |
| 482 |
t.Errorf("got error %v, wanted FailedPrecondition for Copy", err) |
| 483 |
} |
| 484 |
|
| 485 |
// Try copying with a failing precondition on Src. |
| 486 |
err = bucket.Copy(ctx, key2, key, &blob.CopyOptions{ |
| 487 |
BeforeCopy: func(asFunc func(any) bool) error { |
| 488 |
var coh *CopyObjectHandles |
| 489 |
if !asFunc(&coh) { |
| 490 |
return errors.New("Copy.As failed to get CopyObjectHandles") |
| 491 |
} |
| 492 |
// Replace the src ObjectHandle with a new one. |
| 493 |
coh.Src = coh.Src.Generation(9999999) |
| 494 |
return nil |
| 495 |
}, |
| 496 |
}) |
| 497 |
if err == nil || gcerrors.Code(err) != gcerrors.NotFound { |
| 498 |
t.Errorf("got error %v, wanted NotFound for Copy", err) |
| 499 |
} |
| 500 |
|
| 501 |
// Repeat with preconditions on Dst and Src that will succeed. |
| 502 |
err = bucket.Copy(ctx, key2, key, &blob.CopyOptions{ |
| 503 |
BeforeCopy: func(asFunc func(any) bool) error { |
| 504 |
var coh *CopyObjectHandles |
| 505 |
if !asFunc(&coh) { |
| 506 |
return errors.New("Reader.As failed to get CopyObjectHandles") |
| 507 |
} |
| 508 |
coh.Dst = coh.Dst.If(storage.Conditions{DoesNotExist: true}) |
| 509 |
coh.Src = coh.Src.Generation(generation) |
| 510 |
return nil |
| 511 |
}, |
| 512 |
}) |
| 513 |
if err != nil { |
| 514 |
t.Error(err) |
| 515 |
} |
| 516 |
defer bucket.Delete(ctx, key2) |
| 517 |
} |
| 518 |
|
| 519 |
func TestURLOpenerForParams(t *testing.T) { |
| 520 |
ctx := context.Background() |
| 521 |
|
| 522 |
// Create a file for use as a dummy private key file. |
| 523 |
privateKey := []byte("some content") |
| 524 |
pkFile, err := os.CreateTemp("", "my-private-key") |
| 525 |
if err != nil { |
| 526 |
t.Fatal(err) |
| 527 |
} |
| 528 |
defer os.Remove(pkFile.Name()) |
| 529 |
if _, err := pkFile.Write(privateKey); err != nil { |
| 530 |
t.Fatal(err) |
| 531 |
} |
| 532 |
if err := pkFile.Close(); err != nil { |
| 533 |
t.Fatal(err) |
| 534 |
} |
| 535 |
|
| 536 |
tests := []struct { |
| 537 |
name string |
| 538 |
currOpts Options |
| 539 |
query url.Values |
| 540 |
wantOpts Options |
| 541 |
wantClient bool |
| 542 |
wantErr bool |
| 543 |
}{ |
| 544 |
{ |
| 545 |
name: "InvalidParam", |
| 546 |
query: url.Values{ |
| 547 |
"foo": {"bar"}, |
| 548 |
}, |
| 549 |
wantErr: true, |
| 550 |
}, |
| 551 |
{ |
| 552 |
name: "AccessID", |
| 553 |
query: url.Values{ |
| 554 |
"access_id": {"bar"}, |
| 555 |
}, |
| 556 |
wantOpts: Options{GoogleAccessID: "bar"}, |
| 557 |
}, |
| 558 |
{ |
| 559 |
name: "AccessID override", |
| 560 |
currOpts: Options{GoogleAccessID: "foo"}, |
| 561 |
query: url.Values{ |
| 562 |
"access_id": {"bar"}, |
| 563 |
}, |
| 564 |
wantOpts: Options{GoogleAccessID: "bar"}, |
| 565 |
}, |
| 566 |
{ |
| 567 |
name: "AccessID override to - makes new client", |
| 568 |
currOpts: Options{GoogleAccessID: "foo"}, |
| 569 |
query: url.Values{ |
| 570 |
"access_id": {"-"}, |
| 571 |
}, |
| 572 |
wantOpts: Options{}, // cleared |
| 573 |
wantClient: true, |
| 574 |
}, |
| 575 |
{ |
| 576 |
name: "AccessID not overridden", |
| 577 |
currOpts: Options{GoogleAccessID: "bar"}, |
| 578 |
wantOpts: Options{GoogleAccessID: "bar"}, |
| 579 |
}, |
| 580 |
{ |
| 581 |
name: "Invalid value for anonymous", |
| 582 |
query: url.Values{ |
| 583 |
"anonymous": {"bad"}, |
| 584 |
}, |
| 585 |
wantErr: true, |
| 586 |
}, |
| 587 |
{ |
| 588 |
name: "Anonymous", |
| 589 |
currOpts: Options{GoogleAccessID: "foo"}, |
| 590 |
query: url.Values{ |
| 591 |
"anonymous": {"true"}, |
| 592 |
}, |
| 593 |
wantOpts: Options{}, // cleared |
| 594 |
wantClient: true, |
| 595 |
}, |
| 596 |
{ |
| 597 |
name: "BadPrivateKeyPath", |
| 598 |
query: url.Values{ |
| 599 |
"private_key_path": {"/path/does/not/exist"}, |
| 600 |
}, |
| 601 |
wantErr: true, |
| 602 |
}, |
| 603 |
{ |
| 604 |
name: "PrivateKeyPath", |
| 605 |
query: url.Values{ |
| 606 |
"private_key_path": {pkFile.Name()}, |
| 607 |
}, |
| 608 |
wantOpts: Options{PrivateKey: privateKey}, |
| 609 |
}, |
| 610 |
{ |
| 611 |
name: "PrivateKey cleared", |
| 612 |
currOpts: Options{PrivateKey: privateKey}, |
| 613 |
query: url.Values{ |
| 614 |
"private_key_path": {""}, |
| 615 |
}, |
| 616 |
wantOpts: Options{}, |
| 617 |
}, |
| 618 |
{ |
| 619 |
name: "AccessID change clears PrivateKey and MakeSignBytes", |
| 620 |
currOpts: Options{ |
| 621 |
GoogleAccessID: "foo", |
| 622 |
PrivateKey: privateKey, |
| 623 |
MakeSignBytes: func(context.Context) SignBytesFunc { |
| 624 |
return func([]byte) ([]byte, error) { |
| 625 |
return nil, context.DeadlineExceeded |
| 626 |
} |
| 627 |
}, |
| 628 |
}, |
| 629 |
query: url.Values{ |
| 630 |
"access_id": {"bar"}, |
| 631 |
}, |
| 632 |
wantOpts: Options{GoogleAccessID: "bar"}, |
| 633 |
}, |
| 634 |
} |
| 635 |
|
| 636 |
for _, test := range tests { |
| 637 |
t.Run(test.name, func(t *testing.T) { |
| 638 |
o := &URLOpener{Options: test.currOpts} |
| 639 |
got, gotClient, err := o.forParams(ctx, test.query) |
| 640 |
if (err != nil) != test.wantErr { |
| 641 |
t.Errorf("got err %v want error %v", err, test.wantErr) |
| 642 |
} |
| 643 |
if err != nil { |
| 644 |
return |
| 645 |
} |
| 646 |
if diff := cmp.Diff(got, &test.wantOpts); diff != "" { |
| 647 |
t.Errorf("opener.forParams(...) diff (-want +got):\n%s", diff) |
| 648 |
} |
| 649 |
if test.wantClient != (gotClient != nil) { |
| 650 |
t.Errorf("opener.forParams client return value was unexpected, got %v want %v", gotClient != nil, test.wantClient) |
| 651 |
} |
| 652 |
}) |
| 653 |
} |
| 654 |
} |
| 655 |
|
| 656 |
func TestOpenBucketFromURL(t *testing.T) { |
| 657 |
cleanup := setup.FakeGCPDefaultCredentials(t) |
| 658 |
defer cleanup() |
| 659 |
|
| 660 |
pkFile, err := os.CreateTemp("", "my-private-key") |
| 661 |
if err != nil { |
| 662 |
t.Fatal(err) |
| 663 |
} |
| 664 |
defer os.Remove(pkFile.Name()) |
| 665 |
if err := os.WriteFile(pkFile.Name(), []byte("key"), 0o666); err != nil { |
| 666 |
t.Fatal(err) |
| 667 |
} |
| 668 |
|
| 669 |
tests := []struct { |
| 670 |
URL string |
| 671 |
WantErr bool |
| 672 |
}{ |
| 673 |
// OK. |
| 674 |
{"gs://mybucket", false}, |
| 675 |
// OK, setting access_id. |
| 676 |
{"gs://mybucket?access_id=foo", false}, |
| 677 |
// OK, setting private_key_path. |
| 678 |
{"gs://mybucket?private_key_path=" + pkFile.Name(), false}, |
| 679 |
// OK, clearing any pre-existing private key. |
| 680 |
{"gs://mybucket?private_key_path=", false}, |
| 681 |
// OK, setting universe_domain. |
| 682 |
{"gs://mybucket?universe_domain=example.com", false}, |
| 683 |
// OK, universe_domain with empty value. |
| 684 |
{"gs://mybucket?universe_domain=", false}, |
| 685 |
// Invalid private_key_path. |
| 686 |
{"gs://mybucket?private_key_path=invalid-path", true}, |
| 687 |
// Invalid parameter. |
| 688 |
{"gs://mybucket?param=value", true}, |
| 689 |
} |
| 690 |
|
| 691 |
ctx := context.Background() |
| 692 |
for _, test := range tests { |
| 693 |
b, err := blob.OpenBucket(ctx, test.URL) |
| 694 |
if b != nil { |
| 695 |
defer b.Close() |
| 696 |
} |
| 697 |
if (err != nil) != test.WantErr { |
| 698 |
t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr) |
| 699 |
} |
| 700 |
} |
| 701 |
} |
| 702 |
|
| 703 |
func TestReadDefaultCredentials(t *testing.T) { |
| 704 |
tests := []struct { |
| 705 |
givenJSON string |
| 706 |
WantAccessID string |
| 707 |
WantPrivateKey []byte |
| 708 |
}{ |
| 709 |
// Variant A: service account file |
| 710 |
{ |
| 711 |
`{ |
| 712 |
"type": "service_account", |
| 713 |
"project_id": "project-id", |
| 714 |
"private_key_id": "key-id", |
| 715 |
"private_key": "-----BEGIN PRIVATE KEY-----\nprivate-key\n-----END PRIVATE KEY-----\n", |
| 716 |
"client_email": "service-account-email", |
| 717 |
"client_id": "client-id", |
| 718 |
"auth_uri": "https://accounts.google.com/o/oauth2/auth", |
| 719 |
"token_uri": "https://accounts.google.com/o/oauth2/token", |
| 720 |
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", |
| 721 |
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account-email" |
| 722 |
}`, |
| 723 |
"service-account-email", |
| 724 |
[]byte("-----BEGIN PRIVATE KEY-----\nprivate-key\n-----END PRIVATE KEY-----\n"), |
| 725 |
}, |
| 726 |
// Variant A: credentials file absent a private key (stripped) |
| 727 |
{ |
| 728 |
`{ |
| 729 |
"google": {}, |
| 730 |
"client_email": "service-account-email", |
| 731 |
"client_id": "client-id" |
| 732 |
}`, |
| 733 |
"service-account-email", |
| 734 |
[]byte(""), |
| 735 |
}, |
| 736 |
// Variant B: obtained through the REST API |
| 737 |
{ |
| 738 |
`{ |
| 739 |
"name": "projects/project-id/serviceAccounts/service-account-email/keys/key-id", |
| 740 |
"privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE", |
| 741 |
"privateKeyData": "private-key", |
| 742 |
"validAfterTime": "date", |
| 743 |
"validBeforeTime": "date", |
| 744 |
"keyAlgorithm": "KEY_ALG_RSA_2048" |
| 745 |
}`, |
| 746 |
"service-account-email", |
| 747 |
[]byte("private-key"), |
| 748 |
}, |
| 749 |
// An empty input shall not throw an exception |
| 750 |
{"", "", nil}, |
| 751 |
} |
| 752 |
|
| 753 |
for i, test := range tests { |
| 754 |
inJSON := []byte(test.givenJSON) |
| 755 |
if len(test.givenJSON) == 0 { |
| 756 |
inJSON = nil |
| 757 |
} |
| 758 |
|
| 759 |
gotAccessID, gotPrivateKey := readDefaultCredentials(inJSON) |
| 760 |
if gotAccessID != test.WantAccessID || string(gotPrivateKey) != string(test.WantPrivateKey) { |
| 761 |
t.Errorf("Mismatched field values in case %d:\n -- got: %v, %v\n -- want: %v, %v", i, |
| 762 |
gotAccessID, gotPrivateKey, |
| 763 |
test.WantAccessID, test.WantPrivateKey, |
| 764 |
) |
| 765 |
} |
| 766 |
} |
| 767 |
} |
| 768 |
|
| 769 |
func TestRemainingSignedURLSchemes(t *testing.T) { |
| 770 |
tests := []struct { |
| 771 |
name string |
| 772 |
currOpts Options |
| 773 |
wantSignedURL string // Not the actual URL, which is subject to change, but a mimickry. |
| 774 |
wantErr bool |
| 775 |
}{ |
| 776 |
{ |
| 777 |
name: "no scheme available, error", |
| 778 |
wantErr: true, |
| 779 |
}, |
| 780 |
{ |
| 781 |
name: "too many schemes configured", |
| 782 |
currOpts: Options{ |
| 783 |
GoogleAccessID: "foo", |
| 784 |
PrivateKey: []byte("private-key"), |
| 785 |
SignBytes: func([]byte) ([]byte, error) { |
| 786 |
return []byte("signed"), nil |
| 787 |
}, |
| 788 |
}, |
| 789 |
wantErr: true, |
| 790 |
}, |
| 791 |
{ |
| 792 |
name: "SignBytes", |
| 793 |
currOpts: Options{ |
| 794 |
GoogleAccessID: "foo", |
| 795 |
SignBytes: func([]byte) ([]byte, error) { |
| 796 |
return []byte("signed"), nil |
| 797 |
}, |
| 798 |
}, |
| 799 |
wantSignedURL: "https://host/go-cloud-blob-test-bucket/some-key?GoogleAccessId=foo&Signature=c2lnbmVk", |
| 800 |
}, |
| 801 |
{ |
| 802 |
name: "MakeSignBytes is being used", |
| 803 |
currOpts: Options{ |
| 804 |
GoogleAccessID: "foo", |
| 805 |
MakeSignBytes: func(context.Context) SignBytesFunc { |
| 806 |
return func([]byte) ([]byte, error) { |
| 807 |
return []byte("signed"), nil |
| 808 |
} |
| 809 |
}, |
| 810 |
}, |
| 811 |
wantSignedURL: "https://host/go-cloud-blob-test-bucket/some-key?GoogleAccessId=foo&Signature=c2lnbmVk", |
| 812 |
}, |
| 813 |
} |
| 814 |
|
| 815 |
ctx := context.Background() |
| 816 |
signOpts := &driver.SignedURLOptions{ |
| 817 |
Expiry: 30 * time.Second, |
| 818 |
Method: http.MethodGet, |
| 819 |
} |
| 820 |
|
| 821 |
for _, test := range tests { |
| 822 |
t.Run(test.name, func(t *testing.T) { |
| 823 |
bucket := bucket{name: bucketName, opts: &test.currOpts} |
| 824 |
|
| 825 |
// SignedURL doesn't check whether a key exists. |
| 826 |
gotURL, gotErr := bucket.SignedURL(ctx, "some-key", signOpts) |
| 827 |
if (gotErr != nil) != test.wantErr { |
| 828 |
t.Errorf("Got unexpected error %v", gotErr) |
| 829 |
} |
| 830 |
if test.wantSignedURL == "" { |
| 831 |
return |
| 832 |
} |
| 833 |
|
| 834 |
got, _ := url.Parse(gotURL) |
| 835 |
want, _ := url.Parse(test.wantSignedURL) |
| 836 |
gotParams, wantParams := got.Query(), want.Query() |
| 837 |
for _, param := range []string{"GoogleAccessId", "Signature"} { |
| 838 |
if gotParams.Get(param) != wantParams.Get(param) { |
| 839 |
// Print the full URL because the parameter might've not been set at all. |
| 840 |
t.Errorf("Query parameter in SignedURL differs: %v\n -- got URL: %v\n -- want URL: %v", |
| 841 |
param, got, want) |
| 842 |
} |
| 843 |
} |
| 844 |
}) |
| 845 |
} |
| 846 |
} |