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 (
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	
	
	
	raw 
	htransport 
)
Methods which can be used in signed URLs.
var signedURLMethods = map[string]bool{"DELETE": true, "GET": true, "HEAD": true, "POST": true, "PUT": true}

ErrBucketNotExist indicates that the bucket does not exist.
ErrObjectNotExist indicates that the object does not exist.
errMethodNotValid indicates that given HTTP method is not valid.
	errMethodNotValid = fmt.Errorf("storage: HTTP method should be one of %v", reflect.ValueOf(signedURLMethods).MapKeys())
)

var userAgent = fmt.Sprintf("gcloud-golang-storage/%s", version.Repo)

ScopeFullControl grants permissions to manage your data and permissions in Google Cloud Storage.
ScopeReadOnly grants permissions to view your data in Google Cloud Storage.
ScopeReadWrite grants permissions to manage your data in Google Cloud Storage.
	ScopeReadWrite = raw.DevstorageReadWriteScope
)

var xGoogHeader = fmt.Sprintf("gl-go/%s gccl/%s", version.Go(), version.Repo)

func ( http.Header) {
	.Set("x-goog-api-client", xGoogHeader)
}
Client is a client for interacting with Google Cloud Storage. Clients should be reused instead of created as needed. The methods of Client are safe for concurrent use by multiple goroutines.
type Client struct {
	hc  *http.Client
Scheme describes the scheme under the current host.
EnvHost is the host set on the STORAGE_EMULATOR_HOST variable.
ReadHost is the default host used on the reader.
NewClient creates a new Google Cloud Storage client. The default scope is ScopeFullControl. To use a different scope, like ScopeReadOnly, use option.WithScopes.
func ( context.Context,  ...option.ClientOption) (*Client, error) {
	var , ,  string

	if  = os.Getenv("STORAGE_EMULATOR_HOST");  == "" {
		 = "https"
		 = "storage.googleapis.com"
Prepend default options to avoid overriding options passed by the user.
		 = append([]option.ClientOption{option.WithScopes(ScopeFullControl), option.WithUserAgent(userAgent)}, ...)
	} else {
		 = "http"
		 = 

		 = append([]option.ClientOption{option.WithoutAuthentication()}, ...)
	}

	, ,  := htransport.NewClient(, ...)
	if  != nil {
		return nil, fmt.Errorf("dialing: %v", )
	}
	,  := raw.NewService(, option.WithHTTPClient())
	if  != nil {
		return nil, fmt.Errorf("storage client: %v", )
	}
Override the default value for BasePath from the raw client. TODO: remove when the raw client uses this endpoint as its default (~end of 2020)
		.BasePath = "https://storage.googleapis.com/storage/v1/"
If the endpoint has been set explicitly, use this for the BasePath as well as readHost
		.BasePath = 
		,  := url.Parse()
		if  != nil {
			return nil, fmt.Errorf("supplied endpoint %v is not valid: %v", , )
		}
		 = .Host
	}

	return &Client{
		hc:       ,
		raw:      ,
		scheme:   ,
		envHost:  ,
		readHost: ,
	}, nil
}
Close closes the Client. Close need not be called at program exit.
Set fields to nil so that subsequent uses will panic.
	.hc = nil
	.raw = nil
	return nil
}
SigningScheme determines the API version to use when signing URLs.
SigningSchemeDefault is presently V2 and will change to V4 in the future.
SigningSchemeV2 uses the V2 scheme to sign URLs.
SigningSchemeV4 uses the V4 scheme to sign URLs.
URLStyle determines the style to use for the signed URL. pathStyle is the default. All non-default options work with V4 scheme only. See https://cloud.google.com/storage/docs/request-endpoints for details.
host should return the host portion of the signed URL, not including the scheme (e.g. storage.googleapis.com).
	host(bucket string) string
path should return the path portion of the signed URL, which may include both the bucket and object name or only the object name depending on the style.
	path(bucket, object string) string
}

type pathStyle struct{}

type virtualHostedStyle struct{}

type bucketBoundHostname struct {
	hostname string
}

func ( pathStyle) ( string) string {
	return "storage.googleapis.com"
}

func ( virtualHostedStyle) ( string) string {
	return  + ".storage.googleapis.com"
}

func ( bucketBoundHostname) ( string) string {
	return .hostname
}

func ( pathStyle) (,  string) string {
	 := 
	if  != "" {
		 += "/" + 
	}
	return 
}

func ( virtualHostedStyle) (,  string) string {
	return 
}

