aimodelshare 0.1.55__py3-none-any.whl → 0.1.60__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 +263 -82
- 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 +133 -83
- 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 +58 -0
- aimodelshare/moral_compass/_version.py +3 -0
- aimodelshare/moral_compass/api_client.py +601 -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.60.dist-info/METADATA +258 -0
- {aimodelshare-0.1.55.dist-info → aimodelshare-0.1.60.dist-info}/RECORD +31 -25
- aimodelshare-0.1.60.dist-info/licenses/LICENSE +5 -0
- {aimodelshare-0.1.55.dist-info → aimodelshare-0.1.60.dist-info}/top_level.txt +0 -1
- aimodelshare-0.1.55.dist-info/METADATA +0 -63
- aimodelshare-0.1.55.dist-info/licenses/LICENSE +0 -2
- tests/__init__.py +0 -0
- tests/test_aimsonnx.py +0 -135
- tests/test_playground.py +0 -721
- {aimodelshare-0.1.55.dist-info → aimodelshare-0.1.60.dist-info}/WHEEL +0 -0
|
@@ -116,6 +116,26 @@ def import_preprocessor(filepath):
|
|
|
116
116
|
|
|
117
117
|
return preprocessor
|
|
118
118
|
|
|
119
|
+
def _test_object_serialization(obj, obj_name):
|
|
120
|
+
"""
|
|
121
|
+
Test if an object can be serialized with pickle.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
obj: Object to test
|
|
125
|
+
obj_name: Name of the object for error reporting
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
tuple: (success: bool, error_msg: str or None)
|
|
129
|
+
"""
|
|
130
|
+
import pickle
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
pickle.dumps(obj)
|
|
134
|
+
return True, None
|
|
135
|
+
except Exception as e:
|
|
136
|
+
return False, f"{type(e).__name__}: {str(e)}"
|
|
137
|
+
|
|
138
|
+
|
|
119
139
|
def export_preprocessor(preprocessor_fxn,directory, globs=globals()):
|
|
120
140
|
"""
|
|
121
141
|
Exports preprocessor and related objects into zip file for model deployment
|
|
@@ -167,7 +187,7 @@ def export_preprocessor(preprocessor_fxn,directory, globs=globals()):
|
|
|
167
187
|
function_objects=list(inspect.getclosurevars(preprocessor_fxn).globals.keys())
|
|
168
188
|
|
|
169
189
|
import sys
|
|
170
|
-
import
|
|
190
|
+
import importlib.util
|
|
171
191
|
modulenames = ["sklearn","keras","tensorflow","cv2","resize","pytorch","librosa","pyspark"]
|
|
172
192
|
|
|
173
193
|
# List all standard libraries not covered by sys.builtin_module_names
|
|
@@ -185,9 +205,12 @@ def export_preprocessor(preprocessor_fxn,directory, globs=globals()):
|
|
|
185
205
|
modulenames.append(module_name)
|
|
186
206
|
continue
|
|
187
207
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
208
|
+
# Use importlib.util instead of deprecated imp
|
|
209
|
+
spec = importlib.util.find_spec(module_name)
|
|
210
|
+
if spec and spec.origin:
|
|
211
|
+
module_path = spec.origin
|
|
212
|
+
if os.path.dirname(module_path) in stdlib:
|
|
213
|
+
modulenames.append(module_name)
|
|
191
214
|
except Exception as e:
|
|
192
215
|
# print(e)
|
|
193
216
|
continue
|
|
@@ -232,12 +255,19 @@ def export_preprocessor(preprocessor_fxn,directory, globs=globals()):
|
|
|
232
255
|
|
|
233
256
|
export_methods = []
|
|
234
257
|
savedpreprocessorobjectslist = []
|
|
258
|
+
failed_objects = [] # Track failed serializations for better diagnostics
|
|
259
|
+
|
|
235
260
|
for function_objects_nomodule in function_objects_nomodules:
|
|
236
261
|
try:
|
|
237
262
|
savedpreprocessorobjectslist.append(savetopickle(function_objects_nomodule))
|
|
238
263
|
export_methods.append("pickle")
|
|
239
264
|
except Exception as e:
|
|
240
|
-
#
|
|
265
|
+
# Track this failure for diagnostics
|
|
266
|
+
can_serialize, error_msg = _test_object_serialization(
|
|
267
|
+
globals().get(function_objects_nomodule),
|
|
268
|
+
function_objects_nomodule
|
|
269
|
+
)
|
|
270
|
+
|
|
241
271
|
try:
|
|
242
272
|
os.remove(os.path.join(temp_dir, function_objects_nomodule+".pkl"))
|
|
243
273
|
except:
|
|
@@ -246,7 +276,14 @@ def export_preprocessor(preprocessor_fxn,directory, globs=globals()):
|
|
|
246
276
|
try:
|
|
247
277
|
savedpreprocessorobjectslist.append(save_to_zip(function_objects_nomodule))
|
|
248
278
|
export_methods.append("zip")
|
|
249
|
-
except Exception as
|
|
279
|
+
except Exception as zip_e:
|
|
280
|
+
# Both pickle and zip failed - record this
|
|
281
|
+
failed_objects.append({
|
|
282
|
+
'name': function_objects_nomodule,
|
|
283
|
+
'type': type(globals().get(function_objects_nomodule, None)).__name__,
|
|
284
|
+
'pickle_error': str(e),
|
|
285
|
+
'zip_error': str(zip_e)
|
|
286
|
+
})
|
|
250
287
|
# print(e)
|
|
251
288
|
pass
|
|
252
289
|
|
|
@@ -265,6 +302,20 @@ def export_preprocessor(preprocessor_fxn,directory, globs=globals()):
|
|
|
265
302
|
# close the Zip File
|
|
266
303
|
zipObj.close()
|
|
267
304
|
|
|
305
|
+
# If any critical objects failed to serialize, raise an error with details
|
|
306
|
+
if failed_objects:
|
|
307
|
+
failed_names = [obj['name'] for obj in failed_objects]
|
|
308
|
+
error_details = "\n".join([
|
|
309
|
+
f" - {obj['name']} (type: {obj['type']}): {obj['pickle_error'][:100]}"
|
|
310
|
+
for obj in failed_objects
|
|
311
|
+
])
|
|
312
|
+
raise RuntimeError(
|
|
313
|
+
f"Preprocessor export encountered serialization failures for {len(failed_objects)} closure variable(s): "
|
|
314
|
+
f"{', '.join(failed_names)}.\n\nDetails:\n{error_details}\n\n"
|
|
315
|
+
f"These objects are referenced by your preprocessor function but cannot be serialized. "
|
|
316
|
+
f"Common causes include open file handles, database connections, or thread locks."
|
|
317
|
+
)
|
|
318
|
+
|
|
268
319
|
try:
|
|
269
320
|
# clean up temp directory files for future runs
|
|
270
321
|
os.remove(os.path.join(temp_dir,"preprocessor.py"))
|
|
@@ -279,6 +330,9 @@ def export_preprocessor(preprocessor_fxn,directory, globs=globals()):
|
|
|
279
330
|
pass
|
|
280
331
|
|
|
281
332
|
except Exception as e:
|
|
333
|
+
# Re-raise RuntimeError with preserved message
|
|
334
|
+
if isinstance(e, RuntimeError):
|
|
335
|
+
raise
|
|
282
336
|
print(e)
|
|
283
337
|
|
|
284
338
|
return print("Your preprocessor is now saved to 'preprocessor.zip'")
|
|
@@ -1,258 +1,258 @@
|
|
|
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['authorizationToken'])
|
|
9
|
-
print("Method ARN: " + event['methodArn'])
|
|
10
|
-
|
|
11
|
-
'''
|
|
12
|
-
Validate the incoming token and produce the principal user identifier
|
|
13
|
-
associated with the token. This can be accomplished in a number of ways:
|
|
14
|
-
|
|
15
|
-
1. Call out to the OAuth provider
|
|
16
|
-
2. Decode a JWT token inline
|
|
17
|
-
3. Lookup in a self-managed DB
|
|
18
|
-
'''
|
|
19
|
-
idtoken=event['authorizationToken']
|
|
20
|
-
try:
|
|
21
|
-
tokenbodydata=json.loads(idtoken)
|
|
22
|
-
idtoken=tokenbodydata['token']
|
|
23
|
-
evaltrue=tokenbodydata['eval']
|
|
24
|
-
except:
|
|
25
|
-
evaltrue="FALSE"
|
|
26
|
-
|
|
27
|
-
print(event)
|
|
28
|
-
principalId = idtoken
|
|
29
|
-
import jwt
|
|
30
|
-
decoded = jwt.decode(idtoken, options={"verify_signature": False}) # works in PyJWT < v2.0
|
|
31
|
-
|
|
32
|
-
# Check token access with live rest api (with cognito auth activated) to ensure user isn't sending incorrect username
|
|
33
|
-
# 200 status indicates accept, 403 means unauthorized
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
#==============AIMODELSHARE Note: accept / deny languange located on line 67=======================================================
|
|
37
|
-
|
|
38
|
-
'''
|
|
39
|
-
You can send a 401 Unauthorized response to the client by failing like so:
|
|
40
|
-
|
|
41
|
-
raise Exception('Unauthorized')
|
|
42
|
-
|
|
43
|
-
If the token is valid, a policy must be generated which will allow or deny
|
|
44
|
-
access to the client. If access is denied, the client will receive a 403
|
|
45
|
-
Access Denied response. If access is allowed, API Gateway will proceed with
|
|
46
|
-
the backend integration configured on the method that was called.
|
|
47
|
-
|
|
48
|
-
This function must generate a policy that is associated with the recognized
|
|
49
|
-
principal user identifier. Depending on your use case, you might store
|
|
50
|
-
policies in a DB, or generate them on the fly.
|
|
51
|
-
|
|
52
|
-
Keep in mind, the policy is cached for 5 minutes by default (TTL is
|
|
53
|
-
configurable in the authorizer) and will apply to subsequent calls to any
|
|
54
|
-
method/resource in the RestApi made with the same token.
|
|
55
|
-
|
|
56
|
-
The example policy below denies access to all resources in the RestApi.
|
|
57
|
-
'''
|
|
58
|
-
tmp = event['methodArn'].split(':')
|
|
59
|
-
apiGatewayArnTmp = tmp[5].split('/')
|
|
60
|
-
awsAccountId = tmp[4]
|
|
61
|
-
|
|
62
|
-
policy = AuthPolicy(principalId, awsAccountId)
|
|
63
|
-
policy.restApiId = apiGatewayArnTmp[0]
|
|
64
|
-
policy.region = tmp[3]
|
|
65
|
-
policy.stage = apiGatewayArnTmp[1]
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
#====================Accept/Deny auth for AIMODELSHARE begins here===========================================
|
|
69
|
-
import requests
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
headers_with_authentication = {'Content-Type': 'application/json', 'Authorization': idtoken}
|
|
73
|
-
|
|
74
|
-
response=requests.post("https://1b861v14ne.execute-api.us-east-1.amazonaws.com/dev/redisusagetrackerembedded",
|
|
75
|
-
json={"apiid": str(policy.restApiId),"eval":evaltrue}, headers=headers_with_authentication)
|
|
76
|
-
print(response.status_code)
|
|
77
|
-
uniquemodversion=str(response.text)
|
|
78
|
-
|
|
79
|
-
print(response.text)
|
|
80
|
-
if any([response.status_code!=200,response.text.find("Missing")>0,response.text.find("Monthly")>0,response.text.find("monthly")>0]):
|
|
81
|
-
policyresult="deny"
|
|
82
|
-
else:
|
|
83
|
-
policyresult="accept"
|
|
84
|
-
|
|
85
|
-
if policyresult=="deny":
|
|
86
|
-
policy.denyAllMethods()
|
|
87
|
-
else:
|
|
88
|
-
policy.allowAllMethods()
|
|
89
|
-
|
|
90
|
-
# Finally, build the policy
|
|
91
|
-
authResponse = policy.build()
|
|
92
|
-
authResponse['context']['uniquemodversion']=uniquemodversion
|
|
93
|
-
|
|
94
|
-
# new! -- add additional key-value pairs associated with the authenticated principal
|
|
95
|
-
# these are made available by APIGW like so: $context.authorizer.<key>
|
|
96
|
-
# additional context is cached
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
return authResponse
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
class HttpVerb:
|
|
104
|
-
GET = 'GET'
|
|
105
|
-
POST = 'POST'
|
|
106
|
-
PUT = 'PUT'
|
|
107
|
-
PATCH = 'PATCH'
|
|
108
|
-
HEAD = 'HEAD'
|
|
109
|
-
DELETE = 'DELETE'
|
|
110
|
-
OPTIONS = 'OPTIONS'
|
|
111
|
-
ALL = '*'
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
class AuthPolicy(object):
|
|
115
|
-
# The AWS account id the policy will be generated for. This is used to create the method ARNs.
|
|
116
|
-
awsAccountId = ''
|
|
117
|
-
# The principal used for the policy, this should be a unique identifier for the end user.
|
|
118
|
-
principalId = ''
|
|
119
|
-
# The policy version used for the evaluation. This should always be '2012-10-17'
|
|
120
|
-
version = '2012-10-17'
|
|
121
|
-
# The regular expression used to validate resource paths for the policy
|
|
122
|
-
pathRegex = '^[/.a-zA-Z0-9-\*]+$'
|
|
123
|
-
|
|
124
|
-
'''Internal lists of allowed and denied methods.
|
|
125
|
-
|
|
126
|
-
These are lists of objects and each object has 2 properties: A resource
|
|
127
|
-
ARN and a nullable conditions statement. The build method processes these
|
|
128
|
-
lists and generates the approriate statements for the final policy.
|
|
129
|
-
'''
|
|
130
|
-
allowMethods = []
|
|
131
|
-
denyMethods = []
|
|
132
|
-
|
|
133
|
-
# The API Gateway API id. By default this is set to '*'
|
|
134
|
-
restApiId = '*'
|
|
135
|
-
# The region where the API is deployed. By default this is set to '*'
|
|
136
|
-
region = '*'
|
|
137
|
-
# The name of the stage used in the policy. By default this is set to '*'
|
|
138
|
-
stage = '*'
|
|
139
|
-
|
|
140
|
-
def __init__(self, principal, awsAccountId):
|
|
141
|
-
self.awsAccountId = awsAccountId
|
|
142
|
-
self.principalId = principal
|
|
143
|
-
self.allowMethods = []
|
|
144
|
-
self.denyMethods = []
|
|
145
|
-
|
|
146
|
-
def _addMethod(self, effect, verb, resource, conditions):
|
|
147
|
-
'''Adds a method to the internal lists of allowed or denied methods. Each object in
|
|
148
|
-
the internal list contains a resource ARN and a condition statement. The condition
|
|
149
|
-
statement can be null.'''
|
|
150
|
-
if verb != '*' and not hasattr(HttpVerb, verb):
|
|
151
|
-
raise NameError('Invalid HTTP verb ' + verb + '. Allowed verbs in HttpVerb class')
|
|
152
|
-
resourcePattern = re.compile(self.pathRegex)
|
|
153
|
-
if not resourcePattern.match(resource):
|
|
154
|
-
raise NameError('Invalid resource path: ' + resource + '. Path should match ' + self.pathRegex)
|
|
155
|
-
|
|
156
|
-
if resource[:1] == '/':
|
|
157
|
-
resource = resource[1:]
|
|
158
|
-
|
|
159
|
-
resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)
|
|
160
|
-
|
|
161
|
-
if effect.lower() == 'allow':
|
|
162
|
-
self.allowMethods.append({
|
|
163
|
-
'resourceArn': resourceArn,
|
|
164
|
-
'conditions': conditions
|
|
165
|
-
})
|
|
166
|
-
elif effect.lower() == 'deny':
|
|
167
|
-
self.denyMethods.append({
|
|
168
|
-
'resourceArn': resourceArn,
|
|
169
|
-
'conditions': conditions
|
|
170
|
-
})
|
|
171
|
-
|
|
172
|
-
def _getEmptyStatement(self, effect):
|
|
173
|
-
'''Returns an empty statement object prepopulated with the correct action and the
|
|
174
|
-
desired effect.'''
|
|
175
|
-
statement = {
|
|
176
|
-
'Action': 'execute-api:Invoke',
|
|
177
|
-
'Effect': effect[:1].upper() + effect[1:].lower(),
|
|
178
|
-
'Resource': []
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
return statement
|
|
182
|
-
|
|
183
|
-
def _getStatementForEffect(self, effect, methods):
|
|
184
|
-
'''This function loops over an array of objects containing a resourceArn and
|
|
185
|
-
conditions statement and generates the array of statements for the policy.'''
|
|
186
|
-
statements = []
|
|
187
|
-
|
|
188
|
-
if len(methods) > 0:
|
|
189
|
-
statement = self._getEmptyStatement(effect)
|
|
190
|
-
|
|
191
|
-
for curMethod in methods:
|
|
192
|
-
if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
|
|
193
|
-
statement['Resource'].append(curMethod['resourceArn'])
|
|
194
|
-
else:
|
|
195
|
-
conditionalStatement = self._getEmptyStatement(effect)
|
|
196
|
-
conditionalStatement['Resource'].append(curMethod['resourceArn'])
|
|
197
|
-
conditionalStatement['Condition'] = curMethod['conditions']
|
|
198
|
-
statements.append(conditionalStatement)
|
|
199
|
-
|
|
200
|
-
if statement['Resource']:
|
|
201
|
-
statements.append(statement)
|
|
202
|
-
|
|
203
|
-
return statements
|
|
204
|
-
|
|
205
|
-
def allowAllMethods(self):
|
|
206
|
-
'''Adds a '*' allow to the policy to authorize access to all methods of an API'''
|
|
207
|
-
self._addMethod('Allow', HttpVerb.ALL, '*', [])
|
|
208
|
-
|
|
209
|
-
def denyAllMethods(self):
|
|
210
|
-
'''Adds a '*' allow to the policy to deny access to all methods of an API'''
|
|
211
|
-
self._addMethod('Deny', HttpVerb.ALL, '*', [])
|
|
212
|
-
|
|
213
|
-
def allowMethod(self, verb, resource):
|
|
214
|
-
'''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
|
|
215
|
-
methods for the policy'''
|
|
216
|
-
self._addMethod('Allow', verb, resource, [])
|
|
217
|
-
|
|
218
|
-
def denyMethod(self, verb, resource):
|
|
219
|
-
'''Adds an API Gateway method (Http verb + Resource path) to the list of denied
|
|
220
|
-
methods for the policy'''
|
|
221
|
-
self._addMethod('Deny', verb, resource, [])
|
|
222
|
-
|
|
223
|
-
def allowMethodWithConditions(self, verb, resource, conditions):
|
|
224
|
-
'''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
|
|
225
|
-
methods and includes a condition for the policy statement. More on AWS policy
|
|
226
|
-
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
|
|
227
|
-
self._addMethod('Allow', verb, resource, conditions)
|
|
228
|
-
|
|
229
|
-
def denyMethodWithConditions(self, verb, resource, conditions):
|
|
230
|
-
'''Adds an API Gateway method (Http verb + Resource path) to the list of denied
|
|
231
|
-
methods and includes a condition for the policy statement. More on AWS policy
|
|
232
|
-
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
|
|
233
|
-
self._addMethod('Deny', verb, resource, conditions)
|
|
234
|
-
|
|
235
|
-
def build(self):
|
|
236
|
-
'''Generates the policy document based on the internal lists of allowed and denied
|
|
237
|
-
conditions. This will generate a policy with two main statements for the effect:
|
|
238
|
-
one statement for Allow and one statement for Deny.
|
|
239
|
-
Methods that includes conditions will have their own statement in the policy.'''
|
|
240
|
-
if ((self.allowMethods is None or len(self.allowMethods) == 0) and
|
|
241
|
-
(self.denyMethods is None or len(self.denyMethods) == 0)):
|
|
242
|
-
raise NameError('No statements defined for the policy')
|
|
243
|
-
|
|
244
|
-
policy = {
|
|
245
|
-
'principalId': self.principalId,
|
|
246
|
-
'policyDocument': {
|
|
247
|
-
'Version': self.version,
|
|
248
|
-
'Statement': []
|
|
249
|
-
},
|
|
250
|
-
"context": {
|
|
251
|
-
"uniquemodversion":"string"
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Allow', self.allowMethods))
|
|
256
|
-
policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Deny', self.denyMethods))
|
|
257
|
-
|
|
258
|
-
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['authorizationToken'])
|
|
9
|
+
print("Method ARN: " + event['methodArn'])
|
|
10
|
+
|
|
11
|
+
'''
|
|
12
|
+
Validate the incoming token and produce the principal user identifier
|
|
13
|
+
associated with the token. This can be accomplished in a number of ways:
|
|
14
|
+
|
|
15
|
+
1. Call out to the OAuth provider
|
|
16
|
+
2. Decode a JWT token inline
|
|
17
|
+
3. Lookup in a self-managed DB
|
|
18
|
+
'''
|
|
19
|
+
idtoken=event['authorizationToken']
|
|
20
|
+
try:
|
|
21
|
+
tokenbodydata=json.loads(idtoken)
|
|
22
|
+
idtoken=tokenbodydata['token']
|
|
23
|
+
evaltrue=tokenbodydata['eval']
|
|
24
|
+
except:
|
|
25
|
+
evaltrue="FALSE"
|
|
26
|
+
|
|
27
|
+
print(event)
|
|
28
|
+
principalId = idtoken
|
|
29
|
+
import jwt
|
|
30
|
+
decoded = jwt.decode(idtoken, options={"verify_signature": False}) # works in PyJWT < v2.0
|
|
31
|
+
|
|
32
|
+
# Check token access with live rest api (with cognito auth activated) to ensure user isn't sending incorrect username
|
|
33
|
+
# 200 status indicates accept, 403 means unauthorized
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
#==============AIMODELSHARE Note: accept / deny languange located on line 67=======================================================
|
|
37
|
+
|
|
38
|
+
'''
|
|
39
|
+
You can send a 401 Unauthorized response to the client by failing like so:
|
|
40
|
+
|
|
41
|
+
raise Exception('Unauthorized')
|
|
42
|
+
|
|
43
|
+
If the token is valid, a policy must be generated which will allow or deny
|
|
44
|
+
access to the client. If access is denied, the client will receive a 403
|
|
45
|
+
Access Denied response. If access is allowed, API Gateway will proceed with
|
|
46
|
+
the backend integration configured on the method that was called.
|
|
47
|
+
|
|
48
|
+
This function must generate a policy that is associated with the recognized
|
|
49
|
+
principal user identifier. Depending on your use case, you might store
|
|
50
|
+
policies in a DB, or generate them on the fly.
|
|
51
|
+
|
|
52
|
+
Keep in mind, the policy is cached for 5 minutes by default (TTL is
|
|
53
|
+
configurable in the authorizer) and will apply to subsequent calls to any
|
|
54
|
+
method/resource in the RestApi made with the same token.
|
|
55
|
+
|
|
56
|
+
The example policy below denies access to all resources in the RestApi.
|
|
57
|
+
'''
|
|
58
|
+
tmp = event['methodArn'].split(':')
|
|
59
|
+
apiGatewayArnTmp = tmp[5].split('/')
|
|
60
|
+
awsAccountId = tmp[4]
|
|
61
|
+
|
|
62
|
+
policy = AuthPolicy(principalId, awsAccountId)
|
|
63
|
+
policy.restApiId = apiGatewayArnTmp[0]
|
|
64
|
+
policy.region = tmp[3]
|
|
65
|
+
policy.stage = apiGatewayArnTmp[1]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
#====================Accept/Deny auth for AIMODELSHARE begins here===========================================
|
|
69
|
+
import requests
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
headers_with_authentication = {'Content-Type': 'application/json', 'Authorization': idtoken}
|
|
73
|
+
|
|
74
|
+
response=requests.post("https://1b861v14ne.execute-api.us-east-1.amazonaws.com/dev/redisusagetrackerembedded",
|
|
75
|
+
json={"apiid": str(policy.restApiId),"eval":evaltrue}, headers=headers_with_authentication)
|
|
76
|
+
print(response.status_code)
|
|
77
|
+
uniquemodversion=str(response.text)
|
|
78
|
+
|
|
79
|
+
print(response.text)
|
|
80
|
+
if any([response.status_code!=200,response.text.find("Missing")>0,response.text.find("Monthly")>0,response.text.find("monthly")>0]):
|
|
81
|
+
policyresult="deny"
|
|
82
|
+
else:
|
|
83
|
+
policyresult="accept"
|
|
84
|
+
|
|
85
|
+
if policyresult=="deny":
|
|
86
|
+
policy.denyAllMethods()
|
|
87
|
+
else:
|
|
88
|
+
policy.allowAllMethods()
|
|
89
|
+
|
|
90
|
+
# Finally, build the policy
|
|
91
|
+
authResponse = policy.build()
|
|
92
|
+
authResponse['context']['uniquemodversion']=uniquemodversion
|
|
93
|
+
|
|
94
|
+
# new! -- add additional key-value pairs associated with the authenticated principal
|
|
95
|
+
# these are made available by APIGW like so: $context.authorizer.<key>
|
|
96
|
+
# additional context is cached
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
return authResponse
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class HttpVerb:
|
|
104
|
+
GET = 'GET'
|
|
105
|
+
POST = 'POST'
|
|
106
|
+
PUT = 'PUT'
|
|
107
|
+
PATCH = 'PATCH'
|
|
108
|
+
HEAD = 'HEAD'
|
|
109
|
+
DELETE = 'DELETE'
|
|
110
|
+
OPTIONS = 'OPTIONS'
|
|
111
|
+
ALL = '*'
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class AuthPolicy(object):
|
|
115
|
+
# The AWS account id the policy will be generated for. This is used to create the method ARNs.
|
|
116
|
+
awsAccountId = ''
|
|
117
|
+
# The principal used for the policy, this should be a unique identifier for the end user.
|
|
118
|
+
principalId = ''
|
|
119
|
+
# The policy version used for the evaluation. This should always be '2012-10-17'
|
|
120
|
+
version = '2012-10-17'
|
|
121
|
+
# The regular expression used to validate resource paths for the policy
|
|
122
|
+
pathRegex = '^[/.a-zA-Z0-9-\*]+$'
|
|
123
|
+
|
|
124
|
+
'''Internal lists of allowed and denied methods.
|
|
125
|
+
|
|
126
|
+
These are lists of objects and each object has 2 properties: A resource
|
|
127
|
+
ARN and a nullable conditions statement. The build method processes these
|
|
128
|
+
lists and generates the approriate statements for the final policy.
|
|
129
|
+
'''
|
|
130
|
+
allowMethods = []
|
|
131
|
+
denyMethods = []
|
|
132
|
+
|
|
133
|
+
# The API Gateway API id. By default this is set to '*'
|
|
134
|
+
restApiId = '*'
|
|
135
|
+
# The region where the API is deployed. By default this is set to '*'
|
|
136
|
+
region = '*'
|
|
137
|
+
# The name of the stage used in the policy. By default this is set to '*'
|
|
138
|
+
stage = '*'
|
|
139
|
+
|
|
140
|
+
def __init__(self, principal, awsAccountId):
|
|
141
|
+
self.awsAccountId = awsAccountId
|
|
142
|
+
self.principalId = principal
|
|
143
|
+
self.allowMethods = []
|
|
144
|
+
self.denyMethods = []
|
|
145
|
+
|
|
146
|
+
def _addMethod(self, effect, verb, resource, conditions):
|
|
147
|
+
'''Adds a method to the internal lists of allowed or denied methods. Each object in
|
|
148
|
+
the internal list contains a resource ARN and a condition statement. The condition
|
|
149
|
+
statement can be null.'''
|
|
150
|
+
if verb != '*' and not hasattr(HttpVerb, verb):
|
|
151
|
+
raise NameError('Invalid HTTP verb ' + verb + '. Allowed verbs in HttpVerb class')
|
|
152
|
+
resourcePattern = re.compile(self.pathRegex)
|
|
153
|
+
if not resourcePattern.match(resource):
|
|
154
|
+
raise NameError('Invalid resource path: ' + resource + '. Path should match ' + self.pathRegex)
|
|
155
|
+
|
|
156
|
+
if resource[:1] == '/':
|
|
157
|
+
resource = resource[1:]
|
|
158
|
+
|
|
159
|
+
resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)
|
|
160
|
+
|
|
161
|
+
if effect.lower() == 'allow':
|
|
162
|
+
self.allowMethods.append({
|
|
163
|
+
'resourceArn': resourceArn,
|
|
164
|
+
'conditions': conditions
|
|
165
|
+
})
|
|
166
|
+
elif effect.lower() == 'deny':
|
|
167
|
+
self.denyMethods.append({
|
|
168
|
+
'resourceArn': resourceArn,
|
|
169
|
+
'conditions': conditions
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
def _getEmptyStatement(self, effect):
|
|
173
|
+
'''Returns an empty statement object prepopulated with the correct action and the
|
|
174
|
+
desired effect.'''
|
|
175
|
+
statement = {
|
|
176
|
+
'Action': 'execute-api:Invoke',
|
|
177
|
+
'Effect': effect[:1].upper() + effect[1:].lower(),
|
|
178
|
+
'Resource': []
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return statement
|
|
182
|
+
|
|
183
|
+
def _getStatementForEffect(self, effect, methods):
|
|
184
|
+
'''This function loops over an array of objects containing a resourceArn and
|
|
185
|
+
conditions statement and generates the array of statements for the policy.'''
|
|
186
|
+
statements = []
|
|
187
|
+
|
|
188
|
+
if len(methods) > 0:
|
|
189
|
+
statement = self._getEmptyStatement(effect)
|
|
190
|
+
|
|
191
|
+
for curMethod in methods:
|
|
192
|
+
if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
|
|
193
|
+
statement['Resource'].append(curMethod['resourceArn'])
|
|
194
|
+
else:
|
|
195
|
+
conditionalStatement = self._getEmptyStatement(effect)
|
|
196
|
+
conditionalStatement['Resource'].append(curMethod['resourceArn'])
|
|
197
|
+
conditionalStatement['Condition'] = curMethod['conditions']
|
|
198
|
+
statements.append(conditionalStatement)
|
|
199
|
+
|
|
200
|
+
if statement['Resource']:
|
|
201
|
+
statements.append(statement)
|
|
202
|
+
|
|
203
|
+
return statements
|
|
204
|
+
|
|
205
|
+
def allowAllMethods(self):
|
|
206
|
+
'''Adds a '*' allow to the policy to authorize access to all methods of an API'''
|
|
207
|
+
self._addMethod('Allow', HttpVerb.ALL, '*', [])
|
|
208
|
+
|
|
209
|
+
def denyAllMethods(self):
|
|
210
|
+
'''Adds a '*' allow to the policy to deny access to all methods of an API'''
|
|
211
|
+
self._addMethod('Deny', HttpVerb.ALL, '*', [])
|
|
212
|
+
|
|
213
|
+
def allowMethod(self, verb, resource):
|
|
214
|
+
'''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
|
|
215
|
+
methods for the policy'''
|
|
216
|
+
self._addMethod('Allow', verb, resource, [])
|
|
217
|
+
|
|
218
|
+
def denyMethod(self, verb, resource):
|
|
219
|
+
'''Adds an API Gateway method (Http verb + Resource path) to the list of denied
|
|
220
|
+
methods for the policy'''
|
|
221
|
+
self._addMethod('Deny', verb, resource, [])
|
|
222
|
+
|
|
223
|
+
def allowMethodWithConditions(self, verb, resource, conditions):
|
|
224
|
+
'''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
|
|
225
|
+
methods and includes a condition for the policy statement. More on AWS policy
|
|
226
|
+
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
|
|
227
|
+
self._addMethod('Allow', verb, resource, conditions)
|
|
228
|
+
|
|
229
|
+
def denyMethodWithConditions(self, verb, resource, conditions):
|
|
230
|
+
'''Adds an API Gateway method (Http verb + Resource path) to the list of denied
|
|
231
|
+
methods and includes a condition for the policy statement. More on AWS policy
|
|
232
|
+
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
|
|
233
|
+
self._addMethod('Deny', verb, resource, conditions)
|
|
234
|
+
|
|
235
|
+
def build(self):
|
|
236
|
+
'''Generates the policy document based on the internal lists of allowed and denied
|
|
237
|
+
conditions. This will generate a policy with two main statements for the effect:
|
|
238
|
+
one statement for Allow and one statement for Deny.
|
|
239
|
+
Methods that includes conditions will have their own statement in the policy.'''
|
|
240
|
+
if ((self.allowMethods is None or len(self.allowMethods) == 0) and
|
|
241
|
+
(self.denyMethods is None or len(self.denyMethods) == 0)):
|
|
242
|
+
raise NameError('No statements defined for the policy')
|
|
243
|
+
|
|
244
|
+
policy = {
|
|
245
|
+
'principalId': self.principalId,
|
|
246
|
+
'policyDocument': {
|
|
247
|
+
'Version': self.version,
|
|
248
|
+
'Statement': []
|
|
249
|
+
},
|
|
250
|
+
"context": {
|
|
251
|
+
"uniquemodversion":"string"
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Allow', self.allowMethods))
|
|
256
|
+
policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Deny', self.denyMethods))
|
|
257
|
+
|
|
258
|
+
return policy
|
|
@@ -827,7 +827,7 @@ def get_leaderboard(task_type="$task_type", verbose=3, columns=None):
|
|
|
827
827
|
newleaderboard = pd.read_csv("/tmp/"+"model_eval_data_mastertable_v"+str(i)+".csv", sep="\t")
|
|
828
828
|
newleaderboard.drop(newleaderboard.filter(regex="Unname"),axis=1, inplace=True)
|
|
829
829
|
|
|
830
|
-
leaderboard=
|
|
830
|
+
leaderboard=leaderboard.append(newleaderboard).drop_duplicates()
|
|
831
831
|
|
|
832
832
|
leaderboard.drop(leaderboard.filter(regex="Unname"),axis=1, inplace=True)
|
|
833
833
|
#save new leaderboard here
|