forked from pulibrary/pdc_describe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths3-checksum.yaml
270 lines (254 loc) · 10.4 KB
/
s3-checksum.yaml
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
AWSTemplateFormatVersion: "2010-09-09"
Description: Template to setup auto-generation of checksums for objects uploaded onto Amazon S3
Parameters:
ChecksumAlgorithm:
Type: String
Default: SHA256
AllowedValues:
- CRC32
- CRC32C
- SHA1
- SHA256
Description: Select Checksum Algorithm. Default and recommended choice is SHA256, however CRC32, CRC32C, SHA1 are also available.
S3Bucket:
Type: String
Description: Enter the Amazon S3 bucket for setting up Checksums.
Resources:
ChecksumLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
from urllib.parse import unquote_plus
import boto3
import os
s3_client = boto3.client('s3')
s3_resource = s3 = boto3.resource('s3')
def handler(event, context):
print(event)
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
key = unquote_plus(key)
print(f"Object '{key}' was just uploaded in Bucket {bucket}.")
copy_source = {
'Bucket': bucket,
'Key': key
}
attributes = get_attributes(bucket, key)
print(f"Attributes!!!")
print(attributes['Checksum'])
# Only proceed if Checksums don't already exist
if attributes['Checksum'] == None:
print(f"Copying {key} to the same place but adding Checksum ...")
try:
# If using SSE-KMS
if 'EncryptionKey' in attributes:
s3_resource.meta.client.copy(
copy_source,
Bucket=bucket,
Key=key,
ExtraArgs={
'ChecksumAlgorithm':os.environ['Checksum'],
'StorageClass': attributes['StorageClass'],
'ServerSideEncryption': attributes['Encryption'],
'SSEKMSKeyId': attributes['EncryptionKey']
}
)
# If using SSE-S3
elif attributes['Encryption'] != None:
s3_resource.meta.client.copy(
copy_source,
Bucket=bucket,
Key=key,
ExtraArgs={
'ChecksumAlgorithm':os.environ['Checksum'],
'StorageClass': attributes['StorageClass'],
'ServerSideEncryption': attributes['Encryption']
}
)
# If not using any encryption - NOT RECOMMENDED
else:
print(os.environ['Checksum'])
s3_resource.meta.client.copy(
copy_source,
Bucket=bucket,
Key=key,
ExtraArgs={
'ChecksumAlgorithm':os.environ['Checksum'],
'StorageClass': attributes['StorageClass']
}
)
print(f"SUCCESS: {key} now has a {os.environ['Checksum']} Checksum ")
except Exception as e:
print(e)
raise
else:
print(f"{key} already has a Checksum; No further action needed!")
return
def get_attributes(bucket, key):
try:
attributes = {}
response = s3_client.get_object_attributes(
Bucket=bucket,
Key=key,
ObjectAttributes=['Checksum']
)
# Check if the Object already has Checksums
checksum = response['Checksum'].keys() if 'Checksum' in response else [ ]
print(f"Checking whether {key} already has Checksum {checksum}")
if 'ChecksumCRC32' in checksum:
attributes['Checksum'] = 'ChecksumCRC32'
print(f"{key} already has a CRC32 Checksum!")
return attributes
elif 'ChecksumCRC32C' in checksum:
attributes['Checksum'] = 'ChecksumCRC32C'
print(f"{key} already has a CRC32C Checksum!")
return attributes
elif 'ChecksumSHA1' in checksum:
attributes['Checksum'] = 'ChecksumSHA1'
print(f"{key} already has a SHA1 Checksum!")
return attributes
elif 'ChecksumSHA256' in checksum:
attributes['Checksum'] = 'ChecksumSHA256'
print(f"{key} already has a SHA256 Checksum!")
return attributes
else:
print(f"{key} does not have a Checksum!")
attributes['Checksum'] = None
print(f"Obtaining other attributes for {key} ...")
#Check Object's storage class
print(f"Checking Storage Class for {key} ...")
if 'StorageClass' not in response:
print(f"{key} is stored in S3-STANDARD.")
attributes['StorageClass'] = 'STANDARD'
else:
storage_class = response['StorageClass']
print(f"{key} is stored in {storage_class}.")
attributes['StorageClass'] = response['StorageClass']
# Check Object's encryption
print(f"Checking Encryption for {key} ...")
if 'ServerSideEncryption' not in response:
print(f"{key} is not encrypted.")
attributes['Encryption'] = None
else:
print(f"{key} is encrypted.")
attributes['Encryption'] = response['ServerSideEncryption']
if response['ServerSideEncryption'] == 'aws:kms':
attributes['EncryptionKey'] = response['SSEKMSKeyId']
return attributes
except Exception as e:
print(e)
raise
Description: Function to add Checksums to objects in Amazon S3
Environment:
Variables:
Checksum: !Ref ChecksumAlgorithm
Handler: index.handler
Role: !GetAtt ChecksumLambdaRole.Arn
Runtime: python3.9
Timeout: 600
ReservedConcurrentExecutions: 10
Metadata:
cfn_nag:
rules_to_suppress:
- id: W89
reason: "The function does not process any data but merely copies it, hence VPC configuration is not needed."
ChecksumLambdaRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: "lambda.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
Policies:
- PolicyName: S3Permissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: S3ReadWrite
Effect: Allow
Action:
- s3:PutObject
- s3:PutObjectTagging
- s3:PutObjectAcl
- s3:GetObject
- s3:GetObjectVersion
- s3:GetObjectTagging
- s3:GetObjectAcl
- s3:GetObjectAttributes
- s3:GetObjectVersionAttributes
- s3:ListBucket
Resource:
- !Sub "arn:aws:s3:::${S3Bucket}/*"
- PolicyName: KMSPermissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: S3ReadWrite
Effect: Allow
Action:
- kms:Decrypt
- kms:Encrypt
- kms:GenerateDataKey
Resource:
- !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:key/*"
S3InvokeLambdaPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref ChecksumLambdaFunction
Principal: s3.amazonaws.com
SourceArn: !Sub arn:aws:s3:::${S3Bucket}
SourceAccount: !Ref "AWS::AccountId"
S3BatchRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: "batchoperations.s3.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
Policies:
- PolicyName: S3Permissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: S3ReadWrite
Effect: Allow
Action:
- s3:PutObject
- s3:PutObjectAcl
- s3:PutObjectTagging
- s3:GetObject
- s3:GetObjectVersion
- s3:GetObjectAcl
- s3:GetObjectTagging
- s3:ListBucket
- s3:InitiateReplication
- s3:GetReplicationConfiguration
- s3:PutInventoryConfiguration
Resource:
- !Sub "arn:aws:s3:::${S3Bucket}/*"
- PolicyName: KMSPermissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: S3ReadWrite
Effect: Allow
Action:
- kms:Decrypt
- kms:Encrypt
- kms:GenerateDataKey
Resource:
- !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:key/*"