| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package s3blob provides a blob implementation that uses S3. Use OpenBucket |
| 16 |
// to construct a *blob.Bucket. |
| 17 |
// |
| 18 |
// # URLs |
| 19 |
// |
| 20 |
// For blob.OpenBucket, s3blob registers for the scheme "s3". |
| 21 |
// The default URL opener will use an AWS session with the default credentials |
| 22 |
// and configuration. |
| 23 |
// |
| 24 |
// To customize the URL opener, or for more details on the URL format, |
| 25 |
// see URLOpener. |
| 26 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 27 |
// |
| 28 |
// # Escaping |
| 29 |
// |
| 30 |
// Go CDK supports all UTF-8 strings; to make this work with services lacking |
| 31 |
// full UTF-8 support, strings must be escaped (during writes) and unescaped |
| 32 |
// (during reads). The following escapes are performed for s3blob: |
| 33 |
// - Blob keys: ASCII characters 0-31 are escaped to "__0x<hex>__". |
| 34 |
// Additionally, the "/" in "../" is escaped in the same way. |
| 35 |
// - Metadata keys: Escaped using URL encoding, then additionally "@:=" are |
| 36 |
// escaped using "__0x<hex>__". These characters were determined by |
| 37 |
// experimentation. |
| 38 |
// - Metadata values: Escaped using URL encoding. |
| 39 |
// |
| 40 |
// # As |
| 41 |
// |
| 42 |
// s3blob exposes the following types for As: |
| 43 |
// - Bucket: *s3.Client |
| 44 |
// - Error: any error type returned by the service, notably smithy.APIError |
| 45 |
// - ListObject: types.Object for objects, types.CommonPrefix for "directories" |
| 46 |
// - ListOptions.BeforeList: *s3.ListObjectsV2Input or *[]func(*s3.Options), or *s3.ListObjectsInput |
| 47 |
// when Options.UseLegacyList == true |
| 48 |
// - Reader: s3.GetObjectOutput |
| 49 |
// - ReaderOptions.BeforeRead: *s3.GetObjectInput or *[]func(*s3.Options) |
| 50 |
// - Attributes: s3.HeadObjectOutput |
| 51 |
// - CopyOptions.BeforeCopy: s3.CopyObjectInput |
| 52 |
// - WriterOptions.BeforeWrite: *s3.PutObjectInput, *s3manager.Uploader |
| 53 |
// - SignedURLOptions.BeforeSign: *s3.GetObjectInput, when Options.Method == http.MethodGet, or |
| 54 |
// *s3.PutObjectInput, when Options.Method == http.MethodPut |
| 55 |
|
| 56 |
package s3blob // import "gocloud.dev/blob/s3blob" |
| 57 |
|
| 58 |
import ( |
| 59 |
"context" |
| 60 |
"encoding/base64" |
| 61 |
"encoding/hex" |
| 62 |
"errors" |
| 63 |
"fmt" |
| 64 |
"io" |
| 65 |
"net/http" |
| 66 |
"net/url" |
| 67 |
"sort" |
| 68 |
"strconv" |
| 69 |
"strings" |
| 70 |
|
| 71 |
"github.com/aws/aws-sdk-go-v2/aws" |
| 72 |
s3manager "github.com/aws/aws-sdk-go-v2/feature/s3/manager" |
| 73 |
"github.com/aws/aws-sdk-go-v2/service/s3" |
| 74 |
"github.com/aws/aws-sdk-go-v2/service/s3/types" |
| 75 |
"github.com/aws/smithy-go" |
| 76 |
"github.com/google/wire" |
| 77 |
gcaws "gocloud.dev/aws" |
| 78 |
"gocloud.dev/blob" |
| 79 |
"gocloud.dev/blob/driver" |
| 80 |
"gocloud.dev/gcerrors" |
| 81 |
"gocloud.dev/internal/escape" |
| 82 |
"gocloud.dev/internal/gcerr" |
| 83 |
) |
| 84 |
|
| 85 |
const defaultPageSize = 1000 |
| 86 |
|
| 87 |
func init() { |
| 88 |
blob.DefaultURLMux().RegisterBucket(Scheme, new(urlSessionOpener)) |
| 89 |
} |
| 90 |
|
| 91 |
// Set holds Wire providers for this package. |
| 92 |
var Set = wire.NewSet( |
| 93 |
Dial, |
| 94 |
) |
| 95 |
|
| 96 |
// Dial gets an AWS S3 service client using the AWS SDK V2. |
| 97 |
func Dial(cfg aws.Config) *s3.Client { |
| 98 |
return s3.NewFromConfig(cfg) |
| 99 |
} |
| 100 |
|
| 101 |
type urlSessionOpener struct{} |
| 102 |
|
| 103 |
func (o *urlSessionOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) { |
| 104 |
opener := &URLOpener{} |
| 105 |
return opener.OpenBucketURL(ctx, u) |
| 106 |
} |
| 107 |
|
| 108 |
// Scheme is the URL scheme s3blob registers its URLOpener under on |
| 109 |
// blob.DefaultMux. |
| 110 |
const Scheme = "s3" |
| 111 |
|
| 112 |
// URLOpener opens S3 URLs like "s3://mybucket". |
| 113 |
// |
| 114 |
// The URL host is used as the bucket name. |
| 115 |
// |
| 116 |
// See https://pkg.go.dev/gocloud.dev/aws#V2ConfigFromURLParams. |
| 117 |
// |
| 118 |
// The following S3-specific query options are also supported: |
| 119 |
// - ssetype: The type of server side encryption used (AES256, aws:kms, aws:kms:dsse) |
| 120 |
// - kmskeyid: The KMS key ID for server side encryption |
| 121 |
// - accelerate: A value of "true" uses the S3 Transfer Accleration endpoints |
| 122 |
// - use_path_style: A value of true sets the UsePathStyle option. |
| 123 |
// - s3ForcePathStyle: Same as use_path_style, for backwards compatibility with V1. |
| 124 |
// - disable_https: A value of true disables HTTPS in the Endpoint options. |
| 125 |
type URLOpener struct { |
| 126 |
// Options specifies the options to pass to OpenBucket. |
| 127 |
Options Options |
| 128 |
} |
| 129 |
|
| 130 |
const ( |
| 131 |
sseTypeParamKey = "ssetype" |
| 132 |
kmsKeyIdParamKey = "kmskeyid" |
| 133 |
accelerateParamKey = "accelerate" |
| 134 |
usePathStyleParamKey = "use_path_style" |
| 135 |
legacyUsePathStyleParamKey = "s3ForcePathStyle" // for backwards compatibility |
| 136 |
disableHTTPSParamKey = "disable_https" |
| 137 |
) |
| 138 |
|
| 139 |
func toServerSideEncryptionType(value string) (types.ServerSideEncryption, error) { |
| 140 |
for _, sseType := range types.ServerSideEncryptionAes256.Values() { |
| 141 |
if strings.EqualFold(string(sseType), value) { |
| 142 |
return sseType, nil |
| 143 |
} |
| 144 |
} |
| 145 |
return "", fmt.Errorf("%q is not a valid value for %q", value, sseTypeParamKey) |
| 146 |
} |
| 147 |
|
| 148 |
// OpenBucketURL opens a blob.Bucket based on u. |
| 149 |
func (o *URLOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) { |
| 150 |
q := u.Query() |
| 151 |
|
| 152 |
if sseTypeParam := q.Get(sseTypeParamKey); sseTypeParam != "" { |
| 153 |
q.Del(sseTypeParamKey) |
| 154 |
|
| 155 |
sseType, err := toServerSideEncryptionType(sseTypeParam) |
| 156 |
if err != nil { |
| 157 |
return nil, err |
| 158 |
} |
| 159 |
|
| 160 |
o.Options.EncryptionType = sseType |
| 161 |
} |
| 162 |
|
| 163 |
if kmsKeyID := q.Get(kmsKeyIdParamKey); kmsKeyID != "" { |
| 164 |
q.Del(kmsKeyIdParamKey) |
| 165 |
o.Options.KMSEncryptionID = kmsKeyID |
| 166 |
} |
| 167 |
|
| 168 |
accelerate := false |
| 169 |
if accelerateParam := q.Get(accelerateParamKey); accelerateParam != "" { |
| 170 |
q.Del(accelerateParamKey) |
| 171 |
var err error |
| 172 |
accelerate, err = strconv.ParseBool(accelerateParam) |
| 173 |
if err != nil { |
| 174 |
return nil, fmt.Errorf("invalid value for %q: %v", accelerateParamKey, err) |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
opts := []func(*s3.Options){ |
| 179 |
func(o *s3.Options) { |
| 180 |
o.UseAccelerate = accelerate |
| 181 |
}, |
| 182 |
} |
| 183 |
if disableHTTPSParam := q.Get(disableHTTPSParamKey); disableHTTPSParam != "" { |
| 184 |
q.Del(disableHTTPSParamKey) |
| 185 |
value, err := strconv.ParseBool(disableHTTPSParam) |
| 186 |
if err != nil { |
| 187 |
return nil, fmt.Errorf("invalid value for %q: %v", disableHTTPSParamKey, err) |
| 188 |
} |
| 189 |
opts = append(opts, func(o *s3.Options) { |
| 190 |
o.EndpointOptions.DisableHTTPS = value |
| 191 |
}) |
| 192 |
} |
| 193 |
for _, key := range []string{usePathStyleParamKey, legacyUsePathStyleParamKey} { |
| 194 |
if usePathStyleParam := q.Get(key); usePathStyleParam != "" { |
| 195 |
q.Del(key) |
| 196 |
value, err := strconv.ParseBool(usePathStyleParam) |
| 197 |
if err != nil { |
| 198 |
return nil, fmt.Errorf("invalid value for %q: %v", key, err) |
| 199 |
} |
| 200 |
opts = append(opts, func(o *s3.Options) { |
| 201 |
o.UsePathStyle = value |
| 202 |
}) |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
cfg, err := gcaws.V2ConfigFromURLParams(ctx, q) |
| 207 |
if err != nil { |
| 208 |
return nil, fmt.Errorf("open bucket %v: %v", u, err) |
| 209 |
} |
| 210 |
client := s3.NewFromConfig(cfg, opts...) |
| 211 |
|
| 212 |
// The S3 upload manager doesn't use the config or options to set the |
| 213 |
// request checksum calculation. We need to set it explicitly: |
| 214 |
// https://github.com/aws/aws-sdk-go-v2/pull/3151 |
| 215 |
o.Options.RequestChecksumCalculation = cfg.RequestChecksumCalculation |
| 216 |
|
| 217 |
return OpenBucket(ctx, client, u.Host, &o.Options) |
| 218 |
} |
| 219 |
|
| 220 |
// Options sets options for constructing a *blob.Bucket backed by S3. |
| 221 |
type Options struct { |
| 222 |
// UseLegacyList forces the use of ListObjects instead of ListObjectsV2. |
| 223 |
// Some S3-compatible services (like CEPH) do not currently support |
| 224 |
// ListObjectsV2. |
| 225 |
UseLegacyList bool |
| 226 |
|
| 227 |
// EncryptionType sets the encryption type headers when making write or |
| 228 |
// copy calls. This is required if the bucket has a restrictive bucket |
| 229 |
// policy that enforces a specific encryption type |
| 230 |
EncryptionType types.ServerSideEncryption |
| 231 |
|
| 232 |
// KMSEncryptionID sets the kms key id header for write or copy calls. |
| 233 |
// This is required when a bucket policy enforces the use of a specific |
| 234 |
// KMS key for uploads |
| 235 |
KMSEncryptionID string |
| 236 |
|
| 237 |
// RequestChecksumCalculation configures the default integrity protection for |
| 238 |
// requests. This may need to be set to when_required to preserve compatibility for |
| 239 |
// third-party S3 providers: https://github.com/aws/aws-sdk-go-v2/discussions/2960. |
| 240 |
RequestChecksumCalculation aws.RequestChecksumCalculation |
| 241 |
} |
| 242 |
|
| 243 |
// openBucket returns an S3 Bucket. |
| 244 |
func openBucket(ctx context.Context, client *s3.Client, bucketName string, opts *Options) (*bucket, error) { |
| 245 |
if bucketName == "" { |
| 246 |
return nil, errors.New("s3blob.OpenBucket: bucketName is required") |
| 247 |
} |
| 248 |
if opts == nil { |
| 249 |
opts = &Options{} |
| 250 |
} |
| 251 |
if client == nil { |
| 252 |
return nil, errors.New("s3blob.OpenBucket: client is required") |
| 253 |
} |
| 254 |
return &bucket{ |
| 255 |
name: bucketName, |
| 256 |
client: client, |
| 257 |
useLegacyList: opts.UseLegacyList, |
| 258 |
kmsKeyId: opts.KMSEncryptionID, |
| 259 |
encryptionType: opts.EncryptionType, |
| 260 |
requestChecksumCalculation: opts.RequestChecksumCalculation, |
| 261 |
}, nil |
| 262 |
} |
| 263 |
|
| 264 |
// OpenBucket returns a *blob.Bucket backed by S3, using AWS SDK v2. |
| 265 |
func OpenBucket(ctx context.Context, client *s3.Client, bucketName string, opts *Options) (*blob.Bucket, error) { |
| 266 |
drv, err := openBucket(ctx, client, bucketName, opts) |
| 267 |
if err != nil { |
| 268 |
return nil, err |
| 269 |
} |
| 270 |
return blob.NewBucket(drv), nil |
| 271 |
} |
| 272 |
|
| 273 |
var OpenBucketV2 = OpenBucket |
| 274 |
|
| 275 |
// reader reads an S3 object. It implements io.ReadCloser. |
| 276 |
type reader struct { |
| 277 |
body io.ReadCloser |
| 278 |
attrs driver.ReaderAttributes |
| 279 |
raw *s3.GetObjectOutput |
| 280 |
} |
| 281 |
|
| 282 |
func (r *reader) Read(p []byte) (int, error) { |
| 283 |
return r.body.Read(p) |
| 284 |
} |
| 285 |
|
| 286 |
// Close closes the reader itself. It must be called when done reading. |
| 287 |
func (r *reader) Close() error { |
| 288 |
return r.body.Close() |
| 289 |
} |
| 290 |
|
| 291 |
func (r *reader) As(i any) bool { |
| 292 |
p, ok := i.(*s3.GetObjectOutput) |
| 293 |
if !ok { |
| 294 |
return false |
| 295 |
} |
| 296 |
*p = *r.raw |
| 297 |
return true |
| 298 |
} |
| 299 |
|
| 300 |
func (r *reader) Attributes() *driver.ReaderAttributes { |
| 301 |
return &r.attrs |
| 302 |
} |
| 303 |
|
| 304 |
// writer writes an S3 object, it implements io.WriteCloser. |
| 305 |
type writer struct { |
| 306 |
// Ends of an io.Pipe, created when the first byte is written. |
| 307 |
pw *io.PipeWriter |
| 308 |
pr *io.PipeReader |
| 309 |
|
| 310 |
// Alternatively, upload is set to true when Upload was |
| 311 |
// used to upload data. |
| 312 |
upload bool |
| 313 |
|
| 314 |
ctx context.Context |
| 315 |
uploader *s3manager.Uploader |
| 316 |
req *s3.PutObjectInput |
| 317 |
|
| 318 |
donec chan struct{} // closed when done writing |
| 319 |
// The following fields will be written before donec closes: |
| 320 |
err error |
| 321 |
} |
| 322 |
|
| 323 |
// Write appends p to w.pw. User must call Close to close the w after done writing. |
| 324 |
func (w *writer) Write(p []byte) (int, error) { |
| 325 |
// Avoid opening the pipe for a zero-length write; |
| 326 |
// the concrete can do these for empty blobs. |
| 327 |
if len(p) == 0 { |
| 328 |
return 0, nil |
| 329 |
} |
| 330 |
if w.pw == nil { |
| 331 |
// We'll write into pw and use pr as an io.Reader for the |
| 332 |
// Upload call to S3. |
| 333 |
w.pr, w.pw = io.Pipe() |
| 334 |
w.open(w.pr, true) |
| 335 |
} |
| 336 |
return w.pw.Write(p) |
| 337 |
} |
| 338 |
|
| 339 |
// Upload reads from r. Per the driver, it is guaranteed to be the only |
| 340 |
// write call for this writer. |
| 341 |
func (w *writer) Upload(r io.Reader) error { |
| 342 |
w.upload = true |
| 343 |
w.open(r, false) |
| 344 |
return nil |
| 345 |
} |
| 346 |
|
| 347 |
// r may be nil if we're Closing and no data was written. |
| 348 |
// If closePipeOnError is true, w.pr will be closed if there's an |
| 349 |
// error uploading to S3. |
| 350 |
func (w *writer) open(r io.Reader, closePipeOnError bool) { |
| 351 |
// This goroutine will keep running until Close, unless there's an error. |
| 352 |
go func() { |
| 353 |
defer close(w.donec) |
| 354 |
|
| 355 |
if r == nil { |
| 356 |
// AWS doesn't like a nil Body. |
| 357 |
r = http.NoBody |
| 358 |
} |
| 359 |
var err error |
| 360 |
w.req.Body = r |
| 361 |
_, err = w.uploader.Upload(w.ctx, w.req) |
| 362 |
if err != nil { |
| 363 |
if closePipeOnError { |
| 364 |
w.pr.CloseWithError(err) |
| 365 |
} |
| 366 |
w.err = err |
| 367 |
} |
| 368 |
}() |
| 369 |
} |
| 370 |
|
| 371 |
// Close completes the writer and closes it. Any error occurring during write |
| 372 |
// will be returned. If a writer is closed before any Write is called, Close |
| 373 |
// will create an empty file at the given key. |
| 374 |
func (w *writer) Close() error { |
| 375 |
if !w.upload { |
| 376 |
if w.pr != nil { |
| 377 |
defer w.pr.Close() |
| 378 |
} |
| 379 |
if w.pw == nil { |
| 380 |
// We never got any bytes written. We'll write an http.NoBody. |
| 381 |
w.open(nil, false) |
| 382 |
} else if err := w.pw.Close(); err != nil { |
| 383 |
return err |
| 384 |
} |
| 385 |
} |
| 386 |
<-w.donec |
| 387 |
return w.err |
| 388 |
} |
| 389 |
|
| 390 |
// bucket represents an S3 bucket and handles read, write and delete operations. |
| 391 |
type bucket struct { |
| 392 |
name string |
| 393 |
client *s3.Client |
| 394 |
useLegacyList bool |
| 395 |
|
| 396 |
encryptionType types.ServerSideEncryption |
| 397 |
kmsKeyId string |
| 398 |
requestChecksumCalculation aws.RequestChecksumCalculation |
| 399 |
} |
| 400 |
|
| 401 |
func (b *bucket) Close() error { |
| 402 |
return nil |
| 403 |
} |
| 404 |
|
| 405 |
func (b *bucket) ErrorCode(err error) gcerrors.ErrorCode { |
| 406 |
var code string |
| 407 |
var ae smithy.APIError |
| 408 |
var oe *smithy.OperationError |
| 409 |
if errors.As(err, &oe) && strings.Contains(oe.Error(), "301") { |
| 410 |
// AWS returns an OperationError with a missing redirect for invalid buckets. |
| 411 |
code = "NoSuchBucket" |
| 412 |
} else if errors.As(err, &ae) { |
| 413 |
code = ae.ErrorCode() |
| 414 |
} else { |
| 415 |
return gcerrors.Unknown |
| 416 |
} |
| 417 |
switch { |
| 418 |
case code == "NoSuchBucket" || code == "NoSuchKey" || code == "NotFound" || code == "ObjectNotInActiveTierError": |
| 419 |
return gcerrors.NotFound |
| 420 |
case code == "PreconditionFailed": |
| 421 |
return gcerrors.FailedPrecondition |
| 422 |
case code == "AccessDenied" || code == "Forbidden": |
| 423 |
return gcerrors.PermissionDenied |
| 424 |
default: |
| 425 |
return gcerrors.Unknown |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
// ListPaged implements driver.ListPaged. |
| 430 |
func (b *bucket) ListPaged(ctx context.Context, opts *driver.ListOptions) (*driver.ListPage, error) { |
| 431 |
pageSize := opts.PageSize |
| 432 |
if pageSize == 0 { |
| 433 |
pageSize = defaultPageSize |
| 434 |
} |
| 435 |
in := &s3.ListObjectsV2Input{ |
| 436 |
Bucket: aws.String(b.name), |
| 437 |
MaxKeys: aws.Int32(int32(pageSize)), |
| 438 |
} |
| 439 |
if len(opts.PageToken) > 0 { |
| 440 |
in.ContinuationToken = aws.String(string(opts.PageToken)) |
| 441 |
} |
| 442 |
if opts.Prefix != "" { |
| 443 |
in.Prefix = aws.String(escapeKey(opts.Prefix)) |
| 444 |
} |
| 445 |
if opts.Delimiter != "" { |
| 446 |
in.Delimiter = aws.String(escapeKey(opts.Delimiter)) |
| 447 |
} |
| 448 |
resp, err := b.listObjects(ctx, in, opts) |
| 449 |
if err != nil { |
| 450 |
return nil, err |
| 451 |
} |
| 452 |
page := driver.ListPage{} |
| 453 |
if resp.NextContinuationToken != nil { |
| 454 |
page.NextPageToken = []byte(*resp.NextContinuationToken) |
| 455 |
} |
| 456 |
if n := len(resp.Contents) + len(resp.CommonPrefixes); n > 0 { |
| 457 |
page.Objects = make([]*driver.ListObject, n) |
| 458 |
for i, obj := range resp.Contents { |
| 459 |
page.Objects[i] = &driver.ListObject{ |
| 460 |
Key: unescapeKey(aws.ToString(obj.Key)), |
| 461 |
ModTime: *obj.LastModified, |
| 462 |
Size: aws.ToInt64(obj.Size), |
| 463 |
MD5: eTagToMD5(obj.ETag), |
| 464 |
AsFunc: func(i any) bool { |
| 465 |
p, ok := i.(*types.Object) |
| 466 |
if !ok { |
| 467 |
return false |
| 468 |
} |
| 469 |
*p = obj |
| 470 |
return true |
| 471 |
}, |
| 472 |
} |
| 473 |
} |
| 474 |
for i, prefix := range resp.CommonPrefixes { |
| 475 |
page.Objects[i+len(resp.Contents)] = &driver.ListObject{ |
| 476 |
Key: unescapeKey(aws.ToString(prefix.Prefix)), |
| 477 |
IsDir: true, |
| 478 |
AsFunc: func(i any) bool { |
| 479 |
p, ok := i.(*types.CommonPrefix) |
| 480 |
if !ok { |
| 481 |
return false |
| 482 |
} |
| 483 |
*p = prefix |
| 484 |
return true |
| 485 |
}, |
| 486 |
} |
| 487 |
} |
| 488 |
if len(resp.Contents) > 0 && len(resp.CommonPrefixes) > 0 { |
| 489 |
// S3 gives us blobs and "directories" in separate lists; sort them. |
| 490 |
sort.Slice(page.Objects, func(i, j int) bool { |
| 491 |
return page.Objects[i].Key < page.Objects[j].Key |
| 492 |
}) |
| 493 |
} |
| 494 |
} |
| 495 |
return &page, nil |
| 496 |
} |
| 497 |
|
| 498 |
func (b *bucket) listObjects(ctx context.Context, in *s3.ListObjectsV2Input, opts *driver.ListOptions) (*s3.ListObjectsV2Output, error) { |
| 499 |
if !b.useLegacyList { |
| 500 |
var varopt []func(*s3.Options) |
| 501 |
if opts.BeforeList != nil { |
| 502 |
asFunc := func(i any) bool { |
| 503 |
if p, ok := i.(**s3.ListObjectsV2Input); ok { |
| 504 |
*p = in |
| 505 |
return true |
| 506 |
} |
| 507 |
if p, ok := i.(**[]func(*s3.Options)); ok { |
| 508 |
*p = &varopt |
| 509 |
return true |
| 510 |
} |
| 511 |
return false |
| 512 |
} |
| 513 |
if err := opts.BeforeList(asFunc); err != nil { |
| 514 |
return nil, err |
| 515 |
} |
| 516 |
} |
| 517 |
return b.client.ListObjectsV2(ctx, in, varopt...) |
| 518 |
} |
| 519 |
|
| 520 |
// Use the legacy ListObjects request. |
| 521 |
legacyIn := &s3.ListObjectsInput{ |
| 522 |
Bucket: in.Bucket, |
| 523 |
Delimiter: in.Delimiter, |
| 524 |
EncodingType: in.EncodingType, |
| 525 |
Marker: in.ContinuationToken, |
| 526 |
MaxKeys: in.MaxKeys, |
| 527 |
Prefix: in.Prefix, |
| 528 |
RequestPayer: in.RequestPayer, |
| 529 |
} |
| 530 |
if opts.BeforeList != nil { |
| 531 |
asFunc := func(i any) bool { |
| 532 |
p, ok := i.(**s3.ListObjectsInput) |
| 533 |
if !ok { |
| 534 |
return false |
| 535 |
} |
| 536 |
*p = legacyIn |
| 537 |
return true |
| 538 |
} |
| 539 |
if err := opts.BeforeList(asFunc); err != nil { |
| 540 |
return nil, err |
| 541 |
} |
| 542 |
} |
| 543 |
legacyResp, err := b.client.ListObjects(ctx, legacyIn) |
| 544 |
if err != nil { |
| 545 |
return nil, err |
| 546 |
} |
| 547 |
|
| 548 |
var nextContinuationToken *string |
| 549 |
if legacyResp.NextMarker != nil { |
| 550 |
nextContinuationToken = legacyResp.NextMarker |
| 551 |
} else if aws.ToBool(legacyResp.IsTruncated) { |
| 552 |
nextContinuationToken = aws.String(aws.ToString(legacyResp.Contents[len(legacyResp.Contents)-1].Key)) |
| 553 |
} |
| 554 |
return &s3.ListObjectsV2Output{ |
| 555 |
CommonPrefixes: legacyResp.CommonPrefixes, |
| 556 |
Contents: legacyResp.Contents, |
| 557 |
NextContinuationToken: nextContinuationToken, |
| 558 |
}, nil |
| 559 |
} |
| 560 |
|
| 561 |
// As implements driver.As. |
| 562 |
func (b *bucket) As(i any) bool { |
| 563 |
p, ok := i.(**s3.Client) |
| 564 |
if !ok { |
| 565 |
return false |
| 566 |
} |
| 567 |
*p = b.client |
| 568 |
return true |
| 569 |
} |
| 570 |
|
| 571 |
// As implements driver.ErrorAs. |
| 572 |
func (b *bucket) ErrorAs(err error, i any) bool { |
| 573 |
return errors.As(err, i) |
| 574 |
} |
| 575 |
|
| 576 |
// Attributes implements driver.Attributes. |
| 577 |
func (b *bucket) Attributes(ctx context.Context, key string) (*driver.Attributes, error) { |
| 578 |
key = escapeKey(key) |
| 579 |
in := &s3.HeadObjectInput{ |
| 580 |
Bucket: aws.String(b.name), |
| 581 |
Key: aws.String(key), |
| 582 |
} |
| 583 |
resp, err := b.client.HeadObject(ctx, in) |
| 584 |
if err != nil { |
| 585 |
return nil, err |
| 586 |
} |
| 587 |
|
| 588 |
md := make(map[string]string, len(resp.Metadata)) |
| 589 |
for k, v := range resp.Metadata { |
| 590 |
// See the package comments for more details on escaping of metadata |
| 591 |
// keys & values. |
| 592 |
md[escape.HexUnescape(escape.URLUnescape(k))] = escape.URLUnescape(v) |
| 593 |
} |
| 594 |
return &driver.Attributes{ |
| 595 |
CacheControl: aws.ToString(resp.CacheControl), |
| 596 |
ContentDisposition: aws.ToString(resp.ContentDisposition), |
| 597 |
ContentEncoding: aws.ToString(resp.ContentEncoding), |
| 598 |
ContentLanguage: aws.ToString(resp.ContentLanguage), |
| 599 |
ContentType: aws.ToString(resp.ContentType), |
| 600 |
Metadata: md, |
| 601 |
// CreateTime not supported; left as the zero time. |
| 602 |
ModTime: aws.ToTime(resp.LastModified), |
| 603 |
Size: aws.ToInt64(resp.ContentLength), |
| 604 |
MD5: eTagToMD5(resp.ETag), |
| 605 |
ETag: aws.ToString(resp.ETag), |
| 606 |
AsFunc: func(i any) bool { |
| 607 |
p, ok := i.(*s3.HeadObjectOutput) |
| 608 |
if !ok { |
| 609 |
return false |
| 610 |
} |
| 611 |
*p = *resp |
| 612 |
return true |
| 613 |
}, |
| 614 |
}, nil |
| 615 |
} |
| 616 |
|
| 617 |
// NewRangeReader implements driver.NewRangeReader. |
| 618 |
func (b *bucket) NewRangeReader(ctx context.Context, key string, offset, length int64, opts *driver.ReaderOptions) (driver.Reader, error) { |
| 619 |
key = escapeKey(key) |
| 620 |
var byteRange *string |
| 621 |
if offset > 0 && length < 0 { |
| 622 |
byteRange = aws.String(fmt.Sprintf("bytes=%d-", offset)) |
| 623 |
} else if length == 0 { |
| 624 |
// AWS doesn't support a zero-length read; we'll read 1 byte and then |
| 625 |
// ignore it in favor of http.NoBody below. |
| 626 |
byteRange = aws.String(fmt.Sprintf("bytes=%d-%d", offset, offset)) |
| 627 |
} else if length >= 0 { |
| 628 |
byteRange = aws.String(fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) |
| 629 |
} |
| 630 |
in := &s3.GetObjectInput{ |
| 631 |
Bucket: aws.String(b.name), |
| 632 |
Key: aws.String(key), |
| 633 |
Range: byteRange, |
| 634 |
} |
| 635 |
var varopt []func(*s3.Options) |
| 636 |
if opts.BeforeRead != nil { |
| 637 |
asFunc := func(i any) bool { |
| 638 |
if p, ok := i.(**s3.GetObjectInput); ok { |
| 639 |
*p = in |
| 640 |
return true |
| 641 |
} |
| 642 |
if p, ok := i.(**[]func(*s3.Options)); ok { |
| 643 |
*p = &varopt |
| 644 |
return true |
| 645 |
} |
| 646 |
return false |
| 647 |
} |
| 648 |
if err := opts.BeforeRead(asFunc); err != nil { |
| 649 |
return nil, err |
| 650 |
} |
| 651 |
} |
| 652 |
resp, err := b.client.GetObject(ctx, in, varopt...) |
| 653 |
if err != nil { |
| 654 |
return nil, err |
| 655 |
} |
| 656 |
body := resp.Body |
| 657 |
if length == 0 { |
| 658 |
body = http.NoBody |
| 659 |
} |
| 660 |
return &reader{ |
| 661 |
body: body, |
| 662 |
attrs: driver.ReaderAttributes{ |
| 663 |
ContentType: aws.ToString(resp.ContentType), |
| 664 |
ModTime: aws.ToTime(resp.LastModified), |
| 665 |
Size: getSize(aws.ToInt64(resp.ContentLength), aws.ToString(resp.ContentRange)), |
| 666 |
}, |
| 667 |
raw: resp, |
| 668 |
}, nil |
| 669 |
} |
| 670 |
|
| 671 |
// etagToMD5 processes an ETag header and returns an MD5 hash if possible. |
| 672 |
// S3's ETag header is sometimes a quoted hexstring of the MD5. Other times, |
| 673 |
// notably when the object was uploaded in multiple parts, it is not. |
| 674 |
// We do the best we can. |
| 675 |
// Some links about ETag: |
| 676 |
// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTCommonResponseHeaders.html |
| 677 |
// https://github.com/aws/aws-sdk-net/issues/815 |
| 678 |
// https://teppen.io/2018/06/23/aws_s3_etags/ |
| 679 |
func eTagToMD5(etag *string) []byte { |
| 680 |
if etag == nil { |
| 681 |
// No header at all. |
| 682 |
return nil |
| 683 |
} |
| 684 |
// Strip the expected leading and trailing quotes. |
| 685 |
quoted := *etag |
| 686 |
if len(quoted) < 2 || quoted[0] != '"' || quoted[len(quoted)-1] != '"' { |
| 687 |
return nil |
| 688 |
} |
| 689 |
unquoted := quoted[1 : len(quoted)-1] |
| 690 |
// Un-hex; we return nil on error. In particular, we'll get an error here |
| 691 |
// for multi-part uploaded blobs, whose ETag will contain a "-" and so will |
| 692 |
// never be a legal hex encoding. |
| 693 |
md5, err := hex.DecodeString(unquoted) |
| 694 |
if err != nil { |
| 695 |
return nil |
| 696 |
} |
| 697 |
return md5 |
| 698 |
} |
| 699 |
|
| 700 |
func getSize(contentLength int64, contentRange string) int64 { |
| 701 |
// Default size to ContentLength, but that's incorrect for partial-length reads, |
| 702 |
// where ContentLength refers to the size of the returned Body, not the entire |
| 703 |
// size of the blob. ContentRange has the full size. |
| 704 |
size := contentLength |
| 705 |
if contentRange != "" { |
| 706 |
// Sample: bytes 10-14/27 (where 27 is the full size). |
| 707 |
parts := strings.Split(contentRange, "/") |
| 708 |
if len(parts) == 2 { |
| 709 |
if i, err := strconv.ParseInt(parts[1], 10, 64); err == nil { |
| 710 |
size = i |
| 711 |
} |
| 712 |
} |
| 713 |
} |
| 714 |
return size |
| 715 |
} |
| 716 |
|
| 717 |
// escapeKey does all required escaping for UTF-8 strings to work with S3. |
| 718 |
func escapeKey(key string) string { |
| 719 |
return escape.HexEscape(key, func(r []rune, i int) bool { |
| 720 |
c := r[i] |
| 721 |
switch { |
| 722 |
// S3 doesn't handle these characters (determined via experimentation). |
| 723 |
case c < 32: |
| 724 |
return true |
| 725 |
// For "../", escape the trailing slash. |
| 726 |
case i > 1 && c == '/' && r[i-1] == '.' && r[i-2] == '.': |
| 727 |
return true |
| 728 |
} |
| 729 |
return false |
| 730 |
}) |
| 731 |
} |
| 732 |
|
| 733 |
// unescapeKey reverses escapeKey. |
| 734 |
func unescapeKey(key string) string { |
| 735 |
return escape.HexUnescape(key) |
| 736 |
} |
| 737 |
|
| 738 |
// NewTypedWriter implements driver.NewTypedWriter. |
| 739 |
func (b *bucket) NewTypedWriter(ctx context.Context, key, contentType string, opts *driver.WriterOptions) (driver.Writer, error) { |
| 740 |
key = escapeKey(key) |
| 741 |
uploader := s3manager.NewUploader(b.client, func(u *s3manager.Uploader) { |
| 742 |
if opts.BufferSize != 0 { |
| 743 |
u.PartSize = int64(opts.BufferSize) |
| 744 |
} |
| 745 |
if opts.MaxConcurrency != 0 { |
| 746 |
u.Concurrency = opts.MaxConcurrency |
| 747 |
} |
| 748 |
|
| 749 |
u.RequestChecksumCalculation = b.requestChecksumCalculation |
| 750 |
}) |
| 751 |
md := make(map[string]string, len(opts.Metadata)) |
| 752 |
for k, v := range opts.Metadata { |
| 753 |
// See the package comments for more details on escaping of metadata |
| 754 |
// keys & values. |
| 755 |
k = escape.HexEscape(url.PathEscape(k), func(runes []rune, i int) bool { |
| 756 |
c := runes[i] |
| 757 |
return c == '@' || c == ':' || c == '=' |
| 758 |
}) |
| 759 |
md[k] = url.PathEscape(v) |
| 760 |
} |
| 761 |
req := &s3.PutObjectInput{ |
| 762 |
Bucket: aws.String(b.name), |
| 763 |
ContentType: aws.String(contentType), |
| 764 |
Key: aws.String(key), |
| 765 |
Metadata: md, |
| 766 |
} |
| 767 |
|
| 768 |
if opts.IfNotExist { |
| 769 |
// See https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html |
| 770 |
req.IfNoneMatch = aws.String("*") |
| 771 |
} |
| 772 |
if opts.CacheControl != "" { |
| 773 |
req.CacheControl = aws.String(opts.CacheControl) |
| 774 |
} |
| 775 |
if opts.ContentDisposition != "" { |
| 776 |
req.ContentDisposition = aws.String(opts.ContentDisposition) |
| 777 |
} |
| 778 |
if opts.ContentEncoding != "" { |
| 779 |
req.ContentEncoding = aws.String(opts.ContentEncoding) |
| 780 |
} |
| 781 |
if opts.ContentLanguage != "" { |
| 782 |
req.ContentLanguage = aws.String(opts.ContentLanguage) |
| 783 |
} |
| 784 |
if len(opts.ContentMD5) > 0 { |
| 785 |
req.ContentMD5 = aws.String(base64.StdEncoding.EncodeToString(opts.ContentMD5)) |
| 786 |
} |
| 787 |
if b.encryptionType != "" { |
| 788 |
req.ServerSideEncryption = b.encryptionType |
| 789 |
} |
| 790 |
if b.kmsKeyId != "" { |
| 791 |
req.SSEKMSKeyId = aws.String(b.kmsKeyId) |
| 792 |
} |
| 793 |
if opts.BeforeWrite != nil { |
| 794 |
asFunc := func(i any) bool { |
| 795 |
// Note that since the Go CDK Blob |
| 796 |
// abstraction does not expose AWS's |
| 797 |
// Uploader concept, there does not |
| 798 |
// appear to be any utility in |
| 799 |
// exposing the options list to the v2 |
| 800 |
// Uploader's Upload() method. |
| 801 |
// Instead, applications can |
| 802 |
// manipulate the exposed *Uploader |
| 803 |
// directly, including by setting |
| 804 |
// ClientOptions if needed. |
| 805 |
if p, ok := i.(**s3manager.Uploader); ok { |
| 806 |
*p = uploader |
| 807 |
return true |
| 808 |
} |
| 809 |
if p, ok := i.(**s3.PutObjectInput); ok { |
| 810 |
*p = req |
| 811 |
return true |
| 812 |
} |
| 813 |
return false |
| 814 |
} |
| 815 |
if err := opts.BeforeWrite(asFunc); err != nil { |
| 816 |
return nil, err |
| 817 |
} |
| 818 |
} |
| 819 |
return &writer{ |
| 820 |
ctx: ctx, |
| 821 |
uploader: uploader, |
| 822 |
req: req, |
| 823 |
donec: make(chan struct{}), |
| 824 |
}, nil |
| 825 |
} |
| 826 |
|
| 827 |
// Copy implements driver.Copy. |
| 828 |
func (b *bucket) Copy(ctx context.Context, dstKey, srcKey string, opts *driver.CopyOptions) error { |
| 829 |
dstKey = escapeKey(dstKey) |
| 830 |
srcKey = escapeKey(srcKey) |
| 831 |
srcKeyWithBucketEscaped := url.QueryEscape(b.name + "/" + srcKey) |
| 832 |
input := &s3.CopyObjectInput{ |
| 833 |
Bucket: aws.String(b.name), |
| 834 |
CopySource: aws.String(srcKeyWithBucketEscaped), |
| 835 |
Key: aws.String(dstKey), |
| 836 |
} |
| 837 |
if b.encryptionType != "" { |
| 838 |
input.ServerSideEncryption = b.encryptionType |
| 839 |
} |
| 840 |
if b.kmsKeyId != "" { |
| 841 |
input.SSEKMSKeyId = aws.String(b.kmsKeyId) |
| 842 |
} |
| 843 |
if opts.BeforeCopy != nil { |
| 844 |
asFunc := func(i any) bool { |
| 845 |
switch v := i.(type) { |
| 846 |
case **s3.CopyObjectInput: |
| 847 |
*v = input |
| 848 |
return true |
| 849 |
} |
| 850 |
return false |
| 851 |
} |
| 852 |
if err := opts.BeforeCopy(asFunc); err != nil { |
| 853 |
return err |
| 854 |
} |
| 855 |
} |
| 856 |
_, err := b.client.CopyObject(ctx, input) |
| 857 |
return err |
| 858 |
} |
| 859 |
|
| 860 |
// Delete implements driver.Delete. |
| 861 |
func (b *bucket) Delete(ctx context.Context, key string) error { |
| 862 |
if _, err := b.Attributes(ctx, key); err != nil { |
| 863 |
return err |
| 864 |
} |
| 865 |
key = escapeKey(key) |
| 866 |
input := &s3.DeleteObjectInput{ |
| 867 |
Bucket: aws.String(b.name), |
| 868 |
Key: aws.String(key), |
| 869 |
} |
| 870 |
_, err := b.client.DeleteObject(ctx, input) |
| 871 |
return err |
| 872 |
} |
| 873 |
|
| 874 |
func (b *bucket) SignedURL(ctx context.Context, key string, opts *driver.SignedURLOptions) (string, error) { |
| 875 |
key = escapeKey(key) |
| 876 |
switch opts.Method { |
| 877 |
case http.MethodGet: |
| 878 |
in := &s3.GetObjectInput{ |
| 879 |
Bucket: aws.String(b.name), |
| 880 |
Key: aws.String(key), |
| 881 |
} |
| 882 |
if opts.BeforeSign != nil { |
| 883 |
asFunc := func(i any) bool { |
| 884 |
v, ok := i.(**s3.GetObjectInput) |
| 885 |
if ok { |
| 886 |
*v = in |
| 887 |
} |
| 888 |
return ok |
| 889 |
} |
| 890 |
if err := opts.BeforeSign(asFunc); err != nil { |
| 891 |
return "", err |
| 892 |
} |
| 893 |
} |
| 894 |
p, err := s3.NewPresignClient(b.client, s3.WithPresignExpires(opts.Expiry)).PresignGetObject(ctx, in) |
| 895 |
if err != nil { |
| 896 |
return "", err |
| 897 |
} |
| 898 |
return p.URL, nil |
| 899 |
case http.MethodPut: |
| 900 |
in := &s3.PutObjectInput{ |
| 901 |
Bucket: aws.String(b.name), |
| 902 |
Key: aws.String(key), |
| 903 |
} |
| 904 |
if opts.EnforceAbsentContentType || opts.ContentType != "" { |
| 905 |
// https://github.com/aws/aws-sdk-go-v2/issues/1475 |
| 906 |
return "", gcerr.New(gcerr.Unimplemented, nil, 1, "s3blob: AWS SDK v2 does not supported enforcing ContentType in SignedURLs for PUT") |
| 907 |
} |
| 908 |
if opts.BeforeSign != nil { |
| 909 |
asFunc := func(i any) bool { |
| 910 |
v, ok := i.(**s3.PutObjectInput) |
| 911 |
if ok { |
| 912 |
*v = in |
| 913 |
} |
| 914 |
return ok |
| 915 |
} |
| 916 |
if err := opts.BeforeSign(asFunc); err != nil { |
| 917 |
return "", err |
| 918 |
} |
| 919 |
} |
| 920 |
p, err := s3.NewPresignClient(b.client, s3.WithPresignExpires(opts.Expiry)).PresignPutObject(ctx, in) |
| 921 |
if err != nil { |
| 922 |
return "", err |
| 923 |
} |
| 924 |
return p.URL, nil |
| 925 |
case http.MethodDelete: |
| 926 |
// https://github.com/aws/aws-sdk-java-v2/issues/2520 |
| 927 |
return "", gcerr.New(gcerr.Unimplemented, nil, 1, "s3blob: AWS SDK v2 does not support SignedURL for DELETE") |
| 928 |
default: |
| 929 |
return "", fmt.Errorf("unsupported Method %q", opts.Method) |
| 930 |
} |
| 931 |
} |