func ( bucketBoundHostname) (,  string) string {
	return 
}
PathStyle is the default style, and will generate a URL of the form "storage.googleapis.com/<bucket-name>/<object-name>".
func () URLStyle {
	return pathStyle{}
}
VirtualHostedStyle generates a URL relative to the bucket's virtual hostname, e.g. "<bucket-name>.storage.googleapis.com/<object-name>".
BucketBoundHostname generates a URL with a custom hostname tied to a specific GCS bucket. The desired hostname should be passed in using the hostname argument. Generated urls will be of the form "<bucket-bound-hostname>/<object-name>". See https://cloud.google.com/storage/docs/request-endpoints#cname and https://cloud.google.com/load-balancing/docs/https/adding-backend-buckets-to-load-balancers for details. Note that for CNAMEs, only HTTP is supported, so Insecure must be set to true.
func ( string) URLStyle {
	return bucketBoundHostname{hostname: }
}
SignedURLOptions allows you to restrict the access to the signed URL.
GoogleAccessID represents the authorizer of the signed URL generation. It is typically the Google service account client email address from the Google Developers Console in the form of "xxx@developer.gserviceaccount.com". Required.
PrivateKey is the Google service account private key. It is obtainable from the Google Developers Console. At https://console.developers.google.com/project/<your-project-id>/apiui/credential, create a service account client ID or reuse one of your existing service account credentials. Click on the "Generate new P12 key" to generate and download a new private key. Once you download the P12 file, use the following command to convert it into a PEM file. $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes Provide the contents of the PEM file as a byte slice. Exactly one of PrivateKey or SignBytes must be non-nil.
SignBytes is a function for implementing custom signing. For example, if your application is running on Google App Engine, you can use appengine's internal signing function: ctx := appengine.NewContext(request) acc, _ := appengine.ServiceAccount(ctx) url, err := SignedURL("bucket", "object", &SignedURLOptions{ GoogleAccessID: acc, SignBytes: func(b []byte) ([]byte, error) { _, signedBytes, err := appengine.SignBytes(ctx, b) return signedBytes, err }, // etc. }) Exactly one of PrivateKey or SignBytes must be non-nil.
	SignBytes func([]byte) ([]byte, error)
Method is the HTTP method to be used with the signed URL. Signed URLs can be used with GET, HEAD, PUT, and DELETE requests. Required.
Expires is the expiration time on the signed URL. It must be a datetime in the future. For SigningSchemeV4, the expiration may be no more than seven days in the future. Required.
ContentType is the content type header the client must provide to use the generated signed URL. Optional.
Headers is a list of extension headers the client must provide in order to use the generated signed URL. Each must be a string of the form "key:values", with multiple values separated by a semicolon. Optional.
QueryParameters is a map of additional query parameters. When SigningScheme is V4, this is used in computing the signature, and the client must use the same query parameters when using the generated signed URL. Optional.
MD5 is the base64 encoded MD5 checksum of the file. If provided, the client should provide the exact value on the request header in order to use the signed URL. Optional.
Style provides options for the type of URL to use. Options are PathStyle (default), BucketBoundHostname, and VirtualHostedStyle. See https://cloud.google.com/storage/docs/request-endpoints for details. Only supported for V4 signing. Optional.
Insecure determines whether the signed URL should use HTTPS (default) or HTTP. Only supported for V4 signing. Optional.
Scheme determines the version of URL signing to use. Default is SigningSchemeV2.
I was tempted to call this spacex. :)
	spaceRegex = regexp.MustCompile(` +`)

	canonicalHeaderRegexp    = regexp.MustCompile(`(?i)^(x-goog-[^:]+):(.*)?$`)
	excludedCanonicalHeaders = map[string]bool{
		"x-goog-encryption-key":        true,
		"x-goog-encryption-key-sha256": true,
	}
)
v2SanitizeHeaders applies the specifications for canonical extension headers at https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers.
func ( []string) []string {
	 := map[string][]string{}
No leading or trailing whitespaces.
		 := strings.TrimSpace()

Only keep canonical headers, discard any others.
		 := canonicalHeaderRegexp.FindStringSubmatch()
		if len() == 0 {
			continue
		}
		 = [1]
		 = [2]

		 = strings.ToLower(strings.TrimSpace())
		 = strings.TrimSpace()

Do not keep any deliberately excluded canonical headers when signing.
			continue
		}

Remove duplicate headers by appending the values of duplicates in their order of appearance.
			[] = append([], )
		}
	}

	var  []string
There should be no spaces around the colon separating the header name from the header value or around the values themselves. The values should be separated by commas. NOTE: The semantics for headers without a value are not clear. However from specifications these should be edge-cases anyway and we should assume that there will be no canonical headers using empty values. Any such headers are discarded at the regexp stage above.
		 = append(, fmt.Sprintf("%s:%s", , strings.Join(, ",")))
	}
	sort.Strings()
	return 
}
v4SanitizeHeaders applies the specifications for canonical extension headers at https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers. V4 does a couple things differently from V2: - Headers get sorted by key, instead of by key:value. We do this in signedURLV4. - There's no canonical regexp: we simply split headers on :. - We don't exclude canonical headers. - We replace leading and trailing spaces in header values, like v2, but also all intermediate space duplicates get stripped. That is, there's only ever a single consecutive space.
func ( []string) []string {
	 := map[string][]string{}
No leading or trailing whitespaces.
		 := strings.TrimSpace()

		var ,  string
		 := strings.Split(, ":")
		if len() < 2 {
			continue
		}

		 = [0]
		 = [1]

		 = strings.ToLower(strings.TrimSpace())
		 = strings.TrimSpace()
		 = string(spaceRegex.ReplaceAll([]byte(), []byte(" ")))
		 = string(tabRegex.ReplaceAll([]byte(), []byte("\t")))

Remove duplicate headers by appending the values of duplicates in their order of appearance.
			[] = append([], )
		}
	}

	var  []string
