2020-08-12 00:36:09 +00:00
|
|
|
import logging
|
2022-04-14 12:33:53 +00:00
|
|
|
import re
|
|
|
|
import typing as t
|
|
|
|
import orjson
|
2022-04-11 05:23:55 +00:00
|
|
|
import bleach
|
|
|
|
import tornado.web
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-05-05 00:32:09 +00:00
|
|
|
from app.classes.models.crafty_permissions import EnumPermissionsCrafty
|
2022-03-08 04:40:44 +00:00
|
|
|
from app.classes.models.users import ApiKeys
|
2022-05-05 00:32:09 +00:00
|
|
|
from app.classes.shared.helpers import Helpers
|
|
|
|
from app.classes.shared.main_controller import Controller
|
|
|
|
from app.classes.shared.translation import Translation
|
2022-07-16 08:49:48 +00:00
|
|
|
from app.classes.models.management import DatabaseShortcuts
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-03-08 04:40:44 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-04-14 12:33:53 +00:00
|
|
|
bearer_pattern = re.compile(r"^Bearer ", flags=re.IGNORECASE)
|
|
|
|
|
2022-04-11 10:08:36 +00:00
|
|
|
|
2020-08-12 00:36:09 +00:00
|
|
|
class BaseHandler(tornado.web.RequestHandler):
|
2022-06-08 19:42:25 +00:00
|
|
|
nobleach = {bool, type(None)}
|
|
|
|
redactables = ("pass", "api")
|
|
|
|
|
|
|
|
helper: Helpers
|
|
|
|
controller: Controller
|
|
|
|
translator: Translation
|
|
|
|
|
|
|
|
# noinspection PyAttributeOutsideInit
|
|
|
|
def initialize(
|
|
|
|
self, helper=None, controller=None, tasks_manager=None, translator=None
|
|
|
|
):
|
|
|
|
self.helper = helper
|
|
|
|
self.controller = controller
|
|
|
|
self.tasks_manager = tasks_manager
|
|
|
|
self.translator = translator
|
|
|
|
|
2022-04-14 12:33:53 +00:00
|
|
|
def set_default_headers(self) -> None:
|
|
|
|
"""
|
|
|
|
Fix CORS
|
|
|
|
"""
|
|
|
|
self.set_header("Access-Control-Allow-Origin", "*")
|
|
|
|
self.set_header(
|
|
|
|
"Access-Control-Allow-Headers",
|
|
|
|
"Content-Type, x-requested-with, Authorization",
|
|
|
|
)
|
|
|
|
self.set_header(
|
|
|
|
"Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS"
|
|
|
|
)
|
|
|
|
|
|
|
|
def options(self, *_, **__):
|
|
|
|
"""
|
|
|
|
Fix CORS
|
|
|
|
"""
|
|
|
|
# no body
|
|
|
|
self.set_status(204)
|
|
|
|
self.finish()
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
def get_remote_ip(self):
|
2022-03-23 02:50:12 +00:00
|
|
|
remote_ip = (
|
|
|
|
self.request.headers.get("X-Real-IP")
|
|
|
|
or self.request.headers.get("X-Forwarded-For")
|
|
|
|
or self.request.remote_ip
|
|
|
|
)
|
2020-08-12 00:36:09 +00:00
|
|
|
return remote_ip
|
|
|
|
|
2022-04-14 12:33:53 +00:00
|
|
|
current_user: t.Tuple[t.Optional[ApiKeys], t.Dict[str, t.Any], t.Dict[str, t.Any]]
|
2022-04-14 15:48:46 +00:00
|
|
|
"""
|
|
|
|
A variable that contains the current user's data. Please see
|
|
|
|
Please only use this with routes using the `@tornado.web.authenticated` decorator.
|
|
|
|
"""
|
2022-03-23 02:50:12 +00:00
|
|
|
|
|
|
|
def get_current_user(
|
|
|
|
self,
|
2022-04-14 15:48:46 +00:00
|
|
|
) -> t.Optional[
|
|
|
|
t.Tuple[t.Optional[ApiKeys], t.Dict[str, t.Any], t.Dict[str, t.Any]]
|
|
|
|
]:
|
|
|
|
"""
|
|
|
|
Get the token's API key, the token's payload and user data.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
t.Optional[ApiKeys]: The API key of the token.
|
|
|
|
t.Dict[str, t.Any]: The token's payload.
|
|
|
|
t.Dict[str, t.Any]: The user's data from the database.
|
|
|
|
"""
|
2022-04-11 05:23:55 +00:00
|
|
|
return self.controller.authentication.check(self.get_cookie("token"))
|
2021-03-22 04:02:18 +00:00
|
|
|
|
2021-04-04 17:48:02 +00:00
|
|
|
def autobleach(self, name, text):
|
|
|
|
for r in self.redactables:
|
|
|
|
if r in name:
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.debug(f"Auto-bleaching {name}: [**REDACTED**]")
|
2021-04-04 18:22:52 +00:00
|
|
|
break
|
2022-06-14 12:40:57 +00:00
|
|
|
logger.debug(f"Auto-bleaching {name}: {text}")
|
2021-04-03 18:18:43 +00:00
|
|
|
if type(text) in self.nobleach:
|
2021-04-04 17:48:02 +00:00
|
|
|
logger.debug("Auto-bleaching - bypass type")
|
2021-03-22 04:02:18 +00:00
|
|
|
return text
|
2022-06-14 12:40:57 +00:00
|
|
|
return bleach.clean(text)
|
2021-03-22 04:02:18 +00:00
|
|
|
|
|
|
|
def get_argument(
|
2022-03-23 02:50:12 +00:00
|
|
|
self,
|
|
|
|
name: str,
|
2022-04-14 12:33:53 +00:00
|
|
|
default: t.Union[
|
2022-03-23 02:50:12 +00:00
|
|
|
None, str, tornado.web._ArgDefaultMarker
|
|
|
|
] = tornado.web._ARG_DEFAULT,
|
|
|
|
strip: bool = True,
|
2022-04-14 12:33:53 +00:00
|
|
|
) -> t.Optional[str]:
|
2021-03-22 04:02:18 +00:00
|
|
|
arg = self._get_argument(name, default, self.request.arguments, strip)
|
2022-09-07 19:56:18 +00:00
|
|
|
bleached = self.autobleach(name, arg)
|
|
|
|
if "&" in str(bleached):
|
|
|
|
bleached = bleached.replace("&", "&")
|
|
|
|
return bleached
|
2021-03-22 04:02:18 +00:00
|
|
|
|
2022-04-14 12:33:53 +00:00
|
|
|
def get_arguments(self, name: str, strip: bool = True) -> t.List[str]:
|
2022-03-08 03:12:56 +00:00
|
|
|
if not isinstance(strip, bool):
|
|
|
|
raise AssertionError
|
2021-03-22 04:02:18 +00:00
|
|
|
args = self._get_arguments(name, self.request.arguments, strip)
|
|
|
|
args_ret = []
|
|
|
|
for arg in args:
|
2021-04-04 17:48:02 +00:00
|
|
|
args_ret += self.autobleach(name, arg)
|
2021-03-22 04:02:18 +00:00
|
|
|
return args_ret
|
2022-04-14 12:33:53 +00:00
|
|
|
|
|
|
|
def access_denied(self, user: t.Optional[str], reason: t.Optional[str]):
|
|
|
|
ip = self.get_remote_ip()
|
|
|
|
route = self.request.path
|
|
|
|
if user is not None:
|
|
|
|
user_data = f"User {user} from IP {ip}"
|
|
|
|
else:
|
|
|
|
user_data = f"An unknown user from IP {ip}"
|
|
|
|
if reason:
|
|
|
|
ending = f"to the API route {route} because {reason}"
|
|
|
|
else:
|
|
|
|
ending = f"to the API route {route}"
|
|
|
|
logger.info(f"{user_data} was denied access {ending}")
|
|
|
|
self.finish_json(
|
|
|
|
403,
|
|
|
|
{
|
|
|
|
"status": "error",
|
|
|
|
"error": "ACCESS_DENIED",
|
|
|
|
"info": "You were denied access to the requested resource",
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
def _auth_get_api_token(self) -> t.Optional[str]:
|
2022-04-14 15:48:46 +00:00
|
|
|
"""Get an API token from the request
|
|
|
|
|
|
|
|
The API token is searched in the following order:
|
|
|
|
1. The `token` query parameter
|
|
|
|
2. The `Authorization` header
|
|
|
|
3. The `token` cookie
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
t.Optional[str]: The API token or None if no token was found.
|
|
|
|
"""
|
2022-04-14 12:33:53 +00:00
|
|
|
logger.debug("Searching for specified token")
|
2022-04-14 15:48:46 +00:00
|
|
|
api_token = self.get_query_argument("token", None)
|
2022-04-14 12:33:53 +00:00
|
|
|
if api_token is None and self.request.headers.get("Authorization"):
|
|
|
|
api_token = bearer_pattern.sub(
|
|
|
|
"", self.request.headers.get("Authorization")
|
|
|
|
)
|
|
|
|
elif api_token is None:
|
|
|
|
api_token = self.get_cookie("token")
|
|
|
|
return api_token
|
|
|
|
|
|
|
|
def authenticate_user(
|
|
|
|
self,
|
|
|
|
) -> t.Optional[
|
|
|
|
t.Tuple[
|
|
|
|
t.List,
|
2022-05-05 00:32:09 +00:00
|
|
|
t.List[EnumPermissionsCrafty],
|
2022-04-14 12:33:53 +00:00
|
|
|
t.List[str],
|
|
|
|
bool,
|
|
|
|
t.Dict[str, t.Any],
|
|
|
|
]
|
|
|
|
]:
|
|
|
|
try:
|
|
|
|
api_key, _token_data, user = self.controller.authentication.check_err(
|
|
|
|
self._auth_get_api_token()
|
|
|
|
)
|
|
|
|
|
|
|
|
superuser = user["superuser"]
|
|
|
|
if api_key is not None:
|
|
|
|
superuser = superuser and api_key.superuser
|
|
|
|
|
|
|
|
exec_user_role = set()
|
|
|
|
if superuser:
|
2022-07-18 18:57:04 +00:00
|
|
|
authorized_servers = self.controller.servers.get_all_defined_servers()
|
2022-04-14 12:33:53 +00:00
|
|
|
exec_user_role.add("Super User")
|
|
|
|
exec_user_crafty_permissions = (
|
|
|
|
self.controller.crafty_perms.list_defined_crafty_permissions()
|
|
|
|
)
|
|
|
|
|
|
|
|
else:
|
|
|
|
if api_key is not None:
|
|
|
|
exec_user_crafty_permissions = (
|
|
|
|
self.controller.crafty_perms.get_api_key_permissions_list(
|
|
|
|
api_key
|
|
|
|
)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
exec_user_crafty_permissions = (
|
|
|
|
self.controller.crafty_perms.get_crafty_permissions_list(
|
|
|
|
user["user_id"]
|
|
|
|
)
|
|
|
|
)
|
|
|
|
logger.debug(user["roles"])
|
|
|
|
for r in user["roles"]:
|
|
|
|
role = self.controller.roles.get_role(r)
|
|
|
|
exec_user_role.add(role["role_name"])
|
|
|
|
authorized_servers = self.controller.servers.get_authorized_servers(
|
|
|
|
user["user_id"] # TODO: API key authorized servers?
|
|
|
|
)
|
2022-07-18 18:57:04 +00:00
|
|
|
authorized_servers = [
|
|
|
|
DatabaseShortcuts.get_data_obj(x.server_object)
|
|
|
|
for x in authorized_servers
|
|
|
|
]
|
2022-04-14 12:33:53 +00:00
|
|
|
|
|
|
|
logger.debug("Checking results")
|
|
|
|
if user:
|
|
|
|
return (
|
2022-07-18 18:57:04 +00:00
|
|
|
authorized_servers,
|
2022-04-14 12:33:53 +00:00
|
|
|
exec_user_crafty_permissions,
|
|
|
|
exec_user_role,
|
|
|
|
superuser,
|
|
|
|
user,
|
|
|
|
)
|
2022-06-14 12:40:57 +00:00
|
|
|
logging.debug("Auth unsuccessful")
|
|
|
|
self.access_denied(None, "the user provided an invalid token")
|
|
|
|
return None
|
2022-04-14 12:33:53 +00:00
|
|
|
except Exception as auth_exception:
|
|
|
|
logger.debug(
|
|
|
|
"An error occured while authenticating an API user:",
|
|
|
|
exc_info=auth_exception,
|
|
|
|
)
|
|
|
|
self.finish_json(
|
|
|
|
403,
|
|
|
|
{
|
|
|
|
"status": "error",
|
|
|
|
"error": "ACCESS_DENIED",
|
|
|
|
"info": "An error occured while authenticating the user",
|
|
|
|
},
|
|
|
|
)
|
|
|
|
return None
|
|
|
|
|
|
|
|
def finish_json(self, status: int, data: t.Dict[str, t.Any]):
|
|
|
|
self.set_status(status)
|
|
|
|
self.set_header("Content-Type", "application/json")
|
2022-05-23 21:54:06 +00:00
|
|
|
self.finish(orjson.dumps(data))
|