-
Notifications
You must be signed in to change notification settings - Fork 606
/
Copy pathbase_handler.py
434 lines (359 loc) · 13.7 KB
/
base_handler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import base64
import binascii
import concurrent
import json
import logging
import tornado.web
from tabpy.tabpy_server.app.SettingsParameters import SettingsParameters
from tabpy.tabpy_server.handlers.util import hash_password
import uuid
STAGING_THREAD = concurrent.futures.ThreadPoolExecutor(max_workers=3)
class ContextLoggerWrapper:
"""
This class appends request context to logged messages.
"""
@staticmethod
def _generate_call_id():
return str(uuid.uuid4())
def __init__(self, request: tornado.httputil.HTTPServerRequest):
self.call_id = self._generate_call_id()
self.set_request(request)
self.tabpy_username = None
self.log_request_context = False
self.request_context_logged = False
def set_request(self, request: tornado.httputil.HTTPServerRequest):
"""
Set HTTP(S) request for logger. Headers will be used to
append request data as client information, Tableau user name, etc.
"""
self.remote_ip = request.remote_ip
self.method = request.method
self.url = request.full_url()
if "TabPy-Client" in request.headers:
self.client = request.headers["TabPy-Client"]
else:
self.client = None
if "TabPy-User" in request.headers:
self.tableau_username = request.headers["TabPy-User"]
else:
self.tableau_username = None
def set_tabpy_username(self, tabpy_username: str):
self.tabpy_username = tabpy_username
def enable_context_logging(self, enable: bool):
"""
Enable/disable request context information logging.
Parameters
----------
enable: bool
If True request context information will be logged and
every log entry for a request handler will have call ID
with it.
"""
self.log_request_context = enable
def _log_context_info(self):
if not self.log_request_context:
return
context = f"Call ID: {self.call_id}"
if self.remote_ip is not None:
context += f", Caller: {self.remote_ip}"
if self.method is not None:
context += f", Method: {self.method}"
if self.url is not None:
context += f", URL: {self.url}"
if self.client is not None:
context += f", Client: {self.client}"
if self.tableau_username is not None:
context += f", Tableau user: {self.tableau_username}"
if self.tabpy_username is not None:
context += f", TabPy user: {self.tabpy_username}"
logging.getLogger(__name__).log(logging.INFO, context)
self.request_context_logged = True
def log(self, level: int, msg: str):
"""
Log message with or without call ID. If call context is logged and
call ID added to any log entry is specified by if context logging
is enabled (see CallContext.enable_context_logging for more details).
Parameters
----------
level: int
Log level: logging.CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET.
msg: str
Message format string.
args
Same as args in Logger.debug().
kwargs
Same as kwargs in Logger.debug().
"""
extended_msg = msg
if self.log_request_context:
if not self.request_context_logged:
self._log_context_info()
extended_msg += f", <<call ID: {self.call_id}>>"
logging.getLogger(__name__).log(level, extended_msg)
class BaseHandler(tornado.web.RequestHandler):
def initialize(self, app):
self.tabpy_state = app.tabpy_state
# set content type to application/json
self.set_header("Content-Type", "application/json")
self.protocol = self.settings[SettingsParameters.TransferProtocol]
self.port = self.settings[SettingsParameters.Port]
self.python_service = app.python_service
self.credentials = app.credentials
self.username = None
self.password = None
self.eval_timeout = self.settings[SettingsParameters.EvaluateTimeout]
self.logger = ContextLoggerWrapper(self.request)
self.logger.enable_context_logging(
app.settings[SettingsParameters.LogRequestContext]
)
self.logger.log(logging.DEBUG, "Checking if need to handle authentication")
self.not_authorized = not self.handle_authentication("v1")
def error_out(self, code, log_message, info=None):
self.set_status(code)
self.write(json.dumps({"message": log_message, "info": info or {}}))
# We want to duplicate error message in console for
# loggers are misconfigured or causing the failure
# themselves
print(info)
self.logger.log(
logging.ERROR,
'Responding with status={}, message="{}", info="{}"'.format(
code, log_message, info
),
)
self.finish()
def options(self):
# add CORS headers if TabPy has a cors_origin specified
self._add_CORS_header()
self.write({})
def _add_CORS_header(self):
"""
Add CORS header if the TabPy has attribute _cors_origin
and _cors_origin is not an empty string.
"""
origin = self.tabpy_state.get_access_control_allow_origin()
if len(origin) > 0:
self.set_header("Access-Control-Allow-Origin", origin)
self.logger.log(logging.DEBUG, f"Access-Control-Allow-Origin:{origin}")
headers = self.tabpy_state.get_access_control_allow_headers()
if len(headers) > 0:
self.set_header("Access-Control-Allow-Headers", headers)
self.logger.log(logging.DEBUG, f"Access-Control-Allow-Headers:{headers}")
methods = self.tabpy_state.get_access_control_allow_methods()
if len(methods) > 0:
self.set_header("Access-Control-Allow-Methods", methods)
self.logger.log(logging.DEBUG, f"Access-Control-Allow-Methods:{methods}")
def _get_auth_method(self, api_version) -> (bool, str):
"""
Finds authentication method if provided.
Parameters
----------
api_version : str
API version for authentication.
Returns
-------
bool
True if known authentication method is found.
False otherwise.
str
Name of authentication method used by client.
If empty no authentication required.
(True, '') as result of this function means authentication
is not needed.
"""
if api_version not in self.settings[SettingsParameters.ApiVersions]:
self.logger.log(logging.CRITICAL, f'Unknown API version "{api_version}"')
return False, ""
version_settings = self.settings[SettingsParameters.ApiVersions][api_version]
if "features" not in version_settings:
self.logger.log(
logging.INFO, f'No features configured for API "{api_version}"'
)
return True, ""
features = version_settings["features"]
if (
"authentication" not in features
or not features["authentication"]["required"]
):
self.logger.log(
logging.INFO,
"Authentication is not a required feature for API " f'"{api_version}"',
)
return True, ""
auth_feature = features["authentication"]
if "methods" not in auth_feature:
self.logger.log(
logging.INFO,
"Authentication method is not configured for API " f'"{api_version}"',
)
methods = auth_feature["methods"]
if "basic-auth" in auth_feature["methods"]:
return True, "basic-auth"
# Add new methods here...
# No known methods were found
self.logger.log(
logging.CRITICAL,
f'Unknown authentication method(s) "{methods}" are configured '
f'for API "{api_version}"',
)
return False, ""
def _get_basic_auth_credentials(self) -> bool:
"""
Find credentials for basic access authentication method. Credentials if
found stored in Credentials.username and Credentials.password.
Returns
-------
bool
True if valid credentials were found.
False otherwise.
"""
self.logger.log(
logging.DEBUG, "Checking request headers for authentication data"
)
if "Authorization" not in self.request.headers:
self.logger.log(logging.INFO, "Authorization header not found")
return False
auth_header = self.request.headers["Authorization"]
auth_header_list = auth_header.split(" ")
if len(auth_header_list) != 2 or auth_header_list[0] != "Basic":
self.logger.log(
logging.ERROR, f'Unknown authentication method "{auth_header}"'
)
return False
try:
cred = base64.b64decode(auth_header_list[1]).decode("utf-8")
except (binascii.Error, UnicodeDecodeError) as ex:
self.logger.log(logging.CRITICAL, f"Cannot decode credentials: {str(ex)}")
return False
login_pwd = cred.split(":")
if len(login_pwd) != 2:
self.logger.log(logging.ERROR, "Invalid string in encoded credentials")
return False
self.username = login_pwd[0]
self.logger.set_tabpy_username(self.username)
self.password = login_pwd[1]
return True
def _get_credentials(self, method) -> bool:
"""
Find credentials for specified authentication method. Credentials if
found stored in self.username and self.password.
Parameters
----------
method: str
Authentication method name.
Returns
-------
bool
True if valid credentials were found.
False otherwise.
"""
if method == "basic-auth":
return self._get_basic_auth_credentials()
# Add new methods here...
# No known methods were found
self.logger.log(
logging.CRITICAL,
f'Unknown authentication method(s) "{method}" are configured '
f'for API "{api_version}"',
)
return False
def _validate_basic_auth_credentials(self) -> bool:
"""
Validates username:pwd if they are the same as
stored credentials.
Returns
-------
bool
True if credentials has key login and
credentials[login] equal SHA3(pwd), False
otherwise.
"""
login = self.username.lower()
self.logger.log(
logging.DEBUG, f'Validating credentials for user name "{login}"'
)
if login not in self.credentials:
self.logger.log(logging.ERROR, f'User name "{self.username}" not found')
return False
hashed_pwd = hash_password(login, self.password)
if self.credentials[login].lower() != hashed_pwd.lower():
self.logger.log(
logging.ERROR, f'Wrong password for user name "{self.username}"'
)
return False
return True
def _validate_credentials(self, method) -> bool:
"""
Validates credentials according to specified methods if they
are what expected.
Parameters
----------
method: str
Authentication method name.
Returns
-------
bool
True if credentials are valid.
False otherwise.
"""
if method == "basic-auth":
return self._validate_basic_auth_credentials()
# Add new methods here...
# No known methods were found
self.logger.log(
logging.CRITICAL,
f'Unknown authentication method(s) "{method}" are configured '
f'for API "{api_version}"',
)
return False
def handle_authentication(self, api_version) -> bool:
"""
If authentication feature is configured checks provided
credentials.
Parameters
----------
api_version : str
API version for authentication.
Returns
-------
bool
True if authentication is not required.
True if authentication is required and valid
credentials provided.
False otherwise.
"""
self.logger.log(logging.DEBUG, "Handling authentication")
found, method = self._get_auth_method(api_version)
if not found:
return False
if method == "":
# Do not validate credentials
return True
if not self._get_credentials(method):
return False
return self._validate_credentials(method)
def should_fail_with_not_authorized(self):
"""
Checks if authentication is required:
- if it is not returns false, None
- if it is required validates provided credentials
Returns
-------
bool
False if authentication is not required or is
required and validation for credentials passes.
True if validation for credentials failed.
"""
return self.not_authorized
def fail_with_not_authorized(self):
"""
Prepares server 401 response.
"""
self.logger.log(logging.ERROR, "Failing with 401 for unauthorized request")
self.set_status(401)
self.set_header("WWW-Authenticate", f'Basic realm="{self.tabpy_state.name}"')
self.error_out(
401,
info="Unauthorized request.",
log_message="Invalid credentials provided.",
)