aimodelshare 0.1.29__py3-none-any.whl → 0.1.64__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of aimodelshare might be problematic. Click here for more details.
- aimodelshare/__init__.py +94 -14
- aimodelshare/aimsonnx.py +417 -262
- aimodelshare/api.py +13 -12
- aimodelshare/auth.py +163 -0
- aimodelshare/aws.py +4 -4
- aimodelshare/base_image.py +1 -1
- aimodelshare/containerisation.py +1 -1
- aimodelshare/data_sharing/download_data.py +103 -70
- aimodelshare/generatemodelapi.py +7 -6
- aimodelshare/main/authorization.txt +275 -275
- aimodelshare/main/eval_lambda.txt +81 -13
- aimodelshare/model.py +493 -197
- aimodelshare/modeluser.py +89 -1
- aimodelshare/moral_compass/README.md +408 -0
- aimodelshare/moral_compass/__init__.py +37 -0
- aimodelshare/moral_compass/_version.py +3 -0
- aimodelshare/moral_compass/api_client.py +601 -0
- aimodelshare/moral_compass/apps/__init__.py +26 -0
- aimodelshare/moral_compass/apps/ai_consequences.py +297 -0
- aimodelshare/moral_compass/apps/judge.py +299 -0
- aimodelshare/moral_compass/apps/tutorial.py +198 -0
- aimodelshare/moral_compass/apps/what_is_ai.py +426 -0
- aimodelshare/moral_compass/challenge.py +365 -0
- aimodelshare/moral_compass/config.py +187 -0
- aimodelshare/playground.py +26 -14
- aimodelshare/preprocessormodules.py +60 -6
- aimodelshare/pyspark/authorization.txt +258 -258
- aimodelshare/pyspark/eval_lambda.txt +1 -1
- aimodelshare/reproducibility.py +20 -5
- aimodelshare/utils/__init__.py +78 -0
- aimodelshare/utils/optional_deps.py +38 -0
- aimodelshare-0.1.64.dist-info/METADATA +298 -0
- {aimodelshare-0.1.29.dist-info → aimodelshare-0.1.64.dist-info}/RECORD +36 -25
- {aimodelshare-0.1.29.dist-info → aimodelshare-0.1.64.dist-info}/WHEEL +1 -1
- aimodelshare-0.1.64.dist-info/licenses/LICENSE +5 -0
- {aimodelshare-0.1.29.dist-info → aimodelshare-0.1.64.dist-info}/top_level.txt +0 -1
- aimodelshare-0.1.29.dist-info/METADATA +0 -78
- aimodelshare-0.1.29.dist-info/licenses/LICENSE +0 -22
- tests/__init__.py +0 -0
- tests/test_aimsonnx.py +0 -135
- tests/test_playground.py +0 -721
|
@@ -1,275 +1,275 @@
|
|
|
1
|
-
from __future__ import print_function
|
|
2
|
-
|
|
3
|
-
import re
|
|
4
|
-
import json
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
def handler(event, context):
|
|
8
|
-
print("Client token: " + event.get('authorizationToken','empty'))
|
|
9
|
-
print("Method ARN: " + event.get('methodArn','empty'))
|
|
10
|
-
'''
|
|
11
|
-
Validate the incoming token and produce the principal user identifier
|
|
12
|
-
associated with the token. This can be accomplished in a number of ways:
|
|
13
|
-
|
|
14
|
-
1. Call out to the OAuth provider
|
|
15
|
-
2. Decode a JWT token inline
|
|
16
|
-
3. Lookup in a self-managed DB
|
|
17
|
-
'''
|
|
18
|
-
idtoken=event.get('authorizationToken','empty')
|
|
19
|
-
tokenlength=len(idtoken)
|
|
20
|
-
print(tokenlength)
|
|
21
|
-
print(event)
|
|
22
|
-
evaltrue="FALSE"
|
|
23
|
-
principalId = idtoken
|
|
24
|
-
|
|
25
|
-
if tokenlength>=40:
|
|
26
|
-
try:
|
|
27
|
-
tokenbodydata=json.loads(idtoken)
|
|
28
|
-
idtoken=tokenbodydata['token']
|
|
29
|
-
evaltrue=tokenbodydata['eval']
|
|
30
|
-
principalId = idtoken
|
|
31
|
-
|
|
32
|
-
except:
|
|
33
|
-
evaltrue="FALSE"
|
|
34
|
-
|
|
35
|
-
try:
|
|
36
|
-
|
|
37
|
-
import jwt
|
|
38
|
-
decoded = jwt.decode(idtoken, options={"verify_signature": False}) # works in PyJWT < v2.0
|
|
39
|
-
except:
|
|
40
|
-
pass
|
|
41
|
-
else:
|
|
42
|
-
pass
|
|
43
|
-
|
|
44
|
-
# Check token access with live rest api (with cognito auth activated) to ensure user isn't sending incorrect username
|
|
45
|
-
# 200 status indicates accept, 403 means unauthorized
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
#==============AIMODELSHARE Note: accept / deny languange located on line 67=======================================================
|
|
49
|
-
|
|
50
|
-
'''
|
|
51
|
-
You can send a 401 Unauthorized response to the client by failing like so:
|
|
52
|
-
|
|
53
|
-
raise Exception('Unauthorized')
|
|
54
|
-
|
|
55
|
-
If the token is valid, a policy must be generated which will allow or deny
|
|
56
|
-
access to the client. If access is denied, the client will receive a 403
|
|
57
|
-
Access Denied response. If access is allowed, API Gateway will proceed with
|
|
58
|
-
the backend integration configured on the method that was called.
|
|
59
|
-
|
|
60
|
-
This function must generate a policy that is associated with the recognized
|
|
61
|
-
principal user identifier. Depending on your use case, you might store
|
|
62
|
-
policies in a DB, or generate them on the fly.
|
|
63
|
-
|
|
64
|
-
Keep in mind, the policy is cached for 5 minutes by default (TTL is
|
|
65
|
-
configurable in the authorizer) and will apply to subsequent calls to any
|
|
66
|
-
method/resource in the RestApi made with the same token.
|
|
67
|
-
|
|
68
|
-
The example policy below denies access to all resources in the RestApi.
|
|
69
|
-
'''
|
|
70
|
-
tmp = event['methodArn'].split(':')
|
|
71
|
-
apiGatewayArnTmp = tmp[5].split('/')
|
|
72
|
-
awsAccountId = tmp[4]
|
|
73
|
-
|
|
74
|
-
policy = AuthPolicy(principalId, awsAccountId)
|
|
75
|
-
policy.restApiId = apiGatewayArnTmp[0]
|
|
76
|
-
policy.region = tmp[3]
|
|
77
|
-
policy.stage = apiGatewayArnTmp[1]
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
#====================Accept/Deny auth for AIMODELSHARE begins here===========================================
|
|
81
|
-
|
|
82
|
-
import requests
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
headers_with_authentication = {'Content-Type': 'application/json', 'Authorization': idtoken}
|
|
86
|
-
|
|
87
|
-
response=requests.post("https://1b861v14ne.execute-api.us-east-1.amazonaws.com/dev/redisusagetrackerembedded",
|
|
88
|
-
json={"apiid": str(policy.restApiId),"eval":evaltrue}, headers=headers_with_authentication)
|
|
89
|
-
print(response.status_code)
|
|
90
|
-
uniquemodversion=str(response.text)
|
|
91
|
-
|
|
92
|
-
print(response.text)
|
|
93
|
-
|
|
94
|
-
if idtoken=="$apikey":
|
|
95
|
-
policyresult="accept"
|
|
96
|
-
|
|
97
|
-
elif any([response.status_code!=200,response.text.find("Missing")>0,response.text.find("Monthly")>0,response.text.find("monthly")>0]):
|
|
98
|
-
policyresult="deny"
|
|
99
|
-
else:
|
|
100
|
-
policyresult="accept"
|
|
101
|
-
|
|
102
|
-
if policyresult=="deny":
|
|
103
|
-
policy.denyAllMethods()
|
|
104
|
-
else:
|
|
105
|
-
policy.allowAllMethods()
|
|
106
|
-
|
|
107
|
-
# Finally, build the policy
|
|
108
|
-
authResponse = policy.build()
|
|
109
|
-
authResponse['context']['uniquemodversion']=uniquemodversion
|
|
110
|
-
|
|
111
|
-
# new! -- add additional key-value pairs associated with the authenticated principal
|
|
112
|
-
# these are made available by APIGW like so: $context.authorizer.<key>
|
|
113
|
-
# additional context is cached
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
return authResponse
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
class HttpVerb:
|
|
121
|
-
GET = 'GET'
|
|
122
|
-
POST = 'POST'
|
|
123
|
-
PUT = 'PUT'
|
|
124
|
-
PATCH = 'PATCH'
|
|
125
|
-
HEAD = 'HEAD'
|
|
126
|
-
DELETE = 'DELETE'
|
|
127
|
-
OPTIONS = 'OPTIONS'
|
|
128
|
-
ALL = '*'
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
class AuthPolicy(object):
|
|
132
|
-
# The AWS account id the policy will be generated for. This is used to create the method ARNs.
|
|
133
|
-
awsAccountId = ''
|
|
134
|
-
# The principal used for the policy, this should be a unique identifier for the end user.
|
|
135
|
-
principalId = ''
|
|
136
|
-
# The policy version used for the evaluation. This should always be '2012-10-17'
|
|
137
|
-
version = '2012-10-17'
|
|
138
|
-
# The regular expression used to validate resource paths for the policy
|
|
139
|
-
pathRegex = '^[/.a-zA-Z0-9-\*]+$'
|
|
140
|
-
|
|
141
|
-
'''Internal lists of allowed and denied methods.
|
|
142
|
-
|
|
143
|
-
These are lists of objects and each object has 2 properties: A resource
|
|
144
|
-
ARN and a nullable conditions statement. The build method processes these
|
|
145
|
-
lists and generates the approriate statements for the final policy.
|
|
146
|
-
'''
|
|
147
|
-
allowMethods = []
|
|
148
|
-
denyMethods = []
|
|
149
|
-
|
|
150
|
-
# The API Gateway API id. By default this is set to '*'
|
|
151
|
-
restApiId = '*'
|
|
152
|
-
# The region where the API is deployed. By default this is set to '*'
|
|
153
|
-
region = '*'
|
|
154
|
-
# The name of the stage used in the policy. By default this is set to '*'
|
|
155
|
-
stage = '*'
|
|
156
|
-
|
|
157
|
-
def __init__(self, principal, awsAccountId):
|
|
158
|
-
self.awsAccountId = awsAccountId
|
|
159
|
-
self.principalId = principal
|
|
160
|
-
self.allowMethods = []
|
|
161
|
-
self.denyMethods = []
|
|
162
|
-
|
|
163
|
-
def _addMethod(self, effect, verb, resource, conditions):
|
|
164
|
-
'''Adds a method to the internal lists of allowed or denied methods. Each object in
|
|
165
|
-
the internal list contains a resource ARN and a condition statement. The condition
|
|
166
|
-
statement can be null.'''
|
|
167
|
-
if verb != '*' and not hasattr(HttpVerb, verb):
|
|
168
|
-
raise NameError('Invalid HTTP verb ' + verb + '. Allowed verbs in HttpVerb class')
|
|
169
|
-
resourcePattern = re.compile(self.pathRegex)
|
|
170
|
-
if not resourcePattern.match(resource):
|
|
171
|
-
raise NameError('Invalid resource path: ' + resource + '. Path should match ' + self.pathRegex)
|
|
172
|
-
|
|
173
|
-
if resource[:1] == '/':
|
|
174
|
-
resource = resource[1:]
|
|
175
|
-
|
|
176
|
-
resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)
|
|
177
|
-
|
|
178
|
-
if effect.lower() == 'allow':
|
|
179
|
-
self.allowMethods.append({
|
|
180
|
-
'resourceArn': resourceArn,
|
|
181
|
-
'conditions': conditions
|
|
182
|
-
})
|
|
183
|
-
elif effect.lower() == 'deny':
|
|
184
|
-
self.denyMethods.append({
|
|
185
|
-
'resourceArn': resourceArn,
|
|
186
|
-
'conditions': conditions
|
|
187
|
-
})
|
|
188
|
-
|
|
189
|
-
def _getEmptyStatement(self, effect):
|
|
190
|
-
'''Returns an empty statement object prepopulated with the correct action and the
|
|
191
|
-
desired effect.'''
|
|
192
|
-
statement = {
|
|
193
|
-
'Action': 'execute-api:Invoke',
|
|
194
|
-
'Effect': effect[:1].upper() + effect[1:].lower(),
|
|
195
|
-
'Resource': []
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
return statement
|
|
199
|
-
|
|
200
|
-
def _getStatementForEffect(self, effect, methods):
|
|
201
|
-
'''This function loops over an array of objects containing a resourceArn and
|
|
202
|
-
conditions statement and generates the array of statements for the policy.'''
|
|
203
|
-
statements = []
|
|
204
|
-
|
|
205
|
-
if len(methods) > 0:
|
|
206
|
-
statement = self._getEmptyStatement(effect)
|
|
207
|
-
|
|
208
|
-
for curMethod in methods:
|
|
209
|
-
if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
|
|
210
|
-
statement['Resource'].append(curMethod['resourceArn'])
|
|
211
|
-
else:
|
|
212
|
-
conditionalStatement = self._getEmptyStatement(effect)
|
|
213
|
-
conditionalStatement['Resource'].append(curMethod['resourceArn'])
|
|
214
|
-
conditionalStatement['Condition'] = curMethod['conditions']
|
|
215
|
-
statements.append(conditionalStatement)
|
|
216
|
-
|
|
217
|
-
if statement['Resource']:
|
|
218
|
-
statements.append(statement)
|
|
219
|
-
|
|
220
|
-
return statements
|
|
221
|
-
|
|
222
|
-
def allowAllMethods(self):
|
|
223
|
-
'''Adds a '*' allow to the policy to authorize access to all methods of an API'''
|
|
224
|
-
self._addMethod('Allow', HttpVerb.ALL, '*', [])
|
|
225
|
-
|
|
226
|
-
def denyAllMethods(self):
|
|
227
|
-
'''Adds a '*' allow to the policy to deny access to all methods of an API'''
|
|
228
|
-
self._addMethod('Deny', HttpVerb.ALL, '*', [])
|
|
229
|
-
|
|
230
|
-
def allowMethod(self, verb, resource):
|
|
231
|
-
'''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
|
|
232
|
-
methods for the policy'''
|
|
233
|
-
self._addMethod('Allow', verb, resource, [])
|
|
234
|
-
|
|
235
|
-
def denyMethod(self, verb, resource):
|
|
236
|
-
'''Adds an API Gateway method (Http verb + Resource path) to the list of denied
|
|
237
|
-
methods for the policy'''
|
|
238
|
-
self._addMethod('Deny', verb, resource, [])
|
|
239
|
-
|
|
240
|
-
def allowMethodWithConditions(self, verb, resource, conditions):
|
|
241
|
-
'''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
|
|
242
|
-
methods and includes a condition for the policy statement. More on AWS policy
|
|
243
|
-
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
|
|
244
|
-
self._addMethod('Allow', verb, resource, conditions)
|
|
245
|
-
|
|
246
|
-
def denyMethodWithConditions(self, verb, resource, conditions):
|
|
247
|
-
'''Adds an API Gateway method (Http verb + Resource path) to the list of denied
|
|
248
|
-
methods and includes a condition for the policy statement. More on AWS policy
|
|
249
|
-
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
|
|
250
|
-
self._addMethod('Deny', verb, resource, conditions)
|
|
251
|
-
|
|
252
|
-
def build(self):
|
|
253
|
-
'''Generates the policy document based on the internal lists of allowed and denied
|
|
254
|
-
conditions. This will generate a policy with two main statements for the effect:
|
|
255
|
-
one statement for Allow and one statement for Deny.
|
|
256
|
-
Methods that includes conditions will have their own statement in the policy.'''
|
|
257
|
-
if ((self.allowMethods is None or len(self.allowMethods) == 0) and
|
|
258
|
-
(self.denyMethods is None or len(self.denyMethods) == 0)):
|
|
259
|
-
raise NameError('No statements defined for the policy')
|
|
260
|
-
|
|
261
|
-
policy = {
|
|
262
|
-
'principalId': self.principalId,
|
|
263
|
-
'policyDocument': {
|
|
264
|
-
'Version': self.version,
|
|
265
|
-
'Statement': []
|
|
266
|
-
},
|
|
267
|
-
"context": {
|
|
268
|
-
"uniquemodversion":"string"
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Allow', self.allowMethods))
|
|
273
|
-
policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Deny', self.denyMethods))
|
|
274
|
-
|
|
275
|
-
return policy
|
|
1
|
+
from __future__ import print_function
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def handler(event, context):
|
|
8
|
+
print("Client token: " + event.get('authorizationToken','empty'))
|
|
9
|
+
print("Method ARN: " + event.get('methodArn','empty'))
|
|
10
|
+
'''
|
|
11
|
+
Validate the incoming token and produce the principal user identifier
|
|
12
|
+
associated with the token. This can be accomplished in a number of ways:
|
|
13
|
+
|
|
14
|
+
1. Call out to the OAuth provider
|
|
15
|
+
2. Decode a JWT token inline
|
|
16
|
+
3. Lookup in a self-managed DB
|
|
17
|
+
'''
|
|
18
|
+
idtoken=event.get('authorizationToken','empty')
|
|
19
|
+
tokenlength=len(idtoken)
|
|
20
|
+
print(tokenlength)
|
|
21
|
+
print(event)
|
|
22
|
+
evaltrue="FALSE"
|
|
23
|
+
principalId = idtoken
|
|
24
|
+
|
|
25
|
+
if tokenlength>=40:
|
|
26
|
+
try:
|
|
27
|
+
tokenbodydata=json.loads(idtoken)
|
|
28
|
+
idtoken=tokenbodydata['token']
|
|
29
|
+
evaltrue=tokenbodydata['eval']
|
|
30
|
+
principalId = idtoken
|
|
31
|
+
|
|
32
|
+
except:
|
|
33
|
+
evaltrue="FALSE"
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
|
|
37
|
+
import jwt
|
|
38
|
+
decoded = jwt.decode(idtoken, options={"verify_signature": False}) # works in PyJWT < v2.0
|
|
39
|
+
except:
|
|
40
|
+
pass
|
|
41
|
+
else:
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
# Check token access with live rest api (with cognito auth activated) to ensure user isn't sending incorrect username
|
|
45
|
+
# 200 status indicates accept, 403 means unauthorized
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
#==============AIMODELSHARE Note: accept / deny languange located on line 67=======================================================
|
|
49
|
+
|
|
50
|
+
'''
|
|
51
|
+
You can send a 401 Unauthorized response to the client by failing like so:
|
|
52
|
+
|
|
53
|
+
raise Exception('Unauthorized')
|
|
54
|
+
|
|
55
|
+
If the token is valid, a policy must be generated which will allow or deny
|
|
56
|
+
access to the client. If access is denied, the client will receive a 403
|
|
57
|
+
Access Denied response. If access is allowed, API Gateway will proceed with
|
|
58
|
+
the backend integration configured on the method that was called.
|
|
59
|
+
|
|
60
|
+
This function must generate a policy that is associated with the recognized
|
|
61
|
+
principal user identifier. Depending on your use case, you might store
|
|
62
|
+
policies in a DB, or generate them on the fly.
|
|
63
|
+
|
|
64
|
+
Keep in mind, the policy is cached for 5 minutes by default (TTL is
|
|
65
|
+
configurable in the authorizer) and will apply to subsequent calls to any
|
|
66
|
+
method/resource in the RestApi made with the same token.
|
|
67
|
+
|
|
68
|
+
The example policy below denies access to all resources in the RestApi.
|
|
69
|
+
'''
|
|
70
|
+
tmp = event['methodArn'].split(':')
|
|
71
|
+
apiGatewayArnTmp = tmp[5].split('/')
|
|
72
|
+
awsAccountId = tmp[4]
|
|
73
|
+
|
|
74
|
+
policy = AuthPolicy(principalId, awsAccountId)
|
|
75
|
+
policy.restApiId = apiGatewayArnTmp[0]
|
|
76
|
+
policy.region = tmp[3]
|
|
77
|
+
policy.stage = apiGatewayArnTmp[1]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
#====================Accept/Deny auth for AIMODELSHARE begins here===========================================
|
|
81
|
+
|
|
82
|
+
import requests
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
headers_with_authentication = {'Content-Type': 'application/json', 'Authorization': idtoken}
|
|
86
|
+
|
|
87
|
+
response=requests.post("https://1b861v14ne.execute-api.us-east-1.amazonaws.com/dev/redisusagetrackerembedded",
|
|
88
|
+
json={"apiid": str(policy.restApiId),"eval":evaltrue}, headers=headers_with_authentication)
|
|
89
|
+
print(response.status_code)
|
|
90
|
+
uniquemodversion=str(response.text)
|
|
91
|
+
|
|
92
|
+
print(response.text)
|
|
93
|
+
|
|
94
|
+
if idtoken=="$apikey":
|
|
95
|
+
policyresult="accept"
|
|
96
|
+
|
|
97
|
+
elif any([response.status_code!=200,response.text.find("Missing")>0,response.text.find("Monthly")>0,response.text.find("monthly")>0]):
|
|
98
|
+
policyresult="deny"
|
|
99
|
+
else:
|
|
100
|
+
policyresult="accept"
|
|
101
|
+
|
|
102
|
+
if policyresult=="deny":
|
|
103
|
+
policy.denyAllMethods()
|
|
104
|
+
else:
|
|
105
|
+
policy.allowAllMethods()
|
|
106
|
+
|
|
107
|
+
# Finally, build the policy
|
|
108
|
+
authResponse = policy.build()
|
|
109
|
+
authResponse['context']['uniquemodversion']=uniquemodversion
|
|
110
|
+
|
|
111
|
+
# new! -- add additional key-value pairs associated with the authenticated principal
|
|
112
|
+
# these are made available by APIGW like so: $context.authorizer.<key>
|
|
113
|
+
# additional context is cached
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
return authResponse
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class HttpVerb:
|
|
121
|
+
GET = 'GET'
|
|
122
|
+
POST = 'POST'
|
|
123
|
+
PUT = 'PUT'
|
|
124
|
+
PATCH = 'PATCH'
|
|
125
|
+
HEAD = 'HEAD'
|
|
126
|
+
DELETE = 'DELETE'
|
|
127
|
+
OPTIONS = 'OPTIONS'
|
|
128
|
+
ALL = '*'
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class AuthPolicy(object):
|
|
132
|
+
# The AWS account id the policy will be generated for. This is used to create the method ARNs.
|
|
133
|
+
awsAccountId = ''
|
|
134
|
+
# The principal used for the policy, this should be a unique identifier for the end user.
|
|
135
|
+
principalId = ''
|
|
136
|
+
# The policy version used for the evaluation. This should always be '2012-10-17'
|
|
137
|
+
version = '2012-10-17'
|
|
138
|
+
# The regular expression used to validate resource paths for the policy
|
|
139
|
+
pathRegex = '^[/.a-zA-Z0-9-\*]+$'
|
|
140
|
+
|
|
141
|
+
'''Internal lists of allowed and denied methods.
|
|
142
|
+
|
|
143
|
+
These are lists of objects and each object has 2 properties: A resource
|
|
144
|
+
ARN and a nullable conditions statement. The build method processes these
|
|
145
|
+
lists and generates the approriate statements for the final policy.
|
|
146
|
+
'''
|
|
147
|
+
allowMethods = []
|
|
148
|
+
denyMethods = []
|
|
149
|
+
|
|
150
|
+
# The API Gateway API id. By default this is set to '*'
|
|
151
|
+
restApiId = '*'
|
|
152
|
+
# The region where the API is deployed. By default this is set to '*'
|
|
153
|
+
region = '*'
|
|
154
|
+
# The name of the stage used in the policy. By default this is set to '*'
|
|
155
|
+
stage = '*'
|
|
156
|
+
|
|
157
|
+
def __init__(self, principal, awsAccountId):
|
|
158
|
+
self.awsAccountId = awsAccountId
|
|
159
|
+
self.principalId = principal
|
|
160
|
+
self.allowMethods = []
|
|
161
|
+
self.denyMethods = []
|
|
162
|
+
|
|
163
|
+
def _addMethod(self, effect, verb, resource, conditions):
|
|
164
|
+
'''Adds a method to the internal lists of allowed or denied methods. Each object in
|
|
165
|
+
the internal list contains a resource ARN and a condition statement. The condition
|
|
166
|
+
statement can be null.'''
|
|
167
|
+
if verb != '*' and not hasattr(HttpVerb, verb):
|
|
168
|
+
raise NameError('Invalid HTTP verb ' + verb + '. Allowed verbs in HttpVerb class')
|
|
169
|
+
resourcePattern = re.compile(self.pathRegex)
|
|
170
|
+
if not resourcePattern.match(resource):
|
|
171
|
+
raise NameError('Invalid resource path: ' + resource + '. Path should match ' + self.pathRegex)
|
|
172
|
+
|
|
173
|
+
if resource[:1] == '/':
|
|
174
|
+
resource = resource[1:]
|
|
175
|
+
|
|
176
|
+
resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)
|
|
177
|
+
|
|
178
|
+
if effect.lower() == 'allow':
|
|
179
|
+
self.allowMethods.append({
|
|
180
|
+
'resourceArn': resourceArn,
|
|
181
|
+
'conditions': conditions
|
|
182
|
+
})
|
|
183
|
+
elif effect.lower() == 'deny':
|
|
184
|
+
self.denyMethods.append({
|
|
185
|
+
'resourceArn': resourceArn,
|
|
186
|
+
'conditions': conditions
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
def _getEmptyStatement(self, effect):
|
|
190
|
+
'''Returns an empty statement object prepopulated with the correct action and the
|
|
191
|
+
desired effect.'''
|
|
192
|
+
statement = {
|
|
193
|
+
'Action': 'execute-api:Invoke',
|
|
194
|
+
'Effect': effect[:1].upper() + effect[1:].lower(),
|
|
195
|
+
'Resource': []
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return statement
|
|
199
|
+
|
|
200
|
+
def _getStatementForEffect(self, effect, methods):
|
|
201
|
+
'''This function loops over an array of objects containing a resourceArn and
|
|
202
|
+
conditions statement and generates the array of statements for the policy.'''
|
|
203
|
+
statements = []
|
|
204
|
+
|
|
205
|
+
if len(methods) > 0:
|
|
206
|
+
statement = self._getEmptyStatement(effect)
|
|
207
|
+
|
|
208
|
+
for curMethod in methods:
|
|
209
|
+
if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
|
|
210
|
+
statement['Resource'].append(curMethod['resourceArn'])
|
|
211
|
+
else:
|
|
212
|
+
conditionalStatement = self._getEmptyStatement(effect)
|
|
213
|
+
conditionalStatement['Resource'].append(curMethod['resourceArn'])
|
|
214
|
+
conditionalStatement['Condition'] = curMethod['conditions']
|
|
215
|
+
statements.append(conditionalStatement)
|
|
216
|
+
|
|
217
|
+
if statement['Resource']:
|
|
218
|
+
statements.append(statement)
|
|
219
|
+
|
|
220
|
+
return statements
|
|
221
|
+
|
|
222
|
+
def allowAllMethods(self):
|
|
223
|
+
'''Adds a '*' allow to the policy to authorize access to all methods of an API'''
|
|
224
|
+
self._addMethod('Allow', HttpVerb.ALL, '*', [])
|
|
225
|
+
|
|
226
|
+
def denyAllMethods(self):
|
|
227
|
+
'''Adds a '*' allow to the policy to deny access to all methods of an API'''
|
|
228
|
+
self._addMethod('Deny', HttpVerb.ALL, '*', [])
|
|
229
|
+
|
|
230
|
+
def allowMethod(self, verb, resource):
|
|
231
|
+
'''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
|
|
232
|
+
methods for the policy'''
|
|
233
|
+
self._addMethod('Allow', verb, resource, [])
|
|
234
|
+
|
|
235
|
+
def denyMethod(self, verb, resource):
|
|
236
|
+
'''Adds an API Gateway method (Http verb + Resource path) to the list of denied
|
|
237
|
+
methods for the policy'''
|
|
238
|
+
self._addMethod('Deny', verb, resource, [])
|
|
239
|
+
|
|
240
|
+
def allowMethodWithConditions(self, verb, resource, conditions):
|
|
241
|
+
'''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
|
|
242
|
+
methods and includes a condition for the policy statement. More on AWS policy
|
|
243
|
+
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
|
|
244
|
+
self._addMethod('Allow', verb, resource, conditions)
|
|
245
|
+
|
|
246
|
+
def denyMethodWithConditions(self, verb, resource, conditions):
|
|
247
|
+
'''Adds an API Gateway method (Http verb + Resource path) to the list of denied
|
|
248
|
+
methods and includes a condition for the policy statement. More on AWS policy
|
|
249
|
+
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
|
|
250
|
+
self._addMethod('Deny', verb, resource, conditions)
|
|
251
|
+
|
|
252
|
+
def build(self):
|
|
253
|
+
'''Generates the policy document based on the internal lists of allowed and denied
|
|
254
|
+
conditions. This will generate a policy with two main statements for the effect:
|
|
255
|
+
one statement for Allow and one statement for Deny.
|
|
256
|
+
Methods that includes conditions will have their own statement in the policy.'''
|
|
257
|
+
if ((self.allowMethods is None or len(self.allowMethods) == 0) and
|
|
258
|
+
(self.denyMethods is None or len(self.denyMethods) == 0)):
|
|
259
|
+
raise NameError('No statements defined for the policy')
|
|
260
|
+
|
|
261
|
+
policy = {
|
|
262
|
+
'principalId': self.principalId,
|
|
263
|
+
'policyDocument': {
|
|
264
|
+
'Version': self.version,
|
|
265
|
+
'Statement': []
|
|
266
|
+
},
|
|
267
|
+
"context": {
|
|
268
|
+
"uniquemodversion":"string"
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Allow', self.allowMethods))
|
|
273
|
+
policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Deny', self.denyMethods))
|
|
274
|
+
|
|
275
|
+
return policy
|