-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapproov-protected-server.py
More file actions
247 lines (176 loc) · 7.44 KB
/
Copy pathapproov-protected-server.py
File metadata and controls
247 lines (176 loc) · 7.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# System packages
import logging
from random import choice
from base64 import b64decode, b64encode
from os import getenv
from hashlib import sha256
# Third part packages
import jwt
from dotenv import load_dotenv, find_dotenv
from flask import Flask, request, abort, make_response, jsonify
api = Flask(__name__)
api.config["JSON_SORT_KEYS"] = False
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
BAD_REQUEST_RESPONSE = {}
load_dotenv(find_dotenv(), override=True)
HTTP_PORT = int(getenv('HTTP_PORT', 8002))
APPROOV_BASE64_SECRET = getenv('APPROOV_BASE64_SECRET')
APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN = True
_approov_enabled = getenv('APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN', 'True').lower()
if _approov_enabled == 'false':
APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN = False
APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN_BINDING = True
_abort_on_invalid_token_binding = getenv('APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN_BINDING', 'True').lower()
if _abort_on_invalid_token_binding == 'false':
APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN_BINDING = False
APPROOV_LOGGING_ENABLED = True
_approov_logging_enabled = getenv('APPROOV_LOGGING_ENABLED', 'True').lower()
if _approov_logging_enabled == 'false':
APPROOV_LOGGING_ENABLED = False
def _getHeader(key, default_value = None):
return request.headers.get(key, default_value)
def _isEmpty(value):
return value is None or value == ""
def _getAuthorizationToken():
authorization_token = _getHeader("Authorization")
if _isEmpty(authorization_token):
log.error('AUTHORIZATION TOKEN EMPTY OR MISSING')
abort(make_response(jsonify(BAD_REQUEST_RESPONSE), 400))
return authorization_token
def _buildHelloResponse():
return jsonify({
"text": "Hello, World!",
})
def _buildShapeResponse():
shape = choice([
"Circle",
"Triangle",
"Square",
"Rectangle",
])
return jsonify({
"shape": shape,
})
def _buildFormResponse():
form = choice([
'Sphere',
'Cone',
'Cube',
'Box',
])
return jsonify({
"form": form,
})
def _logApproov(message):
if APPROOV_LOGGING_ENABLED is True:
log.info(message)
def _decodeApproovToken(approov_token):
try:
# Decode the approov token, allowing only the HS256 algorithm and using
# the approov base64 encoded SECRET
approov_token_decoded = jwt.decode(approov_token, b64decode(APPROOV_BASE64_SECRET), algorithms=['HS256'])
return approov_token_decoded
except jwt.InvalidSignatureError as e:
_logApproov('APPROOV JWT TOKEN INVALID SIGNATURE: %s' % e)
return None
except jwt.ExpiredSignatureError as e:
_logApproov('APPROOV JWT TOKEN EXPIRED: %s' % e)
return None
except jwt.InvalidTokenError as e:
_logApproov('APPROOV JWT TOKEN INVALID: %s' % e)
return None
def _getApproovToken():
message = 'REQUEST WITH APPROOV TOKEN HEADER EMPTY OR MISSING'
approov_token = _getHeader('approov-token')
if _isEmpty(approov_token):
if APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN is True:
_logApproov('REJECTED ' + message)
abort(make_response(jsonify(BAD_REQUEST_RESPONSE), 400))
_logApproov(message)
return None
approov_token_decoded = _decodeApproovToken(approov_token)
if _isEmpty(approov_token_decoded):
return None
return approov_token_decoded
def _handleApproovProtectedRequest(approov_token_decoded):
message = 'REQUEST WITH VALID APPROOV TOKEN'
if not approov_token_decoded:
message = 'REQUEST WITH INVALID APPROOV TOKEN'
if APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN is True and not approov_token_decoded:
_logApproov('REJECTED ' + message)
abort(make_response(jsonify(BAD_REQUEST_RESPONSE), 401))
_logApproov('ACCEPTED ' + message)
def _checkApproovTokenBinding(approov_token_decoded, token_binding_header):
if _isEmpty(approov_token_decoded):
return False
if 'pay' in approov_token_decoded:
# We need to hash and base64 encode the token binding header, because that's how it was included in the Approov
# token on the mobile app.
token_binding_header_hash = sha256(token_binding_header.encode('utf-8')).digest()
token_binding_header_encoded = b64encode(token_binding_header_hash).decode('utf-8')
return approov_token_decoded['pay'] == token_binding_header_encoded
return False
def _handlesApproovTokenBindingVerification(approov_token_decoded, token_binding_header):
if not 'pay' in approov_token_decoded:
message = 'REQUEST WITH APPROOV TOKEN MISSING THE CLAIM TO VERIFY THE TOKEN BINDING'
if APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN_BINDING is True:
_logApproov('REJECTED ' + message)
abort(make_response(jsonify(BAD_REQUEST_RESPONSE), 401))
else:
_logApproov('ACCEPTED ' + message)
return
message = 'REQUEST WITH VALID TOKEN BINDING IN THE APPROOV TOKEN'
valid_token_binding = _checkApproovTokenBinding(approov_token_decoded, token_binding_header)
if not valid_token_binding:
message = 'REQUEST WITH INVALID TOKEN BINDING IN THE APPROOV TOKEN'
if not valid_token_binding and APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN_BINDING is True:
_logApproov('REJECTED ' + message)
abort(make_response(jsonify(BAD_REQUEST_RESPONSE), 401))
_logApproov('ACCEPTED ' + message)
@api.route("/")
def homePage():
file = open('index.html', 'r')
content = file.read()
file.close()
return content
@api.route("/v1/hello")
def hello():
return _buildHelloResponse()
@api.route("/v1/shapes")
def shapes():
return _buildShapeResponse()
@api.route("/v1/forms")
def forms():
# How to handle and validate the authorization token is out of scope for this tutorial.
authorization_token = _getAuthorizationToken()
return _buildFormResponse()
@api.route("/v2/hello")
def helloV2():
return _buildHelloResponse()
### APPROOV PROTECTED ENDPOINTS ###
@api.route("/v2/shapes")
def shapesV2():
# Will get the Approov JWT token from the header, decode it and on success
# will return it, otherwise None is returned.
approov_token_decoded = _getApproovToken()
# If APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN is set to True it will abort the request
# when the decoded approov token is empty.
_handleApproovProtectedRequest(approov_token_decoded)
return _buildShapeResponse()
@api.route("/v2/forms")
def formsV2():
# Will get the Approov JWT token from the header, decode it and on success
# will return it, otherwise None is returned.
approov_token_decoded = _getApproovToken()
# If APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN is set to True it will abort the request
# when the decoded approov token is empty.
_handleApproovProtectedRequest(approov_token_decoded)
# How to handle and validate the authorization token is out of scope for this tutorial, but
# you should only validate it after you have decoded the Approov token.
authorization_token = _getAuthorizationToken()
# Checks if the Approov token binding is valid and aborts the request when the environment variable
# APPROOV_ABORT_REQUEST_ON_INVALID_TOKEN_BINDING is set to True.
_handlesApproovTokenBindingVerification(approov_token_decoded, authorization_token)
# Now you are free to handle and validate your Authorization token as you usually do.
return _buildFormResponse()