/
s3.go
363 lines (314 loc) · 9.84 KB
/
s3.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
// Copyright 2021 Nitric Pty Ltd.
//
// 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 (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go"
"go.opentelemetry.io/contrib/instrumentation/github.com/aws/aws-sdk-go-v2/otelaws"
"google.golang.org/grpc/codes"
"github.com/nitrictech/nitric/cloud/aws/ifaces/s3iface"
"github.com/nitrictech/nitric/cloud/aws/runtime/env"
"github.com/nitrictech/nitric/cloud/aws/runtime/resource"
grpc_errors "github.com/nitrictech/nitric/core/pkg/grpc/errors"
storagepb "github.com/nitrictech/nitric/core/pkg/proto/storage/v1"
)
const (
// ErrCodeNoSuchTagSet - AWS API neglects to include a constant for this error code.
ErrCodeNoSuchTagSet = "NoSuchTagSet"
ErrCodeAccessDenied = "AccessDenied"
)
// S3StorageService - an AWS S3 implementation of the Nitric Storage Service
type S3StorageService struct {
s3Client s3iface.S3API
preSignClient s3iface.PreSignAPI
provider resource.AwsResourceProvider
selector BucketSelector
}
var _ storagepb.StorageServer = (*S3StorageService)(nil)
type BucketSelector = func(nitricName string) (*string, error)
func (s *S3StorageService) getS3BucketName(ctx context.Context, bucket string) (*string, error) {
if s.selector != nil {
return s.selector(bucket)
}
buckets, err := s.provider.GetResources(ctx, resource.AwsResource_Bucket)
if err != nil {
return nil, fmt.Errorf("error getting bucket list: %w", err)
}
if s3Bucket, ok := buckets[bucket]; ok {
bucketName := strings.Split(s3Bucket.ARN, ":::")[1]
return aws.String(bucketName), nil
}
return nil, fmt.Errorf("bucket %s does not exist", bucket)
}
func isS3AccessDeniedErr(err error) bool {
var opErr *smithy.OperationError
if errors.As(err, &opErr) {
return opErr.Service() == "S3" && strings.Contains(opErr.Unwrap().Error(), "AccessDenied")
}
return false
}
// Read and return the contents of a file in a bucket
func (s *S3StorageService) Read(ctx context.Context, req *storagepb.StorageReadRequest) (*storagepb.StorageReadResponse, error) {
newErr := grpc_errors.ErrorsWithScope("S3StorageService.Read")
if s3BucketName, err := s.getS3BucketName(ctx, req.BucketName); err == nil {
resp, err := s.s3Client.GetObject(ctx, &s3.GetObjectInput{
Bucket: s3BucketName,
Key: aws.String(req.Key),
})
if err != nil {
if isS3AccessDeniedErr(err) {
return nil, newErr(
codes.PermissionDenied,
"unable to read file, this may be due to a missing permissions request in your code.",
err,
)
}
return nil, newErr(
codes.Unknown,
"error reading file",
err,
)
}
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return &storagepb.StorageReadResponse{
Body: bodyBytes,
}, nil
} else {
return nil, newErr(
codes.NotFound,
"error finding S3 bucket",
err,
)
}
}
// Write contents to a file in a bucket
func (s *S3StorageService) Write(ctx context.Context, req *storagepb.StorageWriteRequest) (*storagepb.StorageWriteResponse, error) {
newErr := grpc_errors.ErrorsWithScope("S3StorageService.Write")
if b, err := s.getS3BucketName(ctx, req.BucketName); err == nil {
contentType := http.DetectContentType(req.Body)
if _, err := s.s3Client.PutObject(ctx, &s3.PutObjectInput{
Bucket: b,
Body: bytes.NewReader(req.Body),
ContentType: &contentType,
Key: aws.String(req.Key),
}); err != nil {
if isS3AccessDeniedErr(err) {
return nil, newErr(
codes.PermissionDenied,
"unable to write file, this may be due to a missing permissions request in your code.",
err,
)
}
return nil, newErr(
codes.Unknown,
"error writing file",
err,
)
}
} else {
return nil, newErr(
codes.NotFound,
"error finding S3 bucket",
err,
)
}
return &storagepb.StorageWriteResponse{}, nil
}
// Delete a file from a bucket
func (s *S3StorageService) Delete(ctx context.Context, req *storagepb.StorageDeleteRequest) (*storagepb.StorageDeleteResponse, error) {
newErr := grpc_errors.ErrorsWithScope("S3StorageService.Delete")
if b, err := s.getS3BucketName(ctx, req.BucketName); err == nil {
if _, err := s.s3Client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: b,
Key: aws.String(req.Key),
}); err != nil {
if isS3AccessDeniedErr(err) {
return nil, newErr(
codes.PermissionDenied,
"unable to delete file, this may be due to a missing permissions request in your code.",
err,
)
}
return nil, newErr(
codes.Unknown,
"error deleting file",
err,
)
}
} else {
return nil, newErr(
codes.NotFound,
"error finding S3 bucket",
err,
)
}
return &storagepb.StorageDeleteResponse{}, nil
}
// PreSignUrl generates a signed URL which can be used to perform direct operations on a file
// useful for large file uploads/downloads so they can bypass application code and work directly with S3
func (s *S3StorageService) PreSignUrl(ctx context.Context, req *storagepb.StoragePreSignUrlRequest) (*storagepb.StoragePreSignUrlResponse, error) {
newErr := grpc_errors.ErrorsWithScope("S3StorageService.PreSignUrl")
if b, err := s.getS3BucketName(ctx, req.BucketName); err == nil {
switch req.Operation {
case storagepb.StoragePreSignUrlRequest_READ:
response, err := s.preSignClient.PresignGetObject(ctx, &s3.GetObjectInput{
Bucket: b,
Key: aws.String(req.Key),
}, s3.WithPresignExpires(req.Expiry.AsDuration()))
if err != nil {
return nil, newErr(
codes.Internal,
"failed to generate signed READ URL",
err,
)
}
return &storagepb.StoragePreSignUrlResponse{
Url: response.URL,
}, err
case storagepb.StoragePreSignUrlRequest_WRITE:
req, err := s.preSignClient.PresignPutObject(ctx, &s3.PutObjectInput{
Bucket: b,
Key: aws.String(req.Key),
}, s3.WithPresignExpires(req.Expiry.AsDuration()))
if err != nil {
return nil, newErr(
codes.Internal,
"failed to generate signed WRITE URL",
err,
)
}
return &storagepb.StoragePreSignUrlResponse{
Url: req.URL,
}, err
default:
return nil, newErr(codes.Unimplemented, "requested operation not supported for pre-signed AWS S3 URLs", nil)
}
} else {
return nil, newErr(
codes.NotFound,
"error finding S3 bucket",
err,
)
}
}
// ListFiles lists all files in a bucket
func (s *S3StorageService) ListBlobs(ctx context.Context, req *storagepb.StorageListBlobsRequest) (*storagepb.StorageListBlobsResponse, error) {
newErr := grpc_errors.ErrorsWithScope("S3StorageService.ListFiles")
var prefix *string = nil
if req.Prefix != "" {
// Only apply if prefix isn't default
prefix = &req.Prefix
}
if b, err := s.getS3BucketName(ctx, req.BucketName); err == nil {
objects, err := s.s3Client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
Bucket: b,
Prefix: prefix,
})
if err != nil {
if isS3AccessDeniedErr(err) {
return nil, newErr(
codes.PermissionDenied,
"unable to list files, this may be due to a missing permissions request in your code.",
err,
)
}
return nil, newErr(
codes.Unknown,
"error listing files",
err,
)
}
files := make([]*storagepb.Blob, 0, len(objects.Contents))
for _, o := range objects.Contents {
files = append(files, &storagepb.Blob{
Key: *o.Key,
})
}
return &storagepb.StorageListBlobsResponse{
Blobs: files,
}, nil
} else {
return nil, newErr(
codes.NotFound,
"error finding S3 bucket",
err,
)
}
}
func (s *S3StorageService) Exists(ctx context.Context, req *storagepb.StorageExistsRequest) (*storagepb.StorageExistsResponse, error) {
newErr := grpc_errors.ErrorsWithScope("S3StorageService.Exists")
b, err := s.getS3BucketName(ctx, req.BucketName)
if err != nil {
return nil, newErr(codes.NotFound, "error finding S3 bucket", err)
}
_, err = s.s3Client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: b,
Key: aws.String(req.Key),
})
if err != nil {
if isS3AccessDeniedErr(err) {
return nil, newErr(
codes.PermissionDenied,
"unable to check if file exists, this may be due to a missing permissions request in your code.",
err,
)
}
return &storagepb.StorageExistsResponse{
Exists: false,
}, nil
}
return &storagepb.StorageExistsResponse{
Exists: true,
}, nil
}
// New creates a new default S3 storage plugin
func New(provider resource.AwsResourceProvider) (*S3StorageService, error) {
awsRegion := env.AWS_REGION.String()
cfg, sessionError := config.LoadDefaultConfig(context.TODO(), config.WithRegion(awsRegion))
if sessionError != nil {
return nil, fmt.Errorf("error creating new AWS session %w", sessionError)
}
otelaws.AppendMiddlewares(&cfg.APIOptions)
s3Client := s3.NewFromConfig(cfg)
return &S3StorageService{
s3Client: s3Client,
preSignClient: s3.NewPresignClient(s3Client),
provider: provider,
}, nil
}
// NewWithClient creates a new S3 Storage plugin and injects the given client
func NewWithClient(provider resource.AwsResourceProvider, client s3iface.S3API, preSignClient s3iface.PreSignAPI, opts ...S3StorageServiceOption) (*S3StorageService, error) {
s3Client := &S3StorageService{
s3Client: client,
preSignClient: preSignClient,
provider: provider,
}
for _, o := range opts {
o.Apply(s3Client)
}
return s3Client, nil
}