/
s3-client.go
531 lines (456 loc) · 14.8 KB
/
s3-client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package s3client
import (
"context"
"strings"
"time"
"emperror.dev/errors"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/aws/aws-sdk-go/service/s3/s3manager/s3manageriface"
"github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/config"
"github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/metrics"
"github.com/oxyno-zeta/s3-proxy/pkg/s3-proxy/tracing"
)
type s3client struct {
svcClient s3iface.S3API
s3managerUploader s3manageriface.UploaderAPI
target *config.TargetConfig
metricsCtx metrics.Client
}
// ListObjectsOperation List objects operation.
const ListObjectsOperation = "list-objects"
// GetObjectOperation Get object operation.
const GetObjectOperation = "get-object"
// HeadObjectOperation Head object operation.
const HeadObjectOperation = "head-object"
// PutObjectOperation Put object operation.
const PutObjectOperation = "put-object"
// DeleteObjectOperation Delete object operation.
const DeleteObjectOperation = "delete-object"
const s3MaxKeys int64 = 1000
func (s3cl *s3client) buildGetObjectInputFromInput(input *GetInput) *s3.GetObjectInput {
s3Input := &s3.GetObjectInput{
Bucket: aws.String(s3cl.target.Bucket.Name),
Key: aws.String(input.Key),
IfModifiedSince: input.IfModifiedSince,
IfUnmodifiedSince: input.IfUnmodifiedSince,
}
// Add Range if not empty
if input.Range != "" {
s3Input.Range = aws.String(input.Range)
}
// Add If Match if not empty
if input.IfMatch != "" {
s3Input.IfMatch = aws.String(input.IfMatch)
}
// Add If None Match if not empty
if input.IfNoneMatch != "" {
s3Input.IfNoneMatch = aws.String(input.IfNoneMatch)
}
return s3Input
}
func (s3cl *s3client) GetObjectSignedURL(_ context.Context, input *GetInput, expiration time.Duration) (string, error) {
// Build input
s3Input := s3cl.buildGetObjectInputFromInput(input)
// Build object request
req, _ := s3cl.svcClient.GetObjectRequest(s3Input)
// Build url
urlStr, err := req.Presign(expiration)
// Check error
if err != nil {
// Try to cast error into an AWS Error if possible
//nolint: errorlint // Cast
aerr, ok := err.(awserr.Error)
if ok {
// Check if it is a not found case
if aerr.Code() == s3.ErrCodeNoSuchKey {
return "", ErrNotFound
} else if aerr.Code() == "PreconditionFailed" {
return "", ErrPreconditionFailed
}
}
return "", errors.WithStack(err)
}
return urlStr, nil
}
// ListFilesAndDirectories List files and directories.
func (s3cl *s3client) ListFilesAndDirectories(ctx context.Context, key string) ([]*ListElementOutput, *ResultInfo, error) {
// List files on path
folders := make([]*ListElementOutput, 0)
files := make([]*ListElementOutput, 0)
// Prepare next token structure
var nextToken *string
// Temporary max elements for limits
tmpMaxElements := s3cl.target.Bucket.S3ListMaxKeys
// Loop control
loopControl := true
// Initialize max keys
maxKeys := s3MaxKeys
// Check size of max keys
if s3cl.target.Bucket.S3ListMaxKeys < maxKeys {
maxKeys = s3cl.target.Bucket.S3ListMaxKeys
}
// Get trace
parentTrace := tracing.GetTraceFromContext(ctx)
// Init & get request headers
var requestHeaders map[string]string
if s3cl.target.Bucket.RequestConfig != nil {
requestHeaders = s3cl.target.Bucket.RequestConfig.ListHeaders
}
// Loop
for loopControl {
// Create child trace
childTrace := parentTrace.GetChildTrace("s3-bucket.list-objects-request")
childTrace.SetTag("s3-bucket.bucket-name", s3cl.target.Bucket.Name)
childTrace.SetTag("s3-bucket.bucket-region", s3cl.target.Bucket.Region)
childTrace.SetTag("s3-bucket.bucket-prefix", s3cl.target.Bucket.Prefix)
childTrace.SetTag("s3-bucket.bucket-s3-endpoint", s3cl.target.Bucket.S3Endpoint)
childTrace.SetTag("s3-proxy.target-name", s3cl.target.Name)
// Request S3
err := s3cl.svcClient.ListObjectsV2PagesWithContext(
ctx,
&s3.ListObjectsV2Input{
Bucket: aws.String(s3cl.target.Bucket.Name),
Prefix: aws.String(key),
Delimiter: aws.String("/"),
MaxKeys: aws.Int64(maxKeys),
ContinuationToken: nextToken,
},
func(page *s3.ListObjectsV2Output, lastPage bool) bool {
// Store next token
nextToken = page.NextContinuationToken
// Check if keycount exists
if page.KeyCount != nil {
// Remove current keys to tmp max elements
tmpMaxElements -= *page.KeyCount
// Update max keys if needed
if tmpMaxElements < maxKeys {
maxKeys = tmpMaxElements
}
}
// Manage loop control
loopControl = nextToken != nil && tmpMaxElements > 0
// Manage folders
for _, item := range page.CommonPrefixes {
name := strings.TrimPrefix(*item.Prefix, key)
folders = append(folders, &ListElementOutput{
Type: FolderType,
Key: *item.Prefix,
Name: name,
})
}
// Manage files
for _, item := range page.Contents {
name := strings.TrimPrefix(*item.Key, key)
if name != "" {
files = append(files, &ListElementOutput{
Type: FileType,
ETag: *item.ETag,
Name: name,
LastModified: *item.LastModified,
Size: *item.Size,
Key: *item.Key,
})
}
}
return lastPage
},
addHeadersToRequest(requestHeaders),
)
// Metrics
s3cl.metricsCtx.IncS3Operations(s3cl.target.Name, s3cl.target.Bucket.Name, ListObjectsOperation)
// End trace
childTrace.Finish()
// Check if errors exists
if err != nil {
return nil, nil, errors.WithStack(err)
}
}
// Concat folders and files
//nolint:gocritic // Ignoring this: appendAssign: append result not assigned to the same slice
all := append(folders, files...)
// Create info
info := &ResultInfo{
Bucket: s3cl.target.Bucket.Name,
Region: s3cl.target.Bucket.Region,
S3Endpoint: s3cl.target.Bucket.S3Endpoint,
Key: key,
}
return all, info, nil
}
// GetObject Get object from S3 bucket.
func (s3cl *s3client) GetObject(ctx context.Context, input *GetInput) (*GetOutput, *ResultInfo, error) {
// Get trace
parentTrace := tracing.GetTraceFromContext(ctx)
// Create child trace
childTrace := parentTrace.GetChildTrace("s3-bucket.get-object-request")
childTrace.SetTag("s3-bucket.bucket-name", s3cl.target.Bucket.Name)
childTrace.SetTag("s3-bucket.bucket-region", s3cl.target.Bucket.Region)
childTrace.SetTag("s3-bucket.bucket-prefix", s3cl.target.Bucket.Prefix)
childTrace.SetTag("s3-bucket.bucket-s3-endpoint", s3cl.target.Bucket.S3Endpoint)
childTrace.SetTag("s3-proxy.target-name", s3cl.target.Name)
defer childTrace.Finish()
// Build input
s3Input := s3cl.buildGetObjectInputFromInput(input)
// Init & get request headers
var requestHeaders map[string]string
if s3cl.target.Bucket.RequestConfig != nil {
requestHeaders = s3cl.target.Bucket.RequestConfig.GetHeaders
}
obj, err := s3cl.svcClient.GetObjectWithContext(
ctx,
s3Input,
addHeadersToRequest(requestHeaders),
)
// Metrics
s3cl.metricsCtx.IncS3Operations(s3cl.target.Name, s3cl.target.Bucket.Name, GetObjectOperation)
// Check if error exists
if err != nil {
// Try to cast error into an AWS Error if possible
//nolint: errorlint // Cast
aerr, ok := err.(awserr.Error)
if ok {
// Check if it is a not found case
//nolint: gocritic // Because don't want to write a switch for the moment
if aerr.Code() == s3.ErrCodeNoSuchKey {
return nil, nil, ErrNotFound
} else if aerr.Code() == "NotModified" {
return nil, nil, ErrNotModified
} else if aerr.Code() == "PreconditionFailed" {
return nil, nil, ErrPreconditionFailed
}
}
return nil, nil, errors.WithStack(err)
}
// Build output
output := &GetOutput{
Body: obj.Body,
}
// Metadata transformation
if obj.Metadata != nil {
output.Metadata = aws.StringValueMap(obj.Metadata)
}
if obj.CacheControl != nil {
output.CacheControl = *obj.CacheControl
}
if obj.Expires != nil {
output.Expires = *obj.Expires
}
if obj.ContentDisposition != nil {
output.ContentDisposition = *obj.ContentDisposition
}
if obj.ContentEncoding != nil {
output.ContentEncoding = *obj.ContentEncoding
}
if obj.ContentLanguage != nil {
output.ContentLanguage = *obj.ContentLanguage
}
if obj.ContentLength != nil {
output.ContentLength = *obj.ContentLength
}
if obj.ContentRange != nil {
output.ContentRange = *obj.ContentRange
}
if obj.ContentType != nil {
output.ContentType = *obj.ContentType
}
if obj.ETag != nil {
output.ETag = *obj.ETag
}
if obj.LastModified != nil {
output.LastModified = *obj.LastModified
}
// Create info
info := &ResultInfo{
Bucket: s3cl.target.Bucket.Name,
S3Endpoint: s3cl.target.Bucket.S3Endpoint,
Region: s3cl.target.Bucket.Region,
Key: input.Key,
}
return output, info, nil
}
func (s3cl *s3client) PutObject(ctx context.Context, input *PutInput) (*ResultInfo, error) {
// Get trace
parentTrace := tracing.GetTraceFromContext(ctx)
// Create child trace
childTrace := parentTrace.GetChildTrace("s3-bucket.put-object-request")
childTrace.SetTag("s3-bucket.bucket-name", s3cl.target.Bucket.Name)
childTrace.SetTag("s3-bucket.bucket-region", s3cl.target.Bucket.Region)
childTrace.SetTag("s3-bucket.bucket-prefix", s3cl.target.Bucket.Prefix)
childTrace.SetTag("s3-bucket.bucket-s3-endpoint", s3cl.target.Bucket.S3Endpoint)
childTrace.SetTag("s3-proxy.target-name", s3cl.target.Name)
defer childTrace.Finish()
inp := &s3manager.UploadInput{
Body: input.Body,
Bucket: aws.String(s3cl.target.Bucket.Name),
Key: aws.String(input.Key),
Expires: input.Expires,
}
// Manage ACL
if s3cl.target.Actions != nil &&
s3cl.target.Actions.PUT != nil &&
s3cl.target.Actions.PUT.Config != nil &&
s3cl.target.Actions.PUT.Config.CannedACL != nil &&
*s3cl.target.Actions.PUT.Config.CannedACL != "" {
// Inject ACL
inp.ACL = s3cl.target.Actions.PUT.Config.CannedACL
}
// Manage cache control case
if input.CacheControl != "" {
inp.CacheControl = aws.String(input.CacheControl)
}
// Manage content disposition case
if input.ContentDisposition != "" {
inp.ContentDisposition = aws.String(input.ContentDisposition)
}
// Manage content encoding case
if input.ContentEncoding != "" {
inp.ContentEncoding = aws.String(input.ContentEncoding)
}
// Manage content language case
if input.ContentLanguage != "" {
inp.ContentLanguage = aws.String(input.ContentLanguage)
}
// Manage content type case
if input.ContentType != "" {
inp.ContentType = aws.String(input.ContentType)
}
// Manage metadata case
if input.Metadata != nil {
inp.Metadata = aws.StringMap(input.Metadata)
}
// Manage storage class
if input.StorageClass != "" {
inp.StorageClass = aws.String(input.StorageClass)
}
// Init & get request headers
var requestHeaders map[string]string
if s3cl.target.Bucket.RequestConfig != nil {
requestHeaders = s3cl.target.Bucket.RequestConfig.PutHeaders
}
// Upload to S3 bucket
_, err := s3cl.s3managerUploader.UploadWithContext(ctx, inp, func(u *s3manager.Uploader) {
// Check if it exists
if u.RequestOptions == nil {
u.RequestOptions = make([]request.Option, 0)
}
// Save new option
u.RequestOptions = append(u.RequestOptions, addHeadersToRequest(requestHeaders))
})
// Check error
if err != nil {
return nil, errors.WithStack(err)
}
// Metrics
s3cl.metricsCtx.IncS3Operations(s3cl.target.Name, s3cl.target.Bucket.Name, PutObjectOperation)
// Create info
info := &ResultInfo{
Bucket: s3cl.target.Bucket.Name,
S3Endpoint: s3cl.target.Bucket.S3Endpoint,
Region: s3cl.target.Bucket.Region,
Key: input.Key,
}
// Return
return info, nil
}
func (s3cl *s3client) HeadObject(ctx context.Context, key string) (*HeadOutput, error) {
// Get trace
parentTrace := tracing.GetTraceFromContext(ctx)
// Create child trace
childTrace := parentTrace.GetChildTrace("s3-bucket.head-object-request")
childTrace.SetTag("s3-bucket.bucket-name", s3cl.target.Bucket.Name)
childTrace.SetTag("s3-bucket.bucket-region", s3cl.target.Bucket.Region)
childTrace.SetTag("s3-bucket.bucket-prefix", s3cl.target.Bucket.Prefix)
childTrace.SetTag("s3-bucket.bucket-s3-endpoint", s3cl.target.Bucket.S3Endpoint)
childTrace.SetTag("s3-proxy.target-name", s3cl.target.Name)
defer childTrace.Finish()
// Init & get request headers
var requestHeaders map[string]string
if s3cl.target.Bucket.RequestConfig != nil {
requestHeaders = s3cl.target.Bucket.RequestConfig.GetHeaders
}
// Head object in bucket
_, err := s3cl.svcClient.HeadObjectWithContext(
ctx,
&s3.HeadObjectInput{
Bucket: aws.String(s3cl.target.Bucket.Name),
Key: aws.String(key),
},
addHeadersToRequest(requestHeaders),
)
// Metrics
s3cl.metricsCtx.IncS3Operations(s3cl.target.Name, s3cl.target.Bucket.Name, HeadObjectOperation)
// Test error
if err != nil {
// Try to cast error into an AWS Error if possible
//nolint: errorlint // Cast
aerr, ok := err.(awserr.Error)
if ok {
// Issue not fixed: https://github.com/aws/aws-sdk-go/issues/1208
if aerr.Code() == "NotFound" {
return nil, ErrNotFound
}
}
return nil, errors.WithStack(err)
}
// Generate output
output := &HeadOutput{
Type: FileType,
Key: key,
}
// Return output
return output, nil
}
func (s3cl *s3client) DeleteObject(ctx context.Context, key string) (*ResultInfo, error) {
// Get trace
parentTrace := tracing.GetTraceFromContext(ctx)
// Create child trace
childTrace := parentTrace.GetChildTrace("s3-bucket.delete-object-request")
childTrace.SetTag("s3-bucket.bucket-name", s3cl.target.Bucket.Name)
childTrace.SetTag("s3-bucket.bucket-region", s3cl.target.Bucket.Region)
childTrace.SetTag("s3-bucket.bucket-prefix", s3cl.target.Bucket.Prefix)
childTrace.SetTag("s3-bucket.bucket-s3-endpoint", s3cl.target.Bucket.S3Endpoint)
childTrace.SetTag("s3-proxy.target-name", s3cl.target.Name)
defer childTrace.Finish()
// Init & get request headers
var requestHeaders map[string]string
if s3cl.target.Bucket.RequestConfig != nil {
requestHeaders = s3cl.target.Bucket.RequestConfig.DeleteHeaders
}
// Delete object
_, err := s3cl.svcClient.DeleteObjectWithContext(
ctx,
&s3.DeleteObjectInput{
Bucket: aws.String(s3cl.target.Bucket.Name),
Key: aws.String(key),
},
addHeadersToRequest(requestHeaders),
)
// Check error
if err != nil {
return nil, errors.WithStack(err)
}
// Metrics
s3cl.metricsCtx.IncS3Operations(s3cl.target.Name, s3cl.target.Bucket.Name, DeleteObjectOperation)
// Create info
info := &ResultInfo{
Bucket: s3cl.target.Bucket.Name,
S3Endpoint: s3cl.target.Bucket.S3Endpoint,
Region: s3cl.target.Bucket.Region,
Key: key,
}
// Return
return info, nil
}
func addHeadersToRequest(headers map[string]string) func(r *request.Request) {
return func(r *request.Request) {
// Loop over them
for k, v := range headers {
r.HTTPRequest.Header.Set(k, v)
}
}
}