| 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 provides a blob implementation that uses GCS. Use OpenBucket |
| 16 |
// to construct a *blob.Bucket. |
| 17 |
// |
| 18 |
// # URLs |
| 19 |
// |
| 20 |
// For blob.OpenBucket, gcsblob registers for the scheme "gs". |
| 21 |
// The default URL opener will set up a connection using default credentials |
| 22 |
// from the environment, as described in |
| 23 |
// https://cloud.google.com/docs/authentication/production. |
| 24 |
// You may force the use of an unauthenticated client by setting |
| 25 |
// GoogleAccessID to "-" (via Options or via the URL parameter "access_id"). |
| 26 |
// Some environments, such as GCE, come without a private key. In such cases |
| 27 |
// the IAM Credentials API will be configured for use in Options.MakeSignBytes, |
| 28 |
// which will introduce latency to any and all calls to bucket.SignedURL |
| 29 |
// that you can avoid by installing a service account credentials file or |
| 30 |
// obtaining and configuring a private key: |
| 31 |
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys |
| 32 |
// |
| 33 |
// To customize the URL opener, or for more details on the URL format, |
| 34 |
// see URLOpener. |
| 35 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 36 |
// |
| 37 |
// # Escaping |
| 38 |
// |
| 39 |
// Go CDK supports all UTF-8 strings; to make this work with services lacking |
| 40 |
// full UTF-8 support, strings must be escaped (during writes) and unescaped |
| 41 |
// (during reads). The following escapes are performed for gcsblob: |
| 42 |
// - Blob keys: ASCII characters 10 and 13 are escaped to "__0x<hex>__". |
| 43 |
// Additionally, the "/" in "../" is escaped in the same way. |
| 44 |
// |
| 45 |
// # As |
| 46 |
// |
| 47 |
// gcsblob exposes the following types for As: |
| 48 |
// - Bucket: *storage.Client |
| 49 |
// - Error: *googleapi.Error |
| 50 |
// - ListObject: storage.ObjectAttrs |
| 51 |
// - ListOptions.BeforeList: *storage.Query |
| 52 |
// - Reader: *storage.Reader |
| 53 |
// - ReaderOptions.BeforeRead: **storage.ObjectHandle, *storage.Reader (if accessing both, must be in that order) |
| 54 |
// - Attributes: storage.ObjectAttrs |
| 55 |
// - CopyOptions.BeforeCopy: *CopyObjectHandles, *storage.Copier (if accessing both, must be in that order) |
| 56 |
// - WriterOptions.BeforeWrite: **storage.ObjectHandle, *storage.Writer (if accessing both, must be in that order) |
| 57 |
// - SignedURLOptions.BeforeSign: *storage.SignedURLOptions |
| 58 |
package gcsblob // import "gocloud.dev/blob/gcsblob" |
| 59 |
|
| 60 |
import ( |
| 61 |
"context" |
| 62 |
"encoding/json" |
| 63 |
"errors" |
| 64 |
"fmt" |
| 65 |
"io" |
| 66 |
"net/http" |
| 67 |
"net/url" |
| 68 |
"os" |
| 69 |
"sort" |
| 70 |
"strconv" |
| 71 |
"strings" |
| 72 |
"sync" |
| 73 |
"time" |
| 74 |
|
| 75 |
"cloud.google.com/go/compute/metadata" |
| 76 |
"cloud.google.com/go/storage" |
| 77 |
"github.com/google/wire" |
| 78 |
"golang.org/x/oauth2/google" |
| 79 |
"google.golang.org/api/googleapi" |
| 80 |
"google.golang.org/api/iterator" |
| 81 |
"google.golang.org/api/option" |
| 82 |
|
| 83 |
"gocloud.dev/blob" |
| 84 |
"gocloud.dev/blob/driver" |
| 85 |
"gocloud.dev/gcerrors" |
| 86 |
"gocloud.dev/gcp" |
| 87 |
"gocloud.dev/internal/escape" |
| 88 |
"gocloud.dev/internal/gcerr" |
| 89 |
"gocloud.dev/internal/useragent" |
| 90 |
) |
| 91 |
|
| 92 |
const defaultPageSize = 1000 |
| 93 |
|
| 94 |
func init() { |
| 95 |
blob.DefaultURLMux().RegisterBucket(Scheme, new(lazyCredsOpener)) |
| 96 |
} |
| 97 |
|
| 98 |
// Set holds Wire providers for this package. |
| 99 |
var Set = wire.NewSet( |
| 100 |
wire.Struct(new(URLOpener), "Client"), |
| 101 |
) |
| 102 |
|
| 103 |
// readDefaultCredentials gets the field values from the supplied JSON data. |
| 104 |
// For its possible formats please see |
| 105 |
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys#iam-service-account-keys-create-go |
| 106 |
// |
| 107 |
// Use "golang.org/x/oauth2/google".DefaultCredentials.JSON to get |
| 108 |
// the contents of the preferred credential file. |
| 109 |
// |
| 110 |
// Returns null-values for fields that have not been obtained. |
| 111 |
func readDefaultCredentials(credFileAsJSON []byte) (AccessID string, PrivateKey []byte) { |
| 112 |
// For example, a credentials file as generated for service accounts through the web console. |
| 113 |
var contentVariantA struct { |
| 114 |
ClientEmail string `json:"client_email"` |
| 115 |
PrivateKey string `json:"private_key"` |
| 116 |
} |
| 117 |
if err := json.Unmarshal(credFileAsJSON, &contentVariantA); err == nil { |
| 118 |
AccessID = contentVariantA.ClientEmail |
| 119 |
PrivateKey = []byte(contentVariantA.PrivateKey) |
| 120 |
} |
| 121 |
if AccessID != "" { |
| 122 |
return |
| 123 |
} |
| 124 |
|
| 125 |
// If obtained through the REST API. |
| 126 |
var contentVariantB struct { |
| 127 |
Name string `json:"name"` |
| 128 |
PrivateKeyData string `json:"privateKeyData"` |
| 129 |
} |
| 130 |
if err := json.Unmarshal(credFileAsJSON, &contentVariantB); err == nil { |
| 131 |
nextFieldIsAccessID := false |
| 132 |
for s := range strings.SplitSeq(contentVariantB.Name, "/") { |
| 133 |
if nextFieldIsAccessID { |
| 134 |
AccessID = s |
| 135 |
break |
| 136 |
} |
| 137 |
nextFieldIsAccessID = s == "serviceAccounts" |
| 138 |
} |
| 139 |
PrivateKey = []byte(contentVariantB.PrivateKeyData) |
| 140 |
} |
| 141 |
|
| 142 |
return |
| 143 |
} |
| 144 |
|
| 145 |
// lazyCredsOpener obtains Application Default Credentials on the first call |
| 146 |
// to OpenBucketURL. |
| 147 |
type lazyCredsOpener struct { |
| 148 |
init sync.Once |
| 149 |
opener *URLOpener |
| 150 |
err error |
| 151 |
} |
| 152 |
|
| 153 |
func (o *lazyCredsOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) { |
| 154 |
o.init.Do(func() { |
| 155 |
var opts Options |
| 156 |
var creds *google.Credentials |
| 157 |
if os.Getenv("STORAGE_EMULATOR_HOST") != "" { |
| 158 |
creds, _ = google.CredentialsFromJSON(ctx, []byte(`{"type": "service_account", "project_id": "my-project-id"}`)) |
| 159 |
} else { |
| 160 |
var err error |
| 161 |
// Check if universe_domain is specified in the URL query parameters |
| 162 |
universeDomain := u.Query().Get("universe_domain") |
| 163 |
if universeDomain != "" { |
| 164 |
creds, err = gcp.DefaultCredentialsWithParams(ctx, google.CredentialsParams{ |
| 165 |
UniverseDomain: universeDomain, |
| 166 |
}) |
| 167 |
} else { |
| 168 |
creds, err = gcp.DefaultCredentials(ctx) |
| 169 |
} |
| 170 |
if err != nil { |
| 171 |
fmt.Printf("Warning: unable to load GCP Default Credentials: %v", err) |
| 172 |
// Use empty credentials, in case the user isn't going to actually use |
| 173 |
// them; e.g., getting signed URLs with GoogleAccessID=-. |
| 174 |
creds, _ = google.CredentialsFromJSON(ctx, []byte(`{"type": "service_account"}`)) |
| 175 |
} |
| 176 |
|
| 177 |
// Populate default values from credentials files, where available. |
| 178 |
opts.GoogleAccessID, opts.PrivateKey = readDefaultCredentials(creds.JSON) |
| 179 |
|
| 180 |
ud, err := creds.GetUniverseDomain() |
| 181 |
if err != nil { |
| 182 |
fmt.Printf("Warning: unable to load GCP Universe Domain: %v", err) |
| 183 |
} else if ud != "" { |
| 184 |
opts.ClientOptions = append(opts.ClientOptions, option.WithUniverseDomain(ud)) |
| 185 |
} |
| 186 |
|
| 187 |
// ... else, on GCE, at least get the instance's main service account. |
| 188 |
if opts.GoogleAccessID == "" && metadata.OnGCE() { |
| 189 |
mc := metadata.NewClient(nil) |
| 190 |
opts.GoogleAccessID, _ = mc.Email("") |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
// Provide a default factory for SignBytes for environments without a private key. |
| 195 |
if len(opts.PrivateKey) <= 0 && opts.GoogleAccessID != "" { |
| 196 |
iam := new(credentialsClient) |
| 197 |
// We cannot hold onto the first context: it might've been cancelled already. |
| 198 |
ctx := context.Background() |
| 199 |
opts.MakeSignBytes = iam.CreateMakeSignBytesWith(ctx, opts.GoogleAccessID) |
| 200 |
} |
| 201 |
|
| 202 |
client, err := gcp.NewHTTPClient(gcp.DefaultTransport(), creds.TokenSource) |
| 203 |
if err != nil { |
| 204 |
o.err = err |
| 205 |
return |
| 206 |
} |
| 207 |
o.opener = &URLOpener{Client: client, Options: opts} |
| 208 |
}) |
| 209 |
if o.err != nil { |
| 210 |
return nil, fmt.Errorf("open bucket %v: %v", u, o.err) |
| 211 |
} |
| 212 |
return o.opener.OpenBucketURL(ctx, u) |
| 213 |
} |
| 214 |
|
| 215 |
// Scheme is the URL scheme gcsblob registers its URLOpener under on |
| 216 |
// blob.DefaultMux. |
| 217 |
const Scheme = "gs" |
| 218 |
|
| 219 |
// URLOpener opens GCS URLs like "gs://mybucket". |
| 220 |
// |
| 221 |
// The URL host is used as the bucket name. |
| 222 |
// |
| 223 |
// The following query parameters are supported: |
| 224 |
// |
| 225 |
// - anonymous: A value of "true" forces the use of an unauthenticated client. |
| 226 |
// - access_id: Sets Options.GoogleAccessID; only used in SignedURL, except that |
| 227 |
// a value of "-" forces the use of an unauthenticated client. |
| 228 |
// - private_key_path: Path to read for Options.PrivateKey; only used in SignedURL. |
| 229 |
// - universe_domain: Sets the universe domain for the client. |
| 230 |
type URLOpener struct { |
| 231 |
// Client must be set to a non-nil HTTP client authenticated with |
| 232 |
// Cloud Storage scope or equivalent (unless anonymous=true). |
| 233 |
Client *gcp.HTTPClient |
| 234 |
|
| 235 |
// Options specifies the default options to pass to OpenBucket. |
| 236 |
Options Options |
| 237 |
} |
| 238 |
|
| 239 |
// OpenBucketURL opens the GCS bucket with the same name as the URL's host. |
| 240 |
func (o *URLOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) { |
| 241 |
opts, client, err := o.forParams(ctx, u.Query()) |
| 242 |
if err != nil { |
| 243 |
return nil, fmt.Errorf("open bucket %v: %v", u, err) |
| 244 |
} |
| 245 |
return OpenBucket(ctx, client, u.Host, opts) |
| 246 |
} |
| 247 |
|
| 248 |
func (o *URLOpener) forParams(ctx context.Context, q url.Values) (*Options, *gcp.HTTPClient, error) { |
| 249 |
for k := range q { |
| 250 |
if k != "access_id" && k != "private_key_path" && k != "anonymous" && k != "universe_domain" { |
| 251 |
return nil, nil, fmt.Errorf("invalid query parameter %q", k) |
| 252 |
} |
| 253 |
} |
| 254 |
opts := new(Options) |
| 255 |
*opts = o.Options |
| 256 |
client := o.Client |
| 257 |
if anon := q.Get("anonymous"); anon != "" { |
| 258 |
isAnon, err := strconv.ParseBool(anon) |
| 259 |
if err != nil { |
| 260 |
return nil, nil, fmt.Errorf("invalid value %q for query parameter \"anonymous\": %w", anon, err) |
| 261 |
} |
| 262 |
if isAnon { |
| 263 |
opts.clear() |
| 264 |
client = gcp.NewAnonymousHTTPClient(gcp.DefaultTransport()) |
| 265 |
} |
| 266 |
} |
| 267 |
if accessID := q.Get("access_id"); accessID != "" && accessID != opts.GoogleAccessID { |
| 268 |
opts.clear() |
| 269 |
if accessID == "-" { |
| 270 |
client = gcp.NewAnonymousHTTPClient(gcp.DefaultTransport()) |
| 271 |
} else { |
| 272 |
opts.GoogleAccessID = accessID |
| 273 |
} |
| 274 |
} |
| 275 |
if keyPath := q.Get("private_key_path"); keyPath != "" { |
| 276 |
pk, err := os.ReadFile(keyPath) |
| 277 |
if err != nil { |
| 278 |
return nil, nil, err |
| 279 |
} |
| 280 |
opts.PrivateKey = pk |
| 281 |
} else if _, exists := q["private_key_path"]; exists { |
| 282 |
// A possible default value has been cleared by setting this to an empty value: |
| 283 |
// The private key might have expired, or falling back to SignBytes/MakeSignBytes |
| 284 |
// is intentional such as for tests or involving a key stored in a HSM/TPM. |
| 285 |
opts.PrivateKey = nil |
| 286 |
} |
| 287 |
return opts, client, nil |
| 288 |
} |
| 289 |
|
| 290 |
// Options sets options for constructing a *blob.Bucket backed by GCS. |
| 291 |
type Options struct { |
| 292 |
// GoogleAccessID represents the authorizer for SignedURL. |
| 293 |
// If set to "-", an unauthenticated client will be used. |
| 294 |
// Required to use SignedURL. |
| 295 |
// See https://godoc.org/cloud.google.com/go/storage#SignedURLOptions. |
| 296 |
GoogleAccessID string |
| 297 |
|
| 298 |
// PrivateKey is the Google service account private key. |
| 299 |
// Exactly one of PrivateKey or SignBytes must be non-nil to use SignedURL. |
| 300 |
// See https://godoc.org/cloud.google.com/go/storage#SignedURLOptions. |
| 301 |
// Deprecated: Use MakeSignBytes instead. |
| 302 |
PrivateKey []byte |
| 303 |
|
| 304 |
// SignBytes is a function for implementing custom signing. |
| 305 |
// Exactly one of PrivateKey, SignBytes, or MakeSignBytes must be non-nil to use SignedURL. |
| 306 |
// See https://godoc.org/cloud.google.com/go/storage#SignedURLOptions. |
| 307 |
// Deprecated: Use MakeSignBytes instead. |
| 308 |
SignBytes func([]byte) ([]byte, error) |
| 309 |
|
| 310 |
// MakeSignBytes is a factory for functions that are being used in place of an empty SignBytes. |
| 311 |
// If your implementation of 'SignBytes' needs a request context, set this instead. |
| 312 |
MakeSignBytes func(requestCtx context.Context) SignBytesFunc |
| 313 |
|
| 314 |
// Client provides a *storage.Client to use, instead of constructing one based on |
| 315 |
// the HTTPClient. When set, you must pass nil as the gcp.HTTPClient to OpenBucket. |
| 316 |
// |
| 317 |
// For example, this can be used to create a Bucket backed by a gRPC client. |
| 318 |
Client *storage.Client |
| 319 |
|
| 320 |
// ClientOptions are passed when constructing the storage.Client. |
| 321 |
// Ignored if Client is set. |
| 322 |
ClientOptions []option.ClientOption |
| 323 |
} |
| 324 |
|
| 325 |
// clear clears all the fields of o. |
| 326 |
func (o *Options) clear() { |
| 327 |
o.GoogleAccessID = "" |
| 328 |
o.PrivateKey = nil |
| 329 |
o.SignBytes = nil |
| 330 |
o.MakeSignBytes = nil |
| 331 |
} |
| 332 |
|
| 333 |
// SignBytesFunc is shorthand for the signature of Options.SignBytes. |
| 334 |
type SignBytesFunc func([]byte) ([]byte, error) |
| 335 |
|
| 336 |
// openBucket returns a GCS Bucket that communicates using the given HTTP client. |
| 337 |
func openBucket(ctx context.Context, client *gcp.HTTPClient, bucketName string, opts *Options) (*bucket, error) { |
| 338 |
if opts == nil { |
| 339 |
opts = &Options{} |
| 340 |
} |
| 341 |
if bucketName == "" { |
| 342 |
return nil, errors.New("gcsblob.OpenBucket: bucketName is required") |
| 343 |
} |
| 344 |
if opts.Client != nil { |
| 345 |
if client != nil { |
| 346 |
return nil, errors.New("gcsblob.OpenBucket: client must be nil when providing Options.Client") |
| 347 |
} |
| 348 |
return &bucket{name: bucketName, client: opts.Client, opts: opts}, nil |
| 349 |
} |
| 350 |
if client == nil { |
| 351 |
return nil, errors.New("gcsblob.OpenBucket: client is required") |
| 352 |
} |
| 353 |
|
| 354 |
// We wrap the provided http.Client to add a Go CDK User-Agent. |
| 355 |
clientOpts := []option.ClientOption{option.WithHTTPClient(useragent.HTTPClient(&client.Client, "blob"))} |
| 356 |
if host := os.Getenv("STORAGE_EMULATOR_HOST"); host != "" { |
| 357 |
clientOpts = []option.ClientOption{ |
| 358 |
option.WithoutAuthentication(), |
| 359 |
option.WithEndpoint("http://" + host + "/storage/v1/"), |
| 360 |
option.WithHTTPClient(http.DefaultClient), |
| 361 |
} |
| 362 |
} |
| 363 |
clientOpts = append(clientOpts, opts.ClientOptions...) |
| 364 |
c, err := storage.NewClient(ctx, clientOpts...) |
| 365 |
if err != nil { |
| 366 |
return nil, err |
| 367 |
} |
| 368 |
return &bucket{name: bucketName, client: c, opts: opts}, nil |
| 369 |
} |
| 370 |
|
| 371 |
// OpenBucket returns a *blob.Bucket backed by an existing GCS bucket. See the |
| 372 |
// package documentation for an example. |
| 373 |
func OpenBucket(ctx context.Context, client *gcp.HTTPClient, bucketName string, opts *Options) (*blob.Bucket, error) { |
| 374 |
drv, err := openBucket(ctx, client, bucketName, opts) |
| 375 |
if err != nil { |
| 376 |
return nil, err |
| 377 |
} |
| 378 |
return blob.NewBucket(drv), nil |
| 379 |
} |
| 380 |
|
| 381 |
// bucket represents a GCS bucket, which handles read, write and delete operations |
| 382 |
// on objects within it. |
| 383 |
type bucket struct { |
| 384 |
name string |
| 385 |
client *storage.Client |
| 386 |
opts *Options |
| 387 |
} |
| 388 |
|
| 389 |
var emptyBody = io.NopCloser(strings.NewReader("")) |
| 390 |
|
| 391 |
// reader reads a GCS object. It implements driver.Reader. |
| 392 |
type reader struct { |
| 393 |
body io.ReadCloser |
| 394 |
attrs driver.ReaderAttributes |
| 395 |
raw *storage.Reader |
| 396 |
} |
| 397 |
|
| 398 |
func (r *reader) Read(p []byte) (int, error) { |
| 399 |
return r.body.Read(p) |
| 400 |
} |
| 401 |
|
| 402 |
// Close closes the reader itself. It must be called when done reading. |
| 403 |
func (r *reader) Close() error { |
| 404 |
return r.body.Close() |
| 405 |
} |
| 406 |
|
| 407 |
func (r *reader) Attributes() *driver.ReaderAttributes { |
| 408 |
return &r.attrs |
| 409 |
} |
| 410 |
|
| 411 |
func (r *reader) As(i any) bool { |
| 412 |
p, ok := i.(**storage.Reader) |
| 413 |
if !ok { |
| 414 |
return false |
| 415 |
} |
| 416 |
*p = r.raw |
| 417 |
return true |
| 418 |
} |
| 419 |
|
| 420 |
func (b *bucket) ErrorCode(err error) gcerrors.ErrorCode { |
| 421 |
if errors.Is(err, storage.ErrObjectNotExist) || errors.Is(err, storage.ErrBucketNotExist) { |
| 422 |
return gcerrors.NotFound |
| 423 |
} |
| 424 |
if gerr, ok := err.(*googleapi.Error); ok { |
| 425 |
switch gerr.Code { |
| 426 |
case http.StatusForbidden: |
| 427 |
// 'Permission 'storage.objects.list' denied on resource (or it may not exist)' |
| 428 |
// So we have to pick one. |
| 429 |
return gcerrors.NotFound |
| 430 |
case http.StatusNotFound: |
| 431 |
return gcerrors.NotFound |
| 432 |
case http.StatusPreconditionFailed: |
| 433 |
return gcerrors.FailedPrecondition |
| 434 |
case http.StatusTooManyRequests: |
| 435 |
return gcerrors.ResourceExhausted |
| 436 |
} |
| 437 |
} |
| 438 |
return gcerrors.Unknown |
| 439 |
} |
| 440 |
|
| 441 |
func (b *bucket) Close() error { |
| 442 |
return nil |
| 443 |
} |
| 444 |
|
| 445 |
// ListPaged implements driver.ListPaged. |
| 446 |
func (b *bucket) ListPaged(ctx context.Context, opts *driver.ListOptions) (*driver.ListPage, error) { |
| 447 |
bkt := b.client.Bucket(b.name) |
| 448 |
query := &storage.Query{ |
| 449 |
Prefix: escapeKey(opts.Prefix), |
| 450 |
Delimiter: escapeKey(opts.Delimiter), |
| 451 |
} |
| 452 |
if opts.BeforeList != nil { |
| 453 |
asFunc := func(i any) bool { |
| 454 |
p, ok := i.(**storage.Query) |
| 455 |
if !ok { |
| 456 |
return false |
| 457 |
} |
| 458 |
*p = query |
| 459 |
return true |
| 460 |
} |
| 461 |
if err := opts.BeforeList(asFunc); err != nil { |
| 462 |
return nil, err |
| 463 |
} |
| 464 |
} |
| 465 |
pageSize := opts.PageSize |
| 466 |
if pageSize == 0 { |
| 467 |
pageSize = defaultPageSize |
| 468 |
} |
| 469 |
iter := bkt.Objects(ctx, query) |
| 470 |
pager := iterator.NewPager(iter, pageSize, string(opts.PageToken)) |
| 471 |
var objects []*storage.ObjectAttrs |
| 472 |
nextPageToken, err := pager.NextPage(&objects) |
| 473 |
if err != nil { |
| 474 |
return nil, err |
| 475 |
} |
| 476 |
page := driver.ListPage{NextPageToken: []byte(nextPageToken)} |
| 477 |
if len(objects) > 0 { |
| 478 |
page.Objects = make([]*driver.ListObject, len(objects)) |
| 479 |
for i, obj := range objects { |
| 480 |
toCopy := obj |
| 481 |
asFunc := func(val any) bool { |
| 482 |
p, ok := val.(*storage.ObjectAttrs) |
| 483 |
if !ok { |
| 484 |
return false |
| 485 |
} |
| 486 |
*p = *toCopy |
| 487 |
return true |
| 488 |
} |
| 489 |
if obj.Prefix == "" { |
| 490 |
// Regular blob. |
| 491 |
page.Objects[i] = &driver.ListObject{ |
| 492 |
Key: unescapeKey(obj.Name), |
| 493 |
ModTime: obj.Updated, |
| 494 |
Size: obj.Size, |
| 495 |
MD5: obj.MD5, |
| 496 |
AsFunc: asFunc, |
| 497 |
} |
| 498 |
} else { |
| 499 |
// "Directory". |
| 500 |
page.Objects[i] = &driver.ListObject{ |
| 501 |
Key: unescapeKey(obj.Prefix), |
| 502 |
IsDir: true, |
| 503 |
AsFunc: asFunc, |
| 504 |
} |
| 505 |
} |
| 506 |
} |
| 507 |
// GCS always returns "directories" at the end; sort them. |
| 508 |
sort.Slice(page.Objects, func(i, j int) bool { |
| 509 |
return page.Objects[i].Key < page.Objects[j].Key |
| 510 |
}) |
| 511 |
} |
| 512 |
return &page, nil |
| 513 |
} |
| 514 |
|
| 515 |
// As implements driver.As. |
| 516 |
func (b *bucket) As(i any) bool { |
| 517 |
p, ok := i.(**storage.Client) |
| 518 |
if !ok { |
| 519 |
return false |
| 520 |
} |
| 521 |
*p = b.client |
| 522 |
return true |
| 523 |
} |
| 524 |
|
| 525 |
// As implements driver.ErrorAs. |
| 526 |
func (b *bucket) ErrorAs(err error, i any) bool { |
| 527 |
switch v := err.(type) { |
| 528 |
case *googleapi.Error: |
| 529 |
if p, ok := i.(**googleapi.Error); ok { |
| 530 |
*p = v |
| 531 |
return true |
| 532 |
} |
| 533 |
} |
| 534 |
return false |
| 535 |
} |
| 536 |
|
| 537 |
// Attributes implements driver.Attributes. |
| 538 |
func (b *bucket) Attributes(ctx context.Context, key string) (*driver.Attributes, error) { |
| 539 |
key = escapeKey(key) |
| 540 |
bkt := b.client.Bucket(b.name) |
| 541 |
obj := bkt.Object(key) |
| 542 |
attrs, err := obj.Attrs(ctx) |
| 543 |
if err != nil { |
| 544 |
return nil, err |
| 545 |
} |
| 546 |
// GCS seems to unquote the ETag; restore them. |
| 547 |
// It should be of the form "xxxx" or W/"xxxx". |
| 548 |
eTag := attrs.Etag |
| 549 |
if !strings.HasPrefix(eTag, "W/\"") && !strings.HasPrefix(eTag, "\"") && !strings.HasSuffix(eTag, "\"") { |
| 550 |
eTag = fmt.Sprintf("%q", eTag) |
| 551 |
} |
| 552 |
return &driver.Attributes{ |
| 553 |
CacheControl: attrs.CacheControl, |
| 554 |
ContentDisposition: attrs.ContentDisposition, |
| 555 |
ContentEncoding: attrs.ContentEncoding, |
| 556 |
ContentLanguage: attrs.ContentLanguage, |
| 557 |
ContentType: attrs.ContentType, |
| 558 |
Metadata: attrs.Metadata, |
| 559 |
CreateTime: attrs.Created, |
| 560 |
ModTime: attrs.Updated, |
| 561 |
Size: attrs.Size, |
| 562 |
MD5: attrs.MD5, |
| 563 |
ETag: eTag, |
| 564 |
AsFunc: func(i any) bool { |
| 565 |
p, ok := i.(*storage.ObjectAttrs) |
| 566 |
if !ok { |
| 567 |
return false |
| 568 |
} |
| 569 |
*p = *attrs |
| 570 |
return true |
| 571 |
}, |
| 572 |
}, nil |
| 573 |
} |
| 574 |
|
| 575 |
// NewRangeReader implements driver.NewRangeReader. |
| 576 |
func (b *bucket) NewRangeReader(ctx context.Context, key string, offset, length int64, opts *driver.ReaderOptions) (driver.Reader, error) { |
| 577 |
key = escapeKey(key) |
| 578 |
bkt := b.client.Bucket(b.name) |
| 579 |
obj := bkt.Object(key) |
| 580 |
|
| 581 |
// Add an extra level of indirection so that BeforeRead can replace obj |
| 582 |
// if needed. For example, ObjectHandle.If returns a new ObjectHandle. |
| 583 |
// Also, make the Reader lazily in case this replacement happens. |
| 584 |
objp := &obj |
| 585 |
makeReader := func() (*storage.Reader, error) { |
| 586 |
return (*objp).NewRangeReader(ctx, offset, length) |
| 587 |
} |
| 588 |
|
| 589 |
var r *storage.Reader |
| 590 |
var rerr error |
| 591 |
madeReader := false |
| 592 |
if opts.BeforeRead != nil { |
| 593 |
asFunc := func(i any) bool { |
| 594 |
if p, ok := i.(***storage.ObjectHandle); ok && !madeReader { |
| 595 |
*p = objp |
| 596 |
return true |
| 597 |
} |
| 598 |
if p, ok := i.(**storage.Reader); ok { |
| 599 |
if !madeReader { |
| 600 |
r, rerr = makeReader() |
| 601 |
madeReader = true |
| 602 |
if r == nil { |
| 603 |
return false |
| 604 |
} |
| 605 |
} |
| 606 |
*p = r |
| 607 |
return true |
| 608 |
} |
| 609 |
return false |
| 610 |
} |
| 611 |
if err := opts.BeforeRead(asFunc); err != nil { |
| 612 |
return nil, err |
| 613 |
} |
| 614 |
} |
| 615 |
if !madeReader { |
| 616 |
r, rerr = makeReader() |
| 617 |
} |
| 618 |
if rerr != nil { |
| 619 |
return nil, rerr |
| 620 |
} |
| 621 |
return &reader{ |
| 622 |
body: r, |
| 623 |
attrs: driver.ReaderAttributes{ |
| 624 |
ContentType: r.Attrs.ContentType, |
| 625 |
ModTime: r.Attrs.LastModified, |
| 626 |
Size: r.Attrs.Size, |
| 627 |
}, |
| 628 |
raw: r, |
| 629 |
}, nil |
| 630 |
} |
| 631 |
|
| 632 |
// escapeKey does all required escaping for UTF-8 strings to work with GCS. |
| 633 |
func escapeKey(key string) string { |
| 634 |
return escape.HexEscape(key, func(r []rune, i int) bool { |
| 635 |
switch { |
| 636 |
// GCS doesn't handle these characters (determined via experimentation). |
| 637 |
case r[i] == 10 || r[i] == 13: |
| 638 |
return true |
| 639 |
// For "../", escape the trailing slash. |
| 640 |
case i > 1 && r[i] == '/' && r[i-1] == '.' && r[i-2] == '.': |
| 641 |
return true |
| 642 |
} |
| 643 |
return false |
| 644 |
}) |
| 645 |
} |
| 646 |
|
| 647 |
// unescapeKey reverses escapeKey. |
| 648 |
func unescapeKey(key string) string { |
| 649 |
return escape.HexUnescape(key) |
| 650 |
} |
| 651 |
|
| 652 |
// NewTypedWriter implements driver.NewTypedWriter. |
| 653 |
func (b *bucket) NewTypedWriter(ctx context.Context, key, contentType string, opts *driver.WriterOptions) (driver.Writer, error) { |
| 654 |
key = escapeKey(key) |
| 655 |
bkt := b.client.Bucket(b.name) |
| 656 |
obj := bkt.Object(key) |
| 657 |
|
| 658 |
if opts.IfNotExist { |
| 659 |
obj = obj.If(storage.Conditions{DoesNotExist: true}) |
| 660 |
} |
| 661 |
// Add an extra level of indirection so that BeforeWrite can replace obj |
| 662 |
// if needed. For example, ObjectHandle.If returns a new ObjectHandle. |
| 663 |
// Also, make the Writer lazily in case this replacement happens. |
| 664 |
objp := &obj |
| 665 |
makeWriter := func() *storage.Writer { |
| 666 |
w := (*objp).NewWriter(ctx) |
| 667 |
w.CacheControl = opts.CacheControl |
| 668 |
w.ContentDisposition = opts.ContentDisposition |
| 669 |
w.ContentEncoding = opts.ContentEncoding |
| 670 |
w.ContentLanguage = opts.ContentLanguage |
| 671 |
w.ContentType = contentType |
| 672 |
w.ChunkSize = bufferSize(opts.BufferSize) |
| 673 |
w.Metadata = opts.Metadata |
| 674 |
w.MD5 = opts.ContentMD5 |
| 675 |
w.ForceEmptyContentType = opts.DisableContentTypeDetection |
| 676 |
return w |
| 677 |
} |
| 678 |
|
| 679 |
var w *storage.Writer |
| 680 |
if opts.BeforeWrite != nil { |
| 681 |
asFunc := func(i any) bool { |
| 682 |
if p, ok := i.(***storage.ObjectHandle); ok && w == nil { |
| 683 |
*p = objp |
| 684 |
return true |
| 685 |
} |
| 686 |
if p, ok := i.(**storage.Writer); ok { |
| 687 |
if w == nil { |
| 688 |
w = makeWriter() |
| 689 |
} |
| 690 |
*p = w |
| 691 |
return true |
| 692 |
} |
| 693 |
return false |
| 694 |
} |
| 695 |
if err := opts.BeforeWrite(asFunc); err != nil { |
| 696 |
return nil, err |
| 697 |
} |
| 698 |
} |
| 699 |
if w == nil { |
| 700 |
w = makeWriter() |
| 701 |
} |
| 702 |
return w, nil |
| 703 |
} |
| 704 |
|
| 705 |
// CopyObjectHandles holds the ObjectHandles for the destination and source |
| 706 |
// of a Copy. It is used by the BeforeCopy As hook. |
| 707 |
type CopyObjectHandles struct { |
| 708 |
Dst, Src *storage.ObjectHandle |
| 709 |
} |
| 710 |
|
| 711 |
// Copy implements driver.Copy. |
| 712 |
func (b *bucket) Copy(ctx context.Context, dstKey, srcKey string, opts *driver.CopyOptions) error { |
| 713 |
dstKey = escapeKey(dstKey) |
| 714 |
srcKey = escapeKey(srcKey) |
| 715 |
bkt := b.client.Bucket(b.name) |
| 716 |
|
| 717 |
// Add an extra level of indirection so that BeforeCopy can replace the |
| 718 |
// dst or src ObjectHandles if needed. |
| 719 |
// Also, make the Copier lazily in case this replacement happens. |
| 720 |
handles := CopyObjectHandles{ |
| 721 |
Dst: bkt.Object(dstKey), |
| 722 |
Src: bkt.Object(srcKey), |
| 723 |
} |
| 724 |
makeCopier := func() *storage.Copier { |
| 725 |
return handles.Dst.CopierFrom(handles.Src) |
| 726 |
} |
| 727 |
|
| 728 |
var copier *storage.Copier |
| 729 |
if opts.BeforeCopy != nil { |
| 730 |
asFunc := func(i any) bool { |
| 731 |
if p, ok := i.(**CopyObjectHandles); ok && copier == nil { |
| 732 |
*p = &handles |
| 733 |
return true |
| 734 |
} |
| 735 |
if p, ok := i.(**storage.Copier); ok { |
| 736 |
if copier == nil { |
| 737 |
copier = makeCopier() |
| 738 |
} |
| 739 |
*p = copier |
| 740 |
return true |
| 741 |
} |
| 742 |
return false |
| 743 |
} |
| 744 |
if err := opts.BeforeCopy(asFunc); err != nil { |
| 745 |
return err |
| 746 |
} |
| 747 |
} |
| 748 |
if copier == nil { |
| 749 |
copier = makeCopier() |
| 750 |
} |
| 751 |
_, err := copier.Run(ctx) |
| 752 |
return err |
| 753 |
} |
| 754 |
|
| 755 |
// Delete implements driver.Delete. |
| 756 |
func (b *bucket) Delete(ctx context.Context, key string) error { |
| 757 |
key = escapeKey(key) |
| 758 |
bkt := b.client.Bucket(b.name) |
| 759 |
obj := bkt.Object(key) |
| 760 |
return obj.Delete(ctx) |
| 761 |
} |
| 762 |
|
| 763 |
func (b *bucket) SignedURL(ctx context.Context, key string, dopts *driver.SignedURLOptions) (string, error) { |
| 764 |
numSigners := 0 |
| 765 |
if b.opts.PrivateKey != nil { |
| 766 |
numSigners++ |
| 767 |
} |
| 768 |
if b.opts.SignBytes != nil { |
| 769 |
numSigners++ |
| 770 |
} |
| 771 |
if b.opts.MakeSignBytes != nil { |
| 772 |
numSigners++ |
| 773 |
} |
| 774 |
if b.opts.GoogleAccessID == "" || numSigners != 1 { |
| 775 |
return "", gcerr.New(gcerr.Unimplemented, nil, 1, "gcsblob: to use SignedURL, you must call OpenBucket with a valid Options.GoogleAccessID and exactly one of Options.PrivateKey, Options.SignBytes, or Options.MakeSignBytes") |
| 776 |
} |
| 777 |
|
| 778 |
key = escapeKey(key) |
| 779 |
opts := &storage.SignedURLOptions{ |
| 780 |
Expires: time.Now().Add(dopts.Expiry), |
| 781 |
Method: dopts.Method, |
| 782 |
ContentType: dopts.ContentType, |
| 783 |
GoogleAccessID: b.opts.GoogleAccessID, |
| 784 |
PrivateKey: b.opts.PrivateKey, |
| 785 |
SignBytes: b.opts.SignBytes, |
| 786 |
} |
| 787 |
if b.opts.MakeSignBytes != nil { |
| 788 |
opts.SignBytes = b.opts.MakeSignBytes(ctx) |
| 789 |
} |
| 790 |
if dopts.BeforeSign != nil { |
| 791 |
asFunc := func(i any) bool { |
| 792 |
v, ok := i.(**storage.SignedURLOptions) |
| 793 |
if ok { |
| 794 |
*v = opts |
| 795 |
} |
| 796 |
return ok |
| 797 |
} |
| 798 |
if err := dopts.BeforeSign(asFunc); err != nil { |
| 799 |
return "", err |
| 800 |
} |
| 801 |
} |
| 802 |
return storage.SignedURL(b.name, key, opts) |
| 803 |
} |
| 804 |
|
| 805 |
func bufferSize(size int) int { |
| 806 |
if size == 0 { |
| 807 |
return googleapi.DefaultUploadChunkSize |
| 808 |
} else if size > 0 { |
| 809 |
return size |
| 810 |
} |
| 811 |
return 0 // disable buffering |
| 812 |
} |