This repository was archived by the owner on Dec 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy paths3.py
98 lines (79 loc) · 2.65 KB
/
s3.py
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
import json
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client('s3')
RF_ACCESS_POLICY = {
'Sid': 'RasterFoundryReadWriteAccess',
'Effect': 'Allow',
'Principal': {
'AWS': 'arn:aws:iam::615874746523:root'
},
'Action': [
's3:GetObject',
's3:ListBucket',
's3:PutObject'
],
'Resource': [
'arn:aws:s3:::{}',
'arn:aws:s3:::{}/*'
]
}
def authorize_bucket(bucket_name):
"""Authorize Raster Foundry to read and write from an S3 bucket
Args:
bucket_name (str): the name of the bucket to authorize
Returns:
int: the status code from the attempted policy change
"""
rf_access_policy = RF_ACCESS_POLICY.copy()
rf_access_policy['Resource'] = [
x.format(bucket_name) for x in rf_access_policy['Resource']
]
try:
resp = s3.get_bucket_policy(Bucket=bucket_name)
existing_policy = json.loads(resp['Policy'])
except ClientError:
existing_policy = {
'Version': '2012-10-17',
'Statement': []
}
existing_policy['Statement'].append(rf_access_policy)
new_policy_str = json.dumps(existing_policy)
return s3.put_bucket_policy(
Bucket=bucket_name, Policy=new_policy_str
)['ResponseMetadata']['HTTPStatusCode']
def unauthorize_bucket(bucket_name):
"""Remove Raster Foundry authorization from a bucket
Args:
bucket_name (str): the name of the bucket to unauthorize
Returns:
int: the status code from the attempted policy change
"""
rf_access_policy = RF_ACCESS_POLICY.copy()
rf_access_policy['Resource'] = [
x.format(bucket_name) for x in rf_access_policy['Resource']
]
try:
resp = s3.get_bucket_policy(Bucket=bucket_name)
existing_policy = json.loads(resp['Policy'])
except ClientError:
existing_policy = {
'Version': '2012-10-17',
'Statement': []
}
if rf_access_policy in existing_policy['Statement']:
new_statement = [
x for x in existing_policy['Statement'] if x != rf_access_policy
]
existing_policy['Statement'] = new_statement
if new_statement:
new_policy_str = json.dumps(existing_policy)
resp = s3.put_bucket_policy(
Bucket=bucket_name, Policy=new_policy_str
)['ResponseMetadata']['HTTPStatusCode']
else:
resp = s3.delete_bucket_policy(Bucket=bucket_name)
else:
# No work to do, so just create a mock response
resp = {'ResponseMetadata': {'HTTPStatusCode': 204}}
return resp['ResponseMetadata']['HTTPStatusCode']