| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | |
| Eduardo Sousa | d795f87 | 2019-02-05 16:05:53 +0000 | [diff] [blame] | 3 | # Copyright 2018 Whitestack, LLC |
| 4 | # Copyright 2018 Telefonica S.A. |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 5 | # |
| Eduardo Sousa | d795f87 | 2019-02-05 16:05:53 +0000 | [diff] [blame] | 6 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 7 | # not use this file except in compliance with the License. You may obtain |
| 8 | # a copy of the License at |
| 9 | # |
| 10 | # http://www.apache.org/licenses/LICENSE-2.0 |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 11 | # |
| 12 | # Unless required by applicable law or agreed to in writing, software |
| Eduardo Sousa | d795f87 | 2019-02-05 16:05:53 +0000 | [diff] [blame] | 13 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 14 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 15 | # License for the specific language governing permissions and limitations |
| 16 | # under the License. |
| 17 | # |
| 18 | # For those usages not covered by the Apache License, Version 2.0 please |
| 19 | # contact: esousa@whitestack.com or alfonso.tiernosepulveda@telefonica.com |
| 20 | ## |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 21 | |
| 22 | |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 23 | """ |
| 24 | Authenticator is responsible for authenticating the users, |
| 25 | create the tokens unscoped and scoped, retrieve the role |
| 26 | list inside the projects that they are inserted |
| 27 | """ |
| 28 | |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 29 | __author__ = "Eduardo Sousa <esousa@whitestack.com>; Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>" |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 30 | __date__ = "$27-jul-2018 23:59:59$" |
| 31 | |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 32 | import cherrypy |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 33 | import logging |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 34 | import yaml |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 35 | from base64 import standard_b64decode |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 36 | from copy import deepcopy |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 37 | |
| tierno | 38dcfeb | 2019-06-10 16:44:00 +0000 | [diff] [blame] | 38 | # from functools import reduce |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 39 | from http import HTTPStatus |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 40 | from time import time |
| Eduardo Sousa | 5c01e19 | 2019-05-08 02:35:47 +0100 | [diff] [blame] | 41 | from os import path |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 42 | |
| tierno | c23a9bb | 2020-06-24 10:54:11 +0000 | [diff] [blame] | 43 | from osm_nbi.authconn import AuthException, AuthconnException, AuthExceptionUnauthorized |
| tierno | 9c63011 | 2019-08-29 14:21:41 +0000 | [diff] [blame] | 44 | from osm_nbi.authconn_keystone import AuthconnKeystone |
| delacruzramo | ad682a5 | 2019-12-10 16:26:34 +0100 | [diff] [blame] | 45 | from osm_nbi.authconn_internal import AuthconnInternal |
| K Sai Kiran | 7ddb073 | 2020-10-30 11:14:44 +0530 | [diff] [blame] | 46 | from osm_nbi.authconn_tacacs import AuthconnTacacs |
| delacruzramo | ad682a5 | 2019-12-10 16:26:34 +0100 | [diff] [blame] | 47 | from osm_common import dbmemory, dbmongo, msglocal, msgkafka |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 48 | from osm_common.dbbase import DbException |
| delacruzramo | 029405d | 2019-09-26 10:52:56 +0200 | [diff] [blame] | 49 | from osm_nbi.validation import is_valid_uuid |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 50 | from itertools import chain |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 51 | from uuid import uuid4 |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 52 | |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 53 | |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 54 | class Authenticator: |
| 55 | """ |
| 56 | This class should hold all the mechanisms for User Authentication and |
| 57 | Authorization. Initially it should support Openstack Keystone as a |
| 58 | backend through a plugin model where more backends can be added and a |
| 59 | RBAC model to manage permissions on operations. |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 60 | This class must be threading safe |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 61 | """ |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 62 | |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 63 | periodin_db_pruning = ( |
| 64 | 60 * 30 |
| 65 | ) # for the internal backend only. every 30 minutes expired tokens will be pruned |
| 66 | token_limit = 500 # when reached, the token cache will be cleared |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 67 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 68 | def __init__(self, valid_methods, valid_query_string): |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 69 | """ |
| 70 | Authenticator initializer. Setup the initial state of the object, |
| 71 | while it waits for the config dictionary and database initialization. |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 72 | """ |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 73 | self.backend = None |
| 74 | self.config = None |
| 75 | self.db = None |
| delacruzramo | ad682a5 | 2019-12-10 16:26:34 +0100 | [diff] [blame] | 76 | self.msg = None |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 77 | self.tokens_cache = dict() |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 78 | self.next_db_prune_time = ( |
| 79 | 0 # time when next cleaning of expired tokens must be done |
| 80 | ) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 81 | self.roles_to_operations_file = None |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 82 | # self.roles_to_operations_table = None |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 83 | self.resources_to_operations_mapping = {} |
| 84 | self.operation_to_allowed_roles = {} |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 85 | self.logger = logging.getLogger("nbi.authenticator") |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 86 | self.role_permissions = [] |
| 87 | self.valid_methods = valid_methods |
| 88 | self.valid_query_string = valid_query_string |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 89 | self.system_admin_role_id = None # system_role id |
| tierno | d4a705a | 2020-06-22 10:58:26 +0000 | [diff] [blame] | 90 | self.test_project_id = None # test_project_id |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 91 | |
| 92 | def start(self, config): |
| 93 | """ |
| 94 | Method to configure the Authenticator object. This method should be called |
| 95 | after object creation. It is responsible by initializing the selected backend, |
| 96 | as well as the initialization of the database connection. |
| 97 | |
| 98 | :param config: dictionary containing the relevant parameters for this object. |
| 99 | """ |
| 100 | self.config = config |
| 101 | |
| 102 | try: |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 103 | if not self.db: |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 104 | if config["database"]["driver"] == "mongo": |
| 105 | self.db = dbmongo.DbMongo() |
| 106 | self.db.db_connect(config["database"]) |
| 107 | elif config["database"]["driver"] == "memory": |
| 108 | self.db = dbmemory.DbMemory() |
| 109 | self.db.db_connect(config["database"]) |
| 110 | else: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 111 | raise AuthException( |
| 112 | "Invalid configuration param '{}' at '[database]':'driver'".format( |
| 113 | config["database"]["driver"] |
| 114 | ) |
| 115 | ) |
| delacruzramo | ad682a5 | 2019-12-10 16:26:34 +0100 | [diff] [blame] | 116 | if not self.msg: |
| 117 | if config["message"]["driver"] == "local": |
| 118 | self.msg = msglocal.MsgLocal() |
| 119 | self.msg.connect(config["message"]) |
| 120 | elif config["message"]["driver"] == "kafka": |
| 121 | self.msg = msgkafka.MsgKafka() |
| 122 | self.msg.connect(config["message"]) |
| 123 | else: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 124 | raise AuthException( |
| 125 | "Invalid configuration param '{}' at '[message]':'driver'".format( |
| 126 | config["message"]["driver"] |
| 127 | ) |
| 128 | ) |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 129 | if not self.backend: |
| 130 | if config["authentication"]["backend"] == "keystone": |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 131 | self.backend = AuthconnKeystone( |
| 132 | self.config["authentication"], self.db, self.role_permissions |
| 133 | ) |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 134 | elif config["authentication"]["backend"] == "internal": |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 135 | self.backend = AuthconnInternal( |
| 136 | self.config["authentication"], self.db, self.role_permissions |
| 137 | ) |
| K Sai Kiran | 7ddb073 | 2020-10-30 11:14:44 +0530 | [diff] [blame] | 138 | self._internal_tokens_prune("tokens") |
| 139 | elif config["authentication"]["backend"] == "tacacs": |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 140 | self.backend = AuthconnTacacs( |
| 141 | self.config["authentication"], self.db, self.role_permissions |
| 142 | ) |
| K Sai Kiran | 7ddb073 | 2020-10-30 11:14:44 +0530 | [diff] [blame] | 143 | self._internal_tokens_prune("tokens_tacacs") |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 144 | else: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 145 | raise AuthException( |
| 146 | "Unknown authentication backend: {}".format( |
| 147 | config["authentication"]["backend"] |
| 148 | ) |
| 149 | ) |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 150 | |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 151 | if not self.roles_to_operations_file: |
| 152 | if "roles_to_operations" in config["rbac"]: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 153 | self.roles_to_operations_file = config["rbac"][ |
| 154 | "roles_to_operations" |
| 155 | ] |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 156 | else: |
| Eduardo Sousa | 5c01e19 | 2019-05-08 02:35:47 +0100 | [diff] [blame] | 157 | possible_paths = ( |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 158 | __file__[: __file__.rfind("auth.py")] |
| 159 | + "roles_to_operations.yml", |
| 160 | "./roles_to_operations.yml", |
| Eduardo Sousa | 5c01e19 | 2019-05-08 02:35:47 +0100 | [diff] [blame] | 161 | ) |
| 162 | for config_file in possible_paths: |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 163 | if path.isfile(config_file): |
| 164 | self.roles_to_operations_file = config_file |
| 165 | break |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 166 | if not self.roles_to_operations_file: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 167 | raise AuthException( |
| 168 | "Invalid permission configuration: roles_to_operations file missing" |
| 169 | ) |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 170 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 171 | # load role_permissions |
| 172 | def load_role_permissions(method_dict): |
| 173 | for k in method_dict: |
| 174 | if k == "ROLE_PERMISSION": |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 175 | for method in chain( |
| 176 | method_dict.get("METHODS", ()), method_dict.get("TODO", ()) |
| 177 | ): |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 178 | permission = method_dict["ROLE_PERMISSION"] + method.lower() |
| 179 | if permission not in self.role_permissions: |
| 180 | self.role_permissions.append(permission) |
| 181 | elif k in ("TODO", "METHODS"): |
| 182 | continue |
| tierno | 74b5358 | 2020-06-18 10:52:37 +0000 | [diff] [blame] | 183 | elif method_dict[k]: |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 184 | load_role_permissions(method_dict[k]) |
| 185 | |
| 186 | load_role_permissions(self.valid_methods) |
| 187 | for query_string in self.valid_query_string: |
| 188 | for method in ("get", "put", "patch", "post", "delete"): |
| 189 | permission = query_string.lower() + ":" + method |
| 190 | if permission not in self.role_permissions: |
| 191 | self.role_permissions.append(permission) |
| 192 | |
| tierno | d4a705a | 2020-06-22 10:58:26 +0000 | [diff] [blame] | 193 | # get ids of role system_admin and test project |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 194 | role_system_admin = self.db.get_one( |
| 195 | "roles", {"name": "system_admin"}, fail_on_empty=False |
| 196 | ) |
| tierno | d4a705a | 2020-06-22 10:58:26 +0000 | [diff] [blame] | 197 | if role_system_admin: |
| 198 | self.system_admin_role_id = role_system_admin["_id"] |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 199 | test_project_name = self.config["authentication"].get( |
| 200 | "project_not_authorized", "admin" |
| 201 | ) |
| 202 | test_project = self.db.get_one( |
| 203 | "projects", {"name": test_project_name}, fail_on_empty=False |
| 204 | ) |
| tierno | d4a705a | 2020-06-22 10:58:26 +0000 | [diff] [blame] | 205 | if test_project: |
| 206 | self.test_project_id = test_project["_id"] |
| 207 | |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 208 | except Exception as e: |
| 209 | raise AuthException(str(e)) |
| 210 | |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 211 | def stop(self): |
| 212 | try: |
| 213 | if self.db: |
| 214 | self.db.db_disconnect() |
| 215 | except DbException as e: |
| 216 | raise AuthException(str(e), http_code=e.http_code) |
| 217 | |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 218 | def create_admin_project(self): |
| 219 | """ |
| 220 | Creates a new project 'admin' into database if it doesn't exist. Useful for initialization. |
| 221 | :return: _id identity of the 'admin' project |
| 222 | """ |
| 223 | |
| 224 | # projects = self.db.get_one("projects", fail_on_empty=False, fail_on_more=False) |
| 225 | project_desc = {"name": "admin"} |
| 226 | projects = self.backend.get_project_list(project_desc) |
| 227 | if projects: |
| 228 | return projects[0]["_id"] |
| 229 | now = time() |
| 230 | project_desc["_id"] = str(uuid4()) |
| 231 | project_desc["_admin"] = {"created": now, "modified": now} |
| 232 | pid = self.backend.create_project(project_desc) |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 233 | self.logger.info( |
| 234 | "Project '{}' created at database".format(project_desc["name"]) |
| 235 | ) |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 236 | return pid |
| 237 | |
| 238 | def create_admin_user(self, project_id): |
| 239 | """ |
| 240 | Creates a new user admin/admin into database if database is empty. Useful for initialization |
| 241 | :return: _id identity of the inserted data, or None |
| 242 | """ |
| 243 | # users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False) |
| 244 | users = self.backend.get_user_list() |
| 245 | if users: |
| 246 | return None |
| 247 | # user_desc = {"username": "admin", "password": "admin", "projects": [project_id]} |
| 248 | now = time() |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 249 | user_desc = { |
| 250 | "username": "admin", |
| 251 | "password": "admin", |
| 252 | "_admin": {"created": now, "modified": now}, |
| 253 | } |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 254 | if project_id: |
| 255 | pid = project_id |
| 256 | else: |
| 257 | # proj = self.db.get_one("projects", {"name": "admin"}, fail_on_empty=False, fail_on_more=False) |
| 258 | proj = self.backend.get_project_list({"name": "admin"}) |
| 259 | pid = proj[0]["_id"] if proj else None |
| 260 | # role = self.db.get_one("roles", {"name": "system_admin"}, fail_on_empty=False, fail_on_more=False) |
| 261 | roles = self.backend.get_role_list({"name": "system_admin"}) |
| 262 | if pid and roles: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 263 | user_desc["project_role_mappings"] = [ |
| 264 | {"project": pid, "role": roles[0]["_id"]} |
| 265 | ] |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 266 | uid = self.backend.create_user(user_desc) |
| 267 | self.logger.info("User '{}' created at database".format(user_desc["username"])) |
| 268 | return uid |
| 269 | |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 270 | def init_db(self, target_version="1.0"): |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 271 | """ |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 272 | Check if the database has been initialized, with at least one user. If not, create the required tables |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 273 | and insert the predefined mappings between roles and permissions. |
| 274 | |
| 275 | :param target_version: schema version that should be present in the database. |
| 276 | :return: None if OK, exception if error or version is different. |
| 277 | """ |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 278 | |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 279 | records = self.backend.get_role_list() |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 280 | |
| tierno | c23a9bb | 2020-06-24 10:54:11 +0000 | [diff] [blame] | 281 | # Loading permissions to AUTH. At lease system_admin must be present. |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 282 | if not records or not next( |
| 283 | (r for r in records if r["name"] == "system_admin"), None |
| 284 | ): |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 285 | with open(self.roles_to_operations_file, "r") as stream: |
| delacruzramo | b19cadc | 2019-10-08 10:18:02 +0200 | [diff] [blame] | 286 | roles_to_operations_yaml = yaml.load(stream, Loader=yaml.Loader) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 287 | |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 288 | role_names = [] |
| 289 | for role_with_operations in roles_to_operations_yaml["roles"]: |
| 290 | # Verifying if role already exists. If it does, raise exception |
| 291 | if role_with_operations["name"] not in role_names: |
| 292 | role_names.append(role_with_operations["name"]) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 293 | else: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 294 | raise AuthException( |
| 295 | "Duplicated role name '{}' at file '{}''".format( |
| 296 | role_with_operations["name"], self.roles_to_operations_file |
| 297 | ) |
| 298 | ) |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 299 | |
| 300 | if not role_with_operations["permissions"]: |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 301 | continue |
| 302 | |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 303 | for permission, is_allowed in role_with_operations[ |
| 304 | "permissions" |
| 305 | ].items(): |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 306 | if not isinstance(is_allowed, bool): |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 307 | raise AuthException( |
| 308 | "Invalid value for permission '{}' at role '{}'; at file '{}'".format( |
| 309 | permission, |
| 310 | role_with_operations["name"], |
| 311 | self.roles_to_operations_file, |
| 312 | ) |
| 313 | ) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 314 | |
| tierno | c23a9bb | 2020-06-24 10:54:11 +0000 | [diff] [blame] | 315 | # TODO check permission is ok |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 316 | if permission[-1] == ":": |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 317 | raise AuthException( |
| 318 | "Invalid permission '{}' terminated in ':' for role '{}'; at file {}".format( |
| 319 | permission, |
| 320 | role_with_operations["name"], |
| 321 | self.roles_to_operations_file, |
| 322 | ) |
| 323 | ) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 324 | |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 325 | if "default" not in role_with_operations["permissions"]: |
| 326 | role_with_operations["permissions"]["default"] = False |
| 327 | if "admin" not in role_with_operations["permissions"]: |
| 328 | role_with_operations["permissions"]["admin"] = False |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 329 | |
| 330 | now = time() |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 331 | role_with_operations["_admin"] = { |
| 332 | "created": now, |
| 333 | "modified": now, |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 334 | } |
| 335 | |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 336 | # self.db.create(self.roles_to_operations_table, role_with_operations) |
| tierno | c23a9bb | 2020-06-24 10:54:11 +0000 | [diff] [blame] | 337 | try: |
| 338 | self.backend.create_role(role_with_operations) |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 339 | self.logger.info( |
| 340 | "Role '{}' created".format(role_with_operations["name"]) |
| 341 | ) |
| tierno | c23a9bb | 2020-06-24 10:54:11 +0000 | [diff] [blame] | 342 | except (AuthException, AuthconnException) as e: |
| 343 | if role_with_operations["name"] == "system_admin": |
| 344 | raise |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 345 | self.logger.error( |
| 346 | "Role '{}' cannot be created: {}".format( |
| 347 | role_with_operations["name"], e |
| 348 | ) |
| 349 | ) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 350 | |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 351 | # Create admin project&user if required |
| 352 | pid = self.create_admin_project() |
| tierno | 9ebbf85 | 2019-09-03 14:58:09 +0000 | [diff] [blame] | 353 | user_id = self.create_admin_user(pid) |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 354 | |
| tierno | 9ebbf85 | 2019-09-03 14:58:09 +0000 | [diff] [blame] | 355 | # try to assign system_admin role to user admin if not any user has this role |
| 356 | if not user_id: |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 357 | try: |
| tierno | 9ebbf85 | 2019-09-03 14:58:09 +0000 | [diff] [blame] | 358 | users = self.backend.get_user_list() |
| 359 | roles = self.backend.get_role_list({"name": "system_admin"}) |
| 360 | role_id = roles[0]["_id"] |
| 361 | user_with_system_admin = False |
| 362 | user_admin_id = None |
| 363 | for user in users: |
| 364 | if not user_admin_id: |
| 365 | user_admin_id = user["_id"] |
| 366 | if user["username"] == "admin": |
| 367 | user_admin_id = user["_id"] |
| 368 | for prm in user.get("project_role_mappings", ()): |
| 369 | if prm["role"] == role_id: |
| 370 | user_with_system_admin = True |
| 371 | break |
| 372 | if user_with_system_admin: |
| 373 | break |
| 374 | if not user_with_system_admin: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 375 | self.backend.update_user( |
| 376 | { |
| 377 | "_id": user_admin_id, |
| 378 | "add_project_role_mappings": [ |
| 379 | {"project": pid, "role": role_id} |
| 380 | ], |
| 381 | } |
| 382 | ) |
| 383 | self.logger.info( |
| 384 | "Added role system admin to user='{}' project=admin".format( |
| 385 | user_admin_id |
| 386 | ) |
| 387 | ) |
| delacruzramo | 15ec706 | 2019-12-26 10:09:04 +0000 | [diff] [blame] | 388 | except Exception as e: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 389 | self.logger.error( |
| 390 | "Error in Authorization DataBase initialization: {}: {}".format( |
| 391 | type(e).__name__, e |
| 392 | ) |
| 393 | ) |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 394 | |
| 395 | self.load_operation_to_allowed_roles() |
| 396 | |
| 397 | def load_operation_to_allowed_roles(self): |
| 398 | """ |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 399 | Fills the internal self.operation_to_allowed_roles based on database role content and self.role_permissions |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 400 | It works in a shadow copy and replace at the end to allow other threads working with the old copy |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 401 | :return: None |
| 402 | """ |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 403 | permissions = {oper: [] for oper in self.role_permissions} |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 404 | # records = self.db.get_list(self.roles_to_operations_table) |
| 405 | records = self.backend.get_role_list() |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 406 | |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 407 | ignore_fields = ["_id", "_admin", "name", "default"] |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 408 | for record in records: |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 409 | if not record.get("permissions"): |
| 410 | continue |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 411 | record_permissions = { |
| 412 | oper: record["permissions"].get("default", False) |
| 413 | for oper in self.role_permissions |
| 414 | } |
| 415 | operations_joined = [ |
| 416 | (oper, value) |
| 417 | for oper, value in record["permissions"].items() |
| 418 | if oper not in ignore_fields |
| 419 | ] |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 420 | operations_joined.sort(key=lambda x: x[0].count(":")) |
| 421 | |
| 422 | for oper in operations_joined: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 423 | match = list( |
| 424 | filter(lambda x: x.find(oper[0]) == 0, record_permissions.keys()) |
| 425 | ) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 426 | |
| 427 | for m in match: |
| 428 | record_permissions[m] = oper[1] |
| 429 | |
| 430 | allowed_operations = [k for k, v in record_permissions.items() if v is True] |
| 431 | |
| 432 | for allowed_op in allowed_operations: |
| Eduardo Sousa | 5c01e19 | 2019-05-08 02:35:47 +0100 | [diff] [blame] | 433 | permissions[allowed_op].append(record["name"]) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 434 | |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 435 | self.operation_to_allowed_roles = permissions |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 436 | |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 437 | def authorize( |
| 438 | self, role_permission=None, query_string_operations=None, item_id=None |
| 439 | ): |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 440 | token = None |
| 441 | user_passwd64 = None |
| 442 | try: |
| 443 | # 1. Get token Authorization bearer |
| 444 | auth = cherrypy.request.headers.get("Authorization") |
| 445 | if auth: |
| 446 | auth_list = auth.split(" ") |
| 447 | if auth_list[0].lower() == "bearer": |
| 448 | token = auth_list[-1] |
| 449 | elif auth_list[0].lower() == "basic": |
| 450 | user_passwd64 = auth_list[-1] |
| 451 | if not token: |
| 452 | if cherrypy.session.get("Authorization"): |
| 453 | # 2. Try using session before request a new token. If not, basic authentication will generate |
| 454 | token = cherrypy.session.get("Authorization") |
| 455 | if token == "logout": |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 456 | token = None # force Unauthorized response to insert user password again |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 457 | elif user_passwd64 and cherrypy.request.config.get( |
| 458 | "auth.allow_basic_authentication" |
| 459 | ): |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 460 | # 3. Get new token from user password |
| 461 | user = None |
| 462 | passwd = None |
| 463 | try: |
| 464 | user_passwd = standard_b64decode(user_passwd64).decode() |
| 465 | user, _, passwd = user_passwd.partition(":") |
| 466 | except Exception: |
| 467 | pass |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 468 | outdata = self.new_token( |
| 469 | None, {"username": user, "password": passwd} |
| 470 | ) |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 471 | token = outdata["_id"] |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 472 | cherrypy.session["Authorization"] = token |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 473 | |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 474 | if not token: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 475 | raise AuthException( |
| 476 | "Needed a token or Authorization http header", |
| 477 | http_code=HTTPStatus.UNAUTHORIZED, |
| 478 | ) |
| delacruzramo | ad682a5 | 2019-12-10 16:26:34 +0100 | [diff] [blame] | 479 | |
| 480 | # try to get from cache first |
| 481 | now = time() |
| 482 | token_info = self.tokens_cache.get(token) |
| 483 | if token_info and token_info["expires"] < now: |
| 484 | # delete token. MUST be done with care, as another thread maybe already delete it. Do not use del |
| 485 | self.tokens_cache.pop(token, None) |
| 486 | token_info = None |
| 487 | |
| 488 | # get from database if not in cache |
| 489 | if not token_info: |
| 490 | token_info = self.backend.validate_token(token) |
| 491 | # Clear cache if token limit reached |
| 492 | if len(self.tokens_cache) > self.token_limit: |
| 493 | self.tokens_cache.clear() |
| 494 | self.tokens_cache[token] = token_info |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 495 | # TODO add to token info remote host, port |
| 496 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 497 | if role_permission: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 498 | RBAC_auth = self.check_permissions( |
| 499 | token_info, |
| 500 | cherrypy.request.method, |
| 501 | role_permission, |
| 502 | query_string_operations, |
| 503 | item_id, |
| 504 | ) |
| sousaedu | 60bf895 | 2021-07-08 17:17:23 +0200 | [diff] [blame] | 505 | self.logger.info("RBAC_auth: {}".format(RBAC_auth)) |
| delacruzramo | 029405d | 2019-09-26 10:52:56 +0200 | [diff] [blame] | 506 | token_info["allow_show_user_project_role"] = RBAC_auth |
| 507 | |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 508 | return token_info |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 509 | except AuthException as e: |
| tierno | c844536 | 2019-06-14 12:07:15 +0000 | [diff] [blame] | 510 | if not isinstance(e, AuthExceptionUnauthorized): |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 511 | if cherrypy.session.get("Authorization"): |
| 512 | del cherrypy.session["Authorization"] |
| 513 | cherrypy.response.headers[ |
| 514 | "WWW-Authenticate" |
| 515 | ] = 'Bearer realm="{}"'.format(e) |
| tierno | d4a705a | 2020-06-22 10:58:26 +0000 | [diff] [blame] | 516 | if self.config["authentication"].get("user_not_authorized"): |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 517 | return { |
| 518 | "id": "testing-token", |
| 519 | "_id": "testing-token", |
| 520 | "project_id": self.test_project_id, |
| 521 | "username": self.config["authentication"]["user_not_authorized"], |
| 522 | "roles": [self.system_admin_role_id], |
| 523 | "admin": True, |
| 524 | "allow_show_user_project_role": True, |
| 525 | } |
| tierno | c844536 | 2019-06-14 12:07:15 +0000 | [diff] [blame] | 526 | raise |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 527 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 528 | def new_token(self, token_info, indata, remote): |
| 529 | new_token_info = self.backend.authenticate( |
| tierno | 6486f74 | 2020-02-13 16:30:14 +0000 | [diff] [blame] | 530 | credentials=indata, |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 531 | token_info=token_info, |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 532 | ) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 533 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 534 | new_token_info["remote_port"] = remote.port |
| 535 | if not new_token_info.get("expires"): |
| 536 | new_token_info["expires"] = time() + 3600 |
| 537 | if not new_token_info.get("admin"): |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 538 | new_token_info["admin"] = ( |
| 539 | True if new_token_info.get("project_name") == "admin" else False |
| 540 | ) |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 541 | # TODO put admin in RBAC |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 542 | |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 543 | if remote.name: |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 544 | new_token_info["remote_host"] = remote.name |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 545 | elif remote.ip: |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 546 | new_token_info["remote_host"] = remote.ip |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 547 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 548 | # TODO call self._internal_tokens_prune(now) ? |
| 549 | return deepcopy(new_token_info) |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 550 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 551 | def get_token_list(self, token_info): |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 552 | if self.config["authentication"]["backend"] == "internal": |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 553 | return self._internal_get_token_list(token_info) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 554 | else: |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 555 | # TODO: check if this can be avoided. Backend may provide enough information |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 556 | return [ |
| 557 | deepcopy(token) |
| 558 | for token in self.tokens_cache.values() |
| 559 | if token["username"] == token_info["username"] |
| 560 | ] |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 561 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 562 | def get_token(self, token_info, token): |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 563 | if self.config["authentication"]["backend"] == "internal": |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 564 | return self._internal_get_token(token_info, token) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 565 | else: |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 566 | # TODO: check if this can be avoided. Backend may provide enough information |
| 567 | token_value = self.tokens_cache.get(token) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 568 | if not token_value: |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 569 | raise AuthException("token not found", http_code=HTTPStatus.NOT_FOUND) |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 570 | if ( |
| 571 | token_value["username"] != token_info["username"] |
| 572 | and not token_info["admin"] |
| 573 | ): |
| 574 | raise AuthException( |
| 575 | "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED |
| 576 | ) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 577 | return token_value |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 578 | |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 579 | def del_token(self, token): |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 580 | try: |
| 581 | self.backend.revoke_token(token) |
| delacruzramo | ad682a5 | 2019-12-10 16:26:34 +0100 | [diff] [blame] | 582 | # self.tokens_cache.pop(token, None) |
| 583 | self.remove_token_from_cache(token) |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 584 | return "token '{}' deleted".format(token) |
| 585 | except KeyError: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 586 | raise AuthException( |
| 587 | "Token '{}' not found".format(token), http_code=HTTPStatus.NOT_FOUND |
| 588 | ) |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 589 | |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 590 | def check_permissions( |
| 591 | self, |
| 592 | token_info, |
| 593 | method, |
| 594 | role_permission=None, |
| 595 | query_string_operations=None, |
| 596 | item_id=None, |
| 597 | ): |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 598 | """ |
| 599 | Checks that operation has permissions to be done, base on the assigned roles to this user project |
| 600 | :param token_info: Dictionary that contains "roles" with a list of assigned roles. |
| 601 | This method fills the token_info["admin"] with True or False based on assigned tokens, if any allows admin |
| 602 | This will be used among others to hide or not the _admin content of topics |
| 603 | :param method: GET,PUT, POST, ... |
| 604 | :param role_permission: role permission name of the operation required |
| 605 | :param query_string_operations: list of possible admin query strings provided by user. It is checked that the |
| 606 | assigned role allows this query string for this method |
| delacruzramo | 029405d | 2019-09-26 10:52:56 +0200 | [diff] [blame] | 607 | :param item_id: item identifier if included in the URL, None otherwise |
| 608 | :return: True if access granted by permission rules, False if access granted by default rules (Bug 853) |
| 609 | :raises: AuthExceptionUnauthorized if access denied |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 610 | """ |
| sousaedu | 490d019 | 2021-05-05 12:48:16 +0200 | [diff] [blame] | 611 | self.load_operation_to_allowed_roles() |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 612 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 613 | roles_required = self.operation_to_allowed_roles[role_permission] |
| 614 | roles_allowed = [role["name"] for role in token_info["roles"]] |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 615 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 616 | # fills token_info["admin"] if some roles allows it |
| 617 | token_info["admin"] = False |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 618 | for role in roles_allowed: |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 619 | if role in self.operation_to_allowed_roles["admin:" + method.lower()]: |
| 620 | token_info["admin"] = True |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 621 | break |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 622 | |
| 623 | if "anonymous" in roles_required: |
| delacruzramo | 029405d | 2019-09-26 10:52:56 +0200 | [diff] [blame] | 624 | return True |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 625 | operation_allowed = False |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 626 | for role in roles_allowed: |
| 627 | if role in roles_required: |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 628 | operation_allowed = True |
| 629 | # if query_string operations, check if this role allows it |
| 630 | if not query_string_operations: |
| delacruzramo | 029405d | 2019-09-26 10:52:56 +0200 | [diff] [blame] | 631 | return True |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 632 | for query_string_operation in query_string_operations: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 633 | if ( |
| 634 | role |
| 635 | not in self.operation_to_allowed_roles[query_string_operation] |
| 636 | ): |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 637 | break |
| 638 | else: |
| delacruzramo | 029405d | 2019-09-26 10:52:56 +0200 | [diff] [blame] | 639 | return True |
| 640 | |
| 641 | # Bug 853 - Final Solution |
| 642 | # User/Project/Role whole listings are filtered elsewhere |
| 643 | # uid, pid, rid = ("user_id", "project_id", "id") if is_valid_uuid(id) else ("username", "project_name", "name") |
| 644 | uid = "user_id" if is_valid_uuid(item_id) else "username" |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 645 | if ( |
| 646 | role_permission |
| 647 | in [ |
| 648 | "projects:get", |
| 649 | "projects:id:get", |
| 650 | "roles:get", |
| 651 | "roles:id:get", |
| 652 | "users:get", |
| 653 | ] |
| 654 | ) or (role_permission == "users:id:get" and item_id == token_info[uid]): |
| delacruzramo | 029405d | 2019-09-26 10:52:56 +0200 | [diff] [blame] | 655 | # or (role_permission == "projects:id:get" and item_id == token_info[pid]) \ |
| 656 | # or (role_permission == "roles:id:get" and item_id in [role[rid] for role in token_info["roles"]]): |
| 657 | return False |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 658 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 659 | if not operation_allowed: |
| 660 | raise AuthExceptionUnauthorized("Access denied: lack of permissions.") |
| 661 | else: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 662 | raise AuthExceptionUnauthorized( |
| 663 | "Access denied: You have not permissions to use these admin query string" |
| 664 | ) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 665 | |
| Eduardo Sousa | 5c01e19 | 2019-05-08 02:35:47 +0100 | [diff] [blame] | 666 | def get_user_list(self): |
| 667 | return self.backend.get_user_list() |
| 668 | |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 669 | def _normalize_url(self, url, method): |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 670 | # DEPRECATED !!! |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 671 | # Removing query strings |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 672 | normalized_url = url if "?" not in url else url[: url.find("?")] |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 673 | normalized_url_splitted = normalized_url.split("/") |
| 674 | parameters = {} |
| 675 | |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 676 | filtered_keys = [ |
| 677 | key |
| 678 | for key in self.resources_to_operations_mapping.keys() |
| 679 | if method in key.split()[0] |
| 680 | ] |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 681 | |
| 682 | for idx, path_part in enumerate(normalized_url_splitted): |
| 683 | tmp_keys = [] |
| 684 | for tmp_key in filtered_keys: |
| 685 | splitted = tmp_key.split()[1].split("/") |
| Eduardo Sousa | cc02e9a | 2019-03-20 17:32:36 +0000 | [diff] [blame] | 686 | if idx >= len(splitted): |
| 687 | continue |
| 688 | elif "<" in splitted[idx] and ">" in splitted[idx]: |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 689 | if splitted[idx] == "<artifactPath>": |
| 690 | tmp_keys.append(tmp_key) |
| 691 | continue |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 692 | elif idx == len(normalized_url_splitted) - 1 and len( |
| 693 | normalized_url_splitted |
| 694 | ) != len(splitted): |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 695 | continue |
| 696 | else: |
| 697 | tmp_keys.append(tmp_key) |
| 698 | elif splitted[idx] == path_part: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 699 | if idx == len(normalized_url_splitted) - 1 and len( |
| 700 | normalized_url_splitted |
| 701 | ) != len(splitted): |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 702 | continue |
| 703 | else: |
| 704 | tmp_keys.append(tmp_key) |
| 705 | filtered_keys = tmp_keys |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 706 | if ( |
| 707 | len(filtered_keys) == 1 |
| 708 | and filtered_keys[0].split("/")[-1] == "<artifactPath>" |
| 709 | ): |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 710 | break |
| 711 | |
| 712 | if len(filtered_keys) == 0: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 713 | raise AuthException( |
| 714 | "Cannot make an authorization decision. URL not found. URL: {0}".format( |
| 715 | url |
| 716 | ) |
| 717 | ) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 718 | elif len(filtered_keys) > 1: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 719 | raise AuthException( |
| 720 | "Cannot make an authorization decision. Multiple URLs found. URL: {0}".format( |
| 721 | url |
| 722 | ) |
| 723 | ) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 724 | |
| 725 | filtered_key = filtered_keys[0] |
| 726 | |
| 727 | for idx, path_part in enumerate(filtered_key.split()[1].split("/")): |
| 728 | if "<" in path_part and ">" in path_part: |
| 729 | if path_part == "<artifactPath>": |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 730 | parameters[path_part[1:-1]] = "/".join( |
| 731 | normalized_url_splitted[idx:] |
| 732 | ) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 733 | else: |
| 734 | parameters[path_part[1:-1]] = normalized_url_splitted[idx] |
| 735 | |
| 736 | return filtered_key, parameters |
| 737 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 738 | def _internal_get_token_list(self, token_info): |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 739 | now = time() |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 740 | token_list = self.db.get_list( |
| 741 | "tokens", {"username": token_info["username"], "expires.gt": now} |
| 742 | ) |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 743 | return token_list |
| 744 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 745 | def _internal_get_token(self, token_info, token_id): |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 746 | token_value = self.db.get_one("tokens", {"_id": token_id}, fail_on_empty=False) |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 747 | if not token_value: |
| 748 | raise AuthException("token not found", http_code=HTTPStatus.NOT_FOUND) |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 749 | if ( |
| 750 | token_value["username"] != token_info["username"] |
| 751 | and not token_info["admin"] |
| 752 | ): |
| 753 | raise AuthException( |
| 754 | "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED |
| 755 | ) |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 756 | return token_value |
| 757 | |
| K Sai Kiran | 7ddb073 | 2020-10-30 11:14:44 +0530 | [diff] [blame] | 758 | def _internal_tokens_prune(self, token_collection, now=None): |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 759 | now = now or time() |
| 760 | if not self.next_db_prune_time or self.next_db_prune_time >= now: |
| K Sai Kiran | 7ddb073 | 2020-10-30 11:14:44 +0530 | [diff] [blame] | 761 | self.db.del_list(token_collection, {"expires.lt": now}) |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 762 | self.next_db_prune_time = self.periodin_db_pruning + now |
| delacruzramo | ad682a5 | 2019-12-10 16:26:34 +0100 | [diff] [blame] | 763 | # self.tokens_cache.clear() # not required any more |
| 764 | |
| 765 | def remove_token_from_cache(self, token=None): |
| 766 | if token: |
| 767 | self.tokens_cache.pop(token, None) |
| 768 | else: |
| 769 | self.tokens_cache.clear() |
| 770 | self.msg.write("admin", "revoke_token", {"_id": token} if token else None) |