aimodelshare 0.1.22__py3-none-any.whl → 0.1.24__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/main/authorization.txt +275 -275
- aimodelshare/main/eval_lambda.txt +2 -2
- aimodelshare/pyspark/authorization.txt +258 -258
- aimodelshare/pyspark/eval_lambda.txt +2 -2
- {aimodelshare-0.1.22.dist-info → aimodelshare-0.1.24.dist-info}/METADATA +1 -1
- {aimodelshare-0.1.22.dist-info → aimodelshare-0.1.24.dist-info}/RECORD +9 -9
- {aimodelshare-0.1.22.dist-info → aimodelshare-0.1.24.dist-info}/LICENSE +0 -0
- {aimodelshare-0.1.22.dist-info → aimodelshare-0.1.24.dist-info}/WHEEL +0 -0
- {aimodelshare-0.1.22.dist-info → aimodelshare-0.1.24.dist-info}/top_level.txt +0 -0
|
@@ -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
|
|
@@ -1007,7 +1007,7 @@ def get_leaderboard(task_type="classification", verbose=3, columns=None, private
|
|
|
1007
1007
|
newleaderboard = pd.read_csv("/tmp/"+mastertable_path.split("/")[-1]+"_v"+str(i)+".csv", sep="\t")
|
|
1008
1008
|
newleaderboard.drop(newleaderboard.filter(regex="Unname"),axis=1, inplace=True)
|
|
1009
1009
|
|
|
1010
|
-
leaderboard=
|
|
1010
|
+
leaderboard=pd.concat([leaderboard, newleaderboard]).drop_duplicates()
|
|
1011
1011
|
|
|
1012
1012
|
leaderboard.drop(leaderboard.filter(regex="Unname"),axis=1, inplace=True)
|
|
1013
1013
|
#save new leaderboard here
|
|
@@ -1061,7 +1061,7 @@ def get_leaderboard(task_type="classification", verbose=3, columns=None, private
|
|
|
1061
1061
|
col = col[1:]
|
|
1062
1062
|
ascending = True
|
|
1063
1063
|
|
|
1064
|
-
|
|
1064
|
+
pd.concat([ranks,leaderboard[col].rank(method="dense", ascending=ascending)])
|
|
1065
1065
|
|
|
1066
1066
|
ranks = np.mean(ranks, axis=0)
|
|
1067
1067
|
order = np.argsort(ranks)
|
|
@@ -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=pd.concat([leaderboard, newleaderboard]).drop_duplicates()
|
|
831
831
|
|
|
832
832
|
leaderboard.drop(leaderboard.filter(regex="Unname"),axis=1, inplace=True)
|
|
833
833
|
#save new leaderboard here
|
|
@@ -881,7 +881,7 @@ def get_leaderboard(task_type="$task_type", verbose=3, columns=None):
|
|
|
881
881
|
col = col[1:]
|
|
882
882
|
ascending = True
|
|
883
883
|
|
|
884
|
-
|
|
884
|
+
pd.concat([ranks,leaderboard[col].rank(method="dense", ascending=ascending)])
|
|
885
885
|
|
|
886
886
|
ranks = np.mean(ranks, axis=0)
|
|
887
887
|
order = np.argsort(ranks)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: aimodelshare
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.24
|
|
4
4
|
Summary: Deploy locally saved machine learning models to a live rest API and web-dashboard. Share it with the world via modelshare.org
|
|
5
5
|
Home-page: https://www.modelshare.org
|
|
6
6
|
Author: Michael Parrott
|
|
@@ -105,9 +105,9 @@ aimodelshare/main/6.txt,sha256=DqSveJ3d5FhQ4HZQ7hzEcVLURO5dK1uBtgWIfEPaxj4,3518
|
|
|
105
105
|
aimodelshare/main/7.txt,sha256=a8D5As2ZffV5kkwR0wUJ8V_YidYkyesWEtES12o57Qo,4377
|
|
106
106
|
aimodelshare/main/8.txt,sha256=MfcEQe9Gv6RSmWL3kd7oYkRkdDdkN4bPxEG43QVs7ms,4513
|
|
107
107
|
aimodelshare/main/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
108
|
-
aimodelshare/main/authorization.txt,sha256=
|
|
108
|
+
aimodelshare/main/authorization.txt,sha256=yDzbXZa_NuEBFAJi03cFkKfMl5ZDfAjlonDcPJwSTJM,10667
|
|
109
109
|
aimodelshare/main/eval_classification.txt,sha256=gCBU71rbXRlkBwefVN3WhwVJX9fXh6bwOCa7ofLMdnA,3081
|
|
110
|
-
aimodelshare/main/eval_lambda.txt,sha256=
|
|
110
|
+
aimodelshare/main/eval_lambda.txt,sha256=3FDHufrGUHWWNIidlHrkjKFGer-uFUtMstH1sGRslYk,60325
|
|
111
111
|
aimodelshare/main/eval_regression.txt,sha256=iQeE9mbOkg-BDF9TnoQmglo86jBJitJQCvaf1eELzrs,3111
|
|
112
112
|
aimodelshare/main/lambda_function.txt,sha256=-XkuD2YUOWNryNT7rBPjlts588UAeE949TUqeVGCRlQ,150
|
|
113
113
|
aimodelshare/main/nst.txt,sha256=8kTsR18kDEcaQbv6091XDq1tRiqqFxdqfCteslR_udk,4941
|
|
@@ -123,9 +123,9 @@ aimodelshare/pyspark/6.txt,sha256=j8t-akOZeEL6DX6xChvMU25V5_1z7OwXYlb50XtO2m0,59
|
|
|
123
123
|
aimodelshare/pyspark/7.txt,sha256=88ZJq-b31Zczv6dl0wbbSuEraBq5TJe2SFaxIu16-L0,6819
|
|
124
124
|
aimodelshare/pyspark/8.txt,sha256=es6rcjUvBNUuSQOw1DZT6fDn3C0oHMGuQgXaC-cB5FA,6906
|
|
125
125
|
aimodelshare/pyspark/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
126
|
-
aimodelshare/pyspark/authorization.txt,sha256=
|
|
126
|
+
aimodelshare/pyspark/authorization.txt,sha256=F-fLsMR922MeNRvECTG1Fbl7X1x73i1diAU0JTvgxDw,10331
|
|
127
127
|
aimodelshare/pyspark/eval_classification.txt,sha256=gCBU71rbXRlkBwefVN3WhwVJX9fXh6bwOCa7ofLMdnA,3081
|
|
128
|
-
aimodelshare/pyspark/eval_lambda.txt,sha256=
|
|
128
|
+
aimodelshare/pyspark/eval_lambda.txt,sha256=5oDL695spSMOq7SJcnwa-cYUzefs6dCfAil4AvlcFG8,51485
|
|
129
129
|
aimodelshare/pyspark/eval_regression.txt,sha256=iQeE9mbOkg-BDF9TnoQmglo86jBJitJQCvaf1eELzrs,3111
|
|
130
130
|
aimodelshare/pyspark/lambda_function.txt,sha256=-XkuD2YUOWNryNT7rBPjlts588UAeE949TUqeVGCRlQ,150
|
|
131
131
|
aimodelshare/pyspark/nst.txt,sha256=ZJ8xM80xisQf2hGMUWliKcbeE7HH214Kzd_Ie1wu-q0,7110
|
|
@@ -143,8 +143,8 @@ aimodelshare/sam/template.txt,sha256=JKSvEOZNaaLalHSx7r9psJg_6LLCb0XLAYi1-jYPu3M
|
|
|
143
143
|
tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
144
144
|
tests/test_aimsonnx.py,sha256=-GOF1_qXGQaMxHyqK0GPg7dD1meE-S7CZea4pLmBDTk,3906
|
|
145
145
|
tests/test_playground.py,sha256=vdFWPRrZNQ2poiBOoN3l7HsXB5yc3p3rrrclNYJHnaw,24574
|
|
146
|
-
aimodelshare-0.1.
|
|
147
|
-
aimodelshare-0.1.
|
|
148
|
-
aimodelshare-0.1.
|
|
149
|
-
aimodelshare-0.1.
|
|
150
|
-
aimodelshare-0.1.
|
|
146
|
+
aimodelshare-0.1.24.dist-info/LICENSE,sha256=JXBYLriXYgTloZs-9CJPZY76dqkuDT5df_HghMnljx8,1134
|
|
147
|
+
aimodelshare-0.1.24.dist-info/METADATA,sha256=o9MdHJLjyyjXjwfA52lqetbpiEaDAwN3QGsATMQwQIs,3304
|
|
148
|
+
aimodelshare-0.1.24.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
|
149
|
+
aimodelshare-0.1.24.dist-info/top_level.txt,sha256=2KJgeHQ0BmZuilB75J203i7W4vri6CON2kdbwk9BNpU,19
|
|
150
|
+
aimodelshare-0.1.24.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|