There should be no spaces around the colon separating the header name from the header value or around the values themselves. The values should be separated by commas. NOTE: The semantics for headers without a value are not clear. However from specifications these should be edge-cases anyway and we should assume that there will be no canonical headers using empty values. Any such headers are discarded at the regexp stage above.
		 = append(, fmt.Sprintf("%s:%s", , strings.Join(, ",")))
	}
	return 
}
SignedURL returns a URL for the specified object. Signed URLs allow the users access to a restricted resource for a limited time without having a Google account or signing in. For more information about the signed URLs, see https://cloud.google.com/storage/docs/accesscontrol#Signed-URLs.
func (,  string,  *SignedURLOptions) (string, error) {
	 := utcNow()
	if  := validateOptions(, );  != nil {
		return "", 
	}

	switch .Scheme {
	case SigningSchemeV2:
		.Headers = v2SanitizeHeaders(.Headers)
		return signedURLV2(, , )
	case SigningSchemeV4:
		.Headers = v4SanitizeHeaders(.Headers)
		return signedURLV4(, , , )
	default: // SigningSchemeDefault
		.Headers = v2SanitizeHeaders(.Headers)
		return signedURLV2(, , )
	}
}

func ( *SignedURLOptions,  time.Time) error {
	if  == nil {
		return errors.New("storage: missing required SignedURLOptions")
	}
	if .GoogleAccessID == "" {
		return errors.New("storage: missing required GoogleAccessID")
	}
	if (.PrivateKey == nil) == (.SignBytes == nil) {
		return errors.New("storage: exactly one of PrivateKey or SignedBytes must be set")
	}
	.Method = strings.ToUpper(.Method)
	if ,  := signedURLMethods[.Method]; ! {
		return errMethodNotValid
	}
	if .Expires.IsZero() {
		return errors.New("storage: missing required expires option")
	}
	if .MD5 != "" {
		,  := base64.StdEncoding.DecodeString(.MD5)
		if  != nil || len() != 16 {
			return errors.New("storage: invalid MD5 checksum")
		}
	}
	if .Style == nil {
		.Style = PathStyle()
	}
	if ,  := .Style.(pathStyle); ! && .Scheme == SigningSchemeV2 {
		return errors.New("storage: only path-style URLs are permitted with SigningSchemeV2")
	}
	if .Scheme == SigningSchemeV4 {
		 := .Add(604801 * time.Second) // 7 days + 1 second
		if !.Expires.Before() {
			return errors.New("storage: expires must be within seven days from now")
		}
	}
	return nil
}

const (
	iso8601      = "20060102T150405Z"
	yearMonthDay = "20060102"
)
utcNow returns the current time in UTC and is a variable to allow for reassignment in tests to provide deterministic signed URL values.
var utcNow = func() time.Time {
	return time.Now().UTC()
}
extractHeaderNames takes in a series of key:value headers and returns the header names only.
func ( []string) []string {
	var  []string
	for ,  := range  {
		 := strings.Split(, ":")
		 = append(, [0])
	}
	return 
}
pathEncodeV4 creates an encoded string that matches the v4 signature spec. Following the spec precisely is necessary in order to ensure that the URL and signing string are correctly formed, and Go's url.PathEncode and url.QueryEncode don't generate an exact match without some additional logic.
func ( string) string {
	 := strings.Split(, "/")
	var  []string
	for ,  := range  {
		 = append(, url.QueryEscape())
	}
	 := strings.Join(, "/")
	 = strings.Replace(, "+", "%20", -1)
	return 
}
signedURLV4 creates a signed URL using the sigV4 algorithm.
func (,  string,  *SignedURLOptions,  time.Time) (string, error) {
	 := &bytes.Buffer{}
	fmt.Fprintf(, "%s\n", .Method)

	 := &url.URL{Path: .Style.path(, )}
	.RawPath = pathEncodeV4(.Path)
Note: we have to add a / here because GCS does so auto-magically, despite our encoding not doing so (and we have to exactly match their canonical query).
	fmt.Fprintf(, "/%s\n", .RawPath)

	 := append(extractHeaderNames(.Headers), "host")
	if .ContentType != "" {
		 = append(, "content-type")
	}
	if .MD5 != "" {
		 = append(, "content-md5")
	}
	sort.Strings()
	 := strings.Join(, ";")
	 := .Format(iso8601)
	 := fmt.Sprintf("%s/auto/storage/goog4_request", .Format(yearMonthDay))
	 := url.Values{
		"X-Goog-Algorithm":     {"GOOG4-RSA-SHA256"},
		"X-Goog-Credential":    {fmt.Sprintf("%s/%s", .GoogleAccessID, )},
		"X-Goog-Date":          {},
		"X-Goog-Expires":       {fmt.Sprintf("%d", int(.Expires.Sub().Seconds()))},
		"X-Goog-SignedHeaders": {},
Add user-supplied query parameters to the canonical query string. For V4, it's necessary to include these.
	for ,  := range .QueryParameters {
		[] = append([], ...)
	}

	fmt.Fprintf(, "%s\n", .Encode())
Fill in the hostname based on the desired URL style.
	.Host = .Style.host()
Fill in the URL scheme.
	if .Insecure {
		.Scheme = "http"
	} else {
		.Scheme = "https"
	}

	var  []string
	 = append(, "host:"+.Host)
	 = append(, .Headers...)
	if .ContentType != "" {
		 = append(, "content-type:"+.ContentType)
	}
	if .MD5 != "" {
		 = append(, "content-md5:"+.MD5)
Trim extra whitespace from headers and replace with a single space.
	var  []string
	for ,  := range  {
		 = append(, strings.Join(strings.Fields(), " "))
	}
	 := strings.Join(sortHeadersByKey(), "\n")
	fmt.Fprintf(, "%s\n\n", )
	fmt.Fprintf(, "%s\n", )
If the user provides a value for X-Goog-Content-SHA256, we must use that value in the request string. If not, we use UNSIGNED-PAYLOAD.
	 := false
	for ,  := range  {
		if strings.HasPrefix(strings.ToLower(), "x-goog-content-sha256") && strings.Contains(, ":") {
			 = true
			fmt.Fprintf(, "%s", strings.SplitN(, ":", 2)[1])
			break
		}
	}
	if ! {
		fmt.Fprint(, "UNSIGNED-PAYLOAD")
	}

	 := sha256.Sum256(.Bytes())
	 := hex.EncodeToString([:])
	 := &bytes.Buffer{}
	fmt.Fprint(, "GOOG4-RSA-SHA256\n")
	fmt.Fprintf(, "%s\n", )
	fmt.Fprintf(, "%s\n", )
	fmt.Fprintf(, "%s", )

	 := .SignBytes
	if .PrivateKey != nil {
		,  := parseKey(.PrivateKey)
		if  != nil {
			return "", 
		}
		 = func( []byte) ([]byte, error) {
			 := sha256.Sum256()
			return rsa.SignPKCS1v15(
				rand.Reader,
				,
				crypto.SHA256,
				[:],
			)
		}
	}
	,  := (.Bytes())
	if  != nil {
		return "", 
	}
	 := hex.EncodeToString()
	.Set("X-Goog-Signature", string())
	.RawQuery = .Encode()
	return .String(), nil
}
takes a list of headerKey:headervalue1,headervalue2,etc and sorts by header key.
func ( []string) []string {
	 := map[string]string{}
	var  []string
	for ,  := range  {
		 := strings.Split(, ":")
		 := [0]
		 := [1]
		[] = 
		 = append(, )
	}
	sort.Strings()
	var  []string
	for ,  := range  {
		 := []
		 = append(, fmt.Sprintf("%s:%s", , ))
	}
	return 
}

func (,  string,  *SignedURLOptions) (string, error) {
	 := .SignBytes
	if .PrivateKey != nil {
		,  := parseKey(.PrivateKey)
		if  != nil {
			return "", 
		}
		 = func( []byte) ([]byte, error) {
			 := sha256.Sum256()
			return rsa.SignPKCS1v15(
				rand.Reader,
				,
				crypto.SHA256,
				[:],
			)
		}
	}

	 := &url.URL{
		Path: fmt.Sprintf("/%s/%s", , ),
	}

	 := &bytes.Buffer{}
	fmt.Fprintf(, "%s\n", .Method)
	fmt.Fprintf(, "%s\n", .MD5)
	fmt.Fprintf(, "%s\n", .ContentType)
	fmt.Fprintf(, "%d\n", .Expires.Unix())
	if len(.Headers) > 0 {
		fmt.Fprintf(, "%s\n", strings.Join(.Headers, "\n"))
	}
	fmt.Fprintf(, "%s", .String())

	,  := (.Bytes())
	if  != nil {
		return "", 
	}
	 := base64.StdEncoding.EncodeToString()
	.Scheme = "https"
	.Host = "storage.googleapis.com"
	 := .Query()
	.Set("GoogleAccessId", .GoogleAccessID)
	.Set("Expires", fmt.Sprintf("%d", .Expires.Unix()))
	.Set("Signature", string())
	.RawQuery = .Encode()
	return .String(), nil
}
ObjectHandle provides operations on an object in a Google Cloud Storage bucket. Use BucketHandle.Object to get a handle.
type ObjectHandle struct {
	c              *Client
	bucket         string
	object         string
	acl            ACLHandle
	gen            int64 // a negative value indicates latest
	conds          *Conditions
	encryptionKey  []byte // AES-256 key
	userProject    string // for requester-pays buckets
	readCompressed bool   // Accept-Encoding: gzip
}
ACL provides access to the object's access control list. This controls who can read and write this object. This call does not perform any network operations.
func ( *ObjectHandle) () *ACLHandle {
	return &.acl
}
Generation returns a new ObjectHandle that operates on a specific generation of the object. By default, the handle operates on the latest generation. Not all operations work when given a specific generation; check the API endpoints at https://cloud.google.com/storage/docs/json_api/ for details.
func ( *ObjectHandle) ( int64) *ObjectHandle {
	 := *
	.gen = 
	return &
}
If returns a new ObjectHandle that applies a set of preconditions. Preconditions already set on the ObjectHandle are ignored. Operations on the new handle will return an error if the preconditions are not satisfied. See https://cloud.google.com/storage/docs/generations-preconditions for more details.
func ( *ObjectHandle) ( Conditions) *ObjectHandle {
	 := *
	.conds = &
	return &
}
Key returns a new ObjectHandle that uses the supplied encryption key to encrypt and decrypt the object's contents. Encryption key must be a 32-byte AES-256 key. See https://cloud.google.com/storage/docs/encryption for details.
func ( *ObjectHandle) ( []byte) *ObjectHandle {
	 := *
	.encryptionKey = 
	return &
}
Attrs returns meta information about the object. ErrObjectNotExist will be returned if the object is not found.
func ( *ObjectHandle) ( context.Context) ( *ObjectAttrs,  error) {
	 = trace.StartSpan(, "cloud.google.com/go/storage.Object.Attrs")
	defer func() { trace.EndSpan(, ) }()

	if  := .validate();  != nil {
		return nil, 
	}
	 := .c.raw.Objects.Get(.bucket, .object).Projection("full").Context()
	if  := applyConds("Attrs", .gen, .conds, );  != nil {
		return nil, 
	}
	if .userProject != "" {
		.UserProject(.userProject)
	}
	if  := setEncryptionHeaders(.Header(), .encryptionKey, false);  != nil {
		return nil, 
	}
	var  *raw.Object
	setClientHeader(.Header())
	 = runWithRetry(, func() error { ,  = .Do(); return  })
	if ,  := .(*googleapi.Error);  && .Code == http.StatusNotFound {
		return nil, ErrObjectNotExist
	}
	if  != nil {
		return nil, 
	}
	return newObject(), nil
}
Update updates an object with the provided attributes. All zero-value attributes are ignored. ErrObjectNotExist will be returned if the object is not found.
func ( *ObjectHandle) ( context.Context,  ObjectAttrsToUpdate) ( *ObjectAttrs,  error) {
	 = trace.StartSpan(, "cloud.google.com/go/storage.Object.Update")
	defer func() { trace.EndSpan(, ) }()

	if  := .validate();  != nil {
		return nil, 
	}
Lists of fields to send, and set to null, in the JSON.
	var ,  []string
	if .ContentType != nil {
For ContentType, sending the empty string is a no-op. Instead we send a null.
		if .ContentType == "" {
			 = append(, "ContentType")
		} else {
			 = append(, "ContentType")
		}
	}
	if .ContentLanguage != nil {
For ContentLanguage it's an error to send the empty string. Instead we send a null.
		if .ContentLanguage == "" {
			 = append(, "ContentLanguage")
		} else {
			 = append(, "ContentLanguage")
		}
	}
	if .ContentEncoding != nil {
		.ContentEncoding = optional.ToString(.ContentEncoding)
		 = append(, "ContentEncoding")
	}
	if .ContentDisposition != nil {
		.ContentDisposition = optional.ToString(.ContentDisposition)
		 = append(, "ContentDisposition")
	}
	if .CacheControl != nil {
		.CacheControl = optional.ToString(.CacheControl)
		 = append(, "CacheControl")
	}
	if .EventBasedHold != nil {
		.EventBasedHold = optional.ToBool(.EventBasedHold)
		 = append(, "EventBasedHold")
	}
	if .TemporaryHold != nil {
		.TemporaryHold = optional.ToBool(.TemporaryHold)
		 = append(, "TemporaryHold")
	}
	if .Metadata != nil {
		.Metadata = .Metadata
Sending the empty map is a no-op. We send null instead.
			 = append(, "Metadata")
		} else {
			 = append(, "Metadata")
		}
	}
	if .ACL != nil {
It's an error to attempt to delete the ACL, so we don't append to nullFields here.
		 = append(, "Acl")
	}
	 := .toRawObject(.bucket)
	.ForceSendFields = 
	.NullFields = 
	 := .c.raw.Objects.Patch(.bucket, .object, ).Projection("full").Context()
	if  := applyConds("Update", .gen, .conds, );  != nil {
		return nil, 
	}
	if .userProject != "" {
		.UserProject(.userProject)
	}
	if .PredefinedACL != "" {
		.PredefinedAcl(.PredefinedACL)
	}
	if  := setEncryptionHeaders(.Header(), .encryptionKey, false);  != nil {
		return nil, 
	}
	var  *raw.Object
	setClientHeader(.Header())
	 = runWithRetry(, func() error { ,  = .Do(); return  })
	if ,  := .(*googleapi.Error);  && .Code == http.StatusNotFound {
		return nil, ErrObjectNotExist
	}
	if  != nil {
		return nil, 
	}
	return newObject(), nil
}
BucketName returns the name of the bucket.
func ( *ObjectHandle) () string {
	return .bucket
}
ObjectName returns the name of the object.
func ( *ObjectHandle) () string {
	return .object
}
ObjectAttrsToUpdate is used to update the attributes of an object. Only fields set to non-nil values will be updated. Set a field to its zero value to delete it. For example, to change ContentType and delete ContentEncoding and Metadata, use ObjectAttrsToUpdate{ ContentType: "text/html", ContentEncoding: "", Metadata: map[string]string{}, }
If not empty, applies a predefined set of access controls. ACL must be nil. See https://cloud.google.com/storage/docs/json_api/v1/objects/patch.
Delete deletes the single specified object.
func ( *ObjectHandle) ( context.Context) error {
	if  := .validate();  != nil {
		return 
	}
	 := .c.raw.Objects.Delete(.bucket, .object).Context()
	if  := applyConds("Delete", .gen, .conds, );  != nil {
		return 
	}
	if .userProject != "" {
		.UserProject(.userProject)
Encryption doesn't apply to Delete.
	setClientHeader(.Header())
	 := runWithRetry(, func() error { return .Do() })
	switch e := .(type) {
	case nil:
		return nil
	case *googleapi.Error:
		if .Code == http.StatusNotFound {
			return ErrObjectNotExist
		}
	}
	return 
}
ReadCompressed when true causes the read to happen without decompressing.
func ( *ObjectHandle) ( bool) *ObjectHandle {
	 := *
	.readCompressed = 
	return &
}
NewWriter returns a storage Writer that writes to the GCS object associated with this ObjectHandle. A new object will be created unless an object with this name already exists. Otherwise any previous object with the same name will be replaced. The object will not be available (and any previous object will remain) until Close has been called. Attributes can be set on the object by modifying the returned Writer's ObjectAttrs field before the first call to Write. If no ContentType attribute is specified, the content type will be automatically sniffed using net/http.DetectContentType. It is the caller's responsibility to call Close when writing is done. To stop writing without saving the data, cancel the context.
func ( *ObjectHandle) ( context.Context) *Writer {
	return &Writer{
		ctx:         ,
		o:           ,
		donec:       make(chan struct{}),
		ObjectAttrs: ObjectAttrs{Name: .object},
		ChunkSize:   googleapi.DefaultUploadChunkSize,
	}
}

func ( *ObjectHandle) () error {
	if .bucket == "" {
		return errors.New("storage: bucket name is empty")
	}
	if .object == "" {
		return errors.New("storage: object name is empty")
	}
	if !utf8.ValidString(.object) {
		return fmt.Errorf("storage: object name %q is not valid UTF-8", .object)
	}
	return nil
}
parseKey converts the binary contents of a private key file to an *rsa.PrivateKey. It detects whether the private key is in a PEM container or not. If so, it extracts the private key from PEM container before conversion. It only supports PEM containers with no passphrase.
func ( []byte) (*rsa.PrivateKey, error) {
	if ,  := pem.Decode();  != nil {
		 = .Bytes
	}
	,  := x509.ParsePKCS8PrivateKey()
	if  != nil {
		,  = x509.ParsePKCS1PrivateKey()
		if  != nil {
			return nil, 
		}
	}
	,  := .(*rsa.PrivateKey)
	if ! {
		return nil, errors.New("oauth2: private key is invalid")
	}
	return , nil
}
ObjectAttrs represents the metadata for a Google Cloud Storage (GCS) object.
Bucket is the name of the bucket containing this GCS object. This field is read-only.
Name is the name of the object within the bucket. This field is read-only.
ContentType is the MIME type of the object's content.
ContentLanguage is the content language of the object's content.
CacheControl is the Cache-Control header to be sent in the response headers when serving the object data.
EventBasedHold specifies whether an object is under event-based hold. New objects created in a bucket whose DefaultEventBasedHold is set will default to that value.
TemporaryHold specifies whether an object is under temporary hold. While this flag is set to true, the object is protected against deletion and overwrites.
RetentionExpirationTime is a server-determined value that specifies the earliest time that the object's retention period expires. This is a read-only field.
ACL is the list of access control rules for the object.
If not empty, applies a predefined set of access controls. It should be set only when writing, copying or composing an object. When copying or composing, it acts as the destinationPredefinedAcl parameter. PredefinedACL is always empty for ObjectAttrs returned from the service. See https://cloud.google.com/storage/docs/json_api/v1/objects/insert for valid values.
Owner is the owner of the object. This field is read-only. If non-zero, it is in the form of "user-<userId>".
Size is the length of the object's content. This field is read-only.
ContentEncoding is the encoding of the object's content.
ContentDisposition is the optional Content-Disposition header of the object sent in the response headers.
MD5 is the MD5 hash of the object's content. This field is read-only, except when used from a Writer. If set on a Writer, the uploaded data is rejected if its MD5 hash does not match this field.
	MD5 []byte
CRC32C is the CRC32 checksum of the object's content using the Castagnoli93 polynomial. This field is read-only, except when used from a Writer or Composer. In those cases, if the SendCRC32C field in the Writer or Composer is set to is true, the uploaded data is rejected if its CRC32C hash does not match this field.
MediaLink is an URL to the object's content. This field is read-only.
Metadata represents user-provided metadata, in key/value pairs. It can be nil if no metadata is provided.
Generation is the generation number of the object's content. This field is read-only.
Metageneration is the version of the metadata for this object at this generation. This field is used for preconditions and for detecting changes in metadata. A metageneration number is only meaningful in the context of a particular generation of a particular object. This field is read-only.
StorageClass is the storage class of the object. This defines how objects are stored and determines the SLA and the cost of storage. Typical values are "STANDARD", "NEARLINE", "COLDLINE" and "ARCHIVE". Defaults to "STANDARD". See https://cloud.google.com/storage/docs/storage-classes for all valid values.
Created is the time the object was created. This field is read-only.
Deleted is the time the object was deleted. If not deleted, it is the zero value. This field is read-only.
Updated is the creation or modification time of the object. For buckets with versioning enabled, changing an object's metadata does not change this property. This field is read-only.
CustomerKeySHA256 is the base64-encoded SHA-256 hash of the customer-supplied encryption key for the object. It is empty if there is no customer-supplied encryption key. See // https://cloud.google.com/storage/docs/encryption for more about encryption in Google Cloud Storage.
Cloud KMS key name, in the form projects/P/locations/L/keyRings/R/cryptoKeys/K, used to encrypt this object, if the object is encrypted by such a key. Providing both a KMSKeyName and a customer-supplied encryption key (via ObjectHandle.Key) will result in an error when writing an object.
Prefix is set only for ObjectAttrs which represent synthetic "directory entries" when iterating over buckets using Query.Delimiter. See ObjectIterator.Next. When set, no other fields in ObjectAttrs will be populated.
Etag is the HTTP/1.1 Entity tag for the object. This field is read-only.
convertTime converts a time in RFC3339 format to time.Time. If any error occurs in parsing, the zero-value time.Time is silently returned.
Decode a uint32 encoded in Base64 in big-endian byte order.
func ( string) (uint32, error) {
	,  := base64.StdEncoding.DecodeString()
	if  != nil {
		return 0, 
	}
	if len() != 4 {
		return 0, fmt.Errorf("storage: %q does not encode a 32-bit value", )
	}
	return uint32([0])<<24 + uint32([1])<<16 + uint32([2])<<8 + uint32([3]), nil
}
Encode a uint32 as Base64 in big-endian byte order.
func ( uint32) string {
	 := []byte{byte( >> 24), byte( >> 16), byte( >> 8), byte()}
	return base64.StdEncoding.EncodeToString()
}
Query represents a query to filter objects from a bucket.
Delimiter returns results in a directory-like fashion. Results will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. Optional.
Prefix is the prefix filter to query objects whose names begin with this prefix. Optional.
Versions indicates whether multiple versions of the same object will be included in the results.
fieldSelection is used to select only specific fields to be returned by the query. It's used internally and is populated for the user by calling Query.SetAttrSelection
attrToFieldMap maps the field names of ObjectAttrs to the underlying field names in the API call. Only the ObjectAttrs field names are visible to users because they are already part of the public API of the package.
var attrToFieldMap = map[string]string{
	"Bucket":                  "bucket",
	"Name":                    "name",
	"ContentType":             "contentType",
	"ContentLanguage":         "contentLanguage",
	"CacheControl":            "cacheControl",
	"EventBasedHold":          "eventBasedHold",
	"TemporaryHold":           "temporaryHold",
	"RetentionExpirationTime": "retentionExpirationTime",
	"ACL":                     "acl",
	"Owner":                   "owner",
	"ContentEncoding":         "contentEncoding",
	"ContentDisposition":      "contentDisposition",
	"Size":                    "size",
	"MD5":                     "md5Hash",
	"CRC32C":                  "crc32c",
	"MediaLink":               "mediaLink",
	"Metadata":                "metadata",
	"Generation":              "generation",
	"Metageneration":          "metageneration",
	"StorageClass":            "storageClass",
	"CustomerKeySHA256":       "customerEncryption",
	"KMSKeyName":              "kmsKeyName",
	"Created":                 "timeCreated",
	"Deleted":                 "timeDeleted",
	"Updated":                 "updated",
	"Etag":                    "etag",
}
SetAttrSelection makes the query populate only specific attributes of objects. When iterating over objects, if you only need each object's name and size, pass []string{"Name", "Size"} to this method. Only these fields will be fetched for each object across the network; the other fields of ObjectAttr will remain at their default values. This is a performance optimization; for more information, see https://cloud.google.com/storage/docs/json_api/v1/how-tos/performance
func ( *Query) ( []string) error {
	 := make(map[string]bool)

	for ,  := range  {
		,  := attrToFieldMap[]
		if ! {
			return fmt.Errorf("storage: attr %v is not valid", )
		}
		[] = true
	}

	if len() > 0 {
		var  bytes.Buffer
		.WriteString("items(")
		 := true
		for  := range  {
			if ! {
				.WriteString(",")
			}
			 = false
			.WriteString()
		}
		.WriteString(")")
		.fieldSelection = .String()
	}
	return nil
}
Conditions constrain methods to act on specific generations of objects. The zero value is an empty set of constraints. Not all conditions or combinations of conditions are applicable to all methods. See https://cloud.google.com/storage/docs/generations-preconditions for details on how these operate.
Generation constraints. At most one of the following can be set to a non-zero value.
GenerationMatch specifies that the object must have the given generation for the operation to occur. If GenerationMatch is zero, it has no effect. Use DoesNotExist to specify that the object does not exist in the bucket.
GenerationNotMatch specifies that the object must not have the given generation for the operation to occur. If GenerationNotMatch is zero, it has no effect.
DoesNotExist specifies that the object must not exist in the bucket for the operation to occur. If DoesNotExist is false, it has no effect.
Metadata generation constraints. At most one of the following can be set to a non-zero value.
MetagenerationMatch specifies that the object must have the given metageneration for the operation to occur. If MetagenerationMatch is zero, it has no effect.
MetagenerationNotMatch specifies that the object must not have the given metageneration for the operation to occur. If MetagenerationNotMatch is zero, it has no effect.
	MetagenerationNotMatch int64
}

func ( *Conditions) ( string) error {
	if * == (Conditions{}) {
		return fmt.Errorf("storage: %s: empty conditions", )
	}
	if !.isGenerationValid() {
		return fmt.Errorf("storage: %s: multiple conditions specified for generation", )
	}
	if !.isMetagenerationValid() {
		return fmt.Errorf("storage: %s: multiple conditions specified for metageneration", )
	}
	return nil
}

func ( *Conditions) () bool {
	 := 0
	if .GenerationMatch != 0 {
		++
	}
	if .GenerationNotMatch != 0 {
		++
	}
	if .DoesNotExist {
		++
	}
	return  <= 1
}

func ( *Conditions) () bool {
	return .MetagenerationMatch == 0 || .MetagenerationNotMatch == 0
}
applyConds modifies the provided call using the conditions in conds. call is something that quacks like a *raw.WhateverCall.
func ( string,  int64,  *Conditions,  interface{}) error {
	 := reflect.ValueOf()
	if  >= 0 {
		if !setConditionField(, "Generation", ) {
			return fmt.Errorf("storage: %s: generation not supported", )
		}
	}
	if  == nil {
		return nil
	}
	if  := .validate();  != nil {
		return 
	}
	switch {
	case .GenerationMatch != 0:
		if !setConditionField(, "IfGenerationMatch", .GenerationMatch) {
			return fmt.Errorf("storage: %s: ifGenerationMatch not supported", )
		}
	case .GenerationNotMatch != 0:
		if !setConditionField(, "IfGenerationNotMatch", .GenerationNotMatch) {
			return fmt.Errorf("storage: %s: ifGenerationNotMatch not supported", )
		}
	case .DoesNotExist:
		if !setConditionField(, "IfGenerationMatch", int64(0)) {
			return fmt.Errorf("storage: %s: DoesNotExist not supported", )
		}
	}
	switch {
	case .MetagenerationMatch != 0:
		if !setConditionField(, "IfMetagenerationMatch", .MetagenerationMatch) {
			return fmt.Errorf("storage: %s: ifMetagenerationMatch not supported", )
		}
	case .MetagenerationNotMatch != 0:
		if !setConditionField(, "IfMetagenerationNotMatch", .MetagenerationNotMatch) {
			return fmt.Errorf("storage: %s: ifMetagenerationNotMatch not supported", )
		}
	}
	return nil
}

func ( int64,  *Conditions,  *raw.ObjectsRewriteCall) error {
	if  >= 0 {
		.SourceGeneration()
	}
	if  == nil {
		return nil
	}
	if  := .validate("CopyTo source");  != nil {
		return 
	}
	switch {
	case .GenerationMatch != 0:
		.IfSourceGenerationMatch(.GenerationMatch)
	case .GenerationNotMatch != 0:
		.IfSourceGenerationNotMatch(.GenerationNotMatch)
	case .DoesNotExist:
		.IfSourceGenerationMatch(0)
	}
	switch {
	case .MetagenerationMatch != 0:
		.IfSourceMetagenerationMatch(.MetagenerationMatch)
	case .MetagenerationNotMatch != 0:
		.IfSourceMetagenerationNotMatch(.MetagenerationNotMatch)
	}
	return nil
}
setConditionField sets a field on a *raw.WhateverCall. We can't use anonymous interfaces because the return type is different, since the field setters are builders.
func ( reflect.Value,  string,  interface{}) bool {
	 := .MethodByName()
	if !.IsValid() {
		return false
	}
	.Call([]reflect.Value{reflect.ValueOf()})
	return true
}
conditionsQuery returns the generation and conditions as a URL query string suitable for URL.RawQuery. It assumes that the conditions have been validated.
URL escapes are elided because integer strings are URL-safe.
	var  []byte

	 := func( string,  int64) {
		if len() > 0 {
			 = append(, '&')
		}
		 = append(, ...)
		 = strconv.AppendInt(, , 10)
	}

	if  >= 0 {
		("generation=", )
	}
	if  == nil {
		return string()
	}
	switch {
	case .GenerationMatch != 0:
		("ifGenerationMatch=", .GenerationMatch)
	case .GenerationNotMatch != 0:
		("ifGenerationNotMatch=", .GenerationNotMatch)
	case .DoesNotExist:
		("ifGenerationMatch=", 0)
	}
	switch {
	case .MetagenerationMatch != 0:
		("ifMetagenerationMatch=", .MetagenerationMatch)
	case .MetagenerationNotMatch != 0:
		("ifMetagenerationNotMatch=", .MetagenerationNotMatch)
	}
	return string()
}
composeSourceObj wraps a *raw.ComposeRequestSourceObjects, but adds the methods that modifyCall searches for by name.
It's safe to overwrite ObjectPreconditions, since its only field is IfGenerationMatch.
TODO(jbd): Ask the API team to return a more user-friendly error and avoid doing this check at the client level.
	if len() != 32 {
		return errors.New("storage: not a 32-byte AES-256 key")
	}
	var  string
	if  {
		 = "copy-source-"
	}
	.Set("x-goog-"++"encryption-algorithm", "AES256")
	.Set("x-goog-"++"encryption-key", base64.StdEncoding.EncodeToString())
	 := sha256.Sum256()
	.Set("x-goog-"++"encryption-key-sha256", base64.StdEncoding.EncodeToString([:]))
	return nil
}
ServiceAccount fetches the email address of the given project's Google Cloud Storage service account.
func ( *Client) ( context.Context,  string) (string, error) {
	 := .raw.Projects.ServiceAccount.Get()
	,  := .Context().Do()
	if  != nil {
		return "", 
	}
	return .EmailAddress, nil