| 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 |
| tierno | 38dcfeb | 2019-06-10 16:44:00 +0000 | [diff] [blame] | 37 | # from functools import reduce |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 38 | from http import HTTPStatus |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 39 | from time import time |
| Eduardo Sousa | 5c01e19 | 2019-05-08 02:35:47 +0100 | [diff] [blame] | 40 | from os import path |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 41 | |
| tierno | 9c63011 | 2019-08-29 14:21:41 +0000 | [diff] [blame] | 42 | from osm_nbi.authconn import AuthException, AuthExceptionUnauthorized |
| 43 | from osm_nbi.authconn_keystone import AuthconnKeystone |
| 44 | from osm_nbi.authconn_internal import AuthconnInternal # Comment out for testing&debugging, uncomment when ready |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 45 | from osm_common import dbmongo |
| 46 | from osm_common import dbmemory |
| 47 | from osm_common.dbbase import DbException |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 48 | from itertools import chain |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 49 | |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 50 | from uuid import uuid4 |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 51 | |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 52 | |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 53 | class Authenticator: |
| 54 | """ |
| 55 | This class should hold all the mechanisms for User Authentication and |
| 56 | Authorization. Initially it should support Openstack Keystone as a |
| 57 | backend through a plugin model where more backends can be added and a |
| 58 | RBAC model to manage permissions on operations. |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 59 | This class must be threading safe |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 60 | """ |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 61 | |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 62 | periodin_db_pruning = 60 * 30 # for the internal backend only. every 30 minutes expired tokens will be pruned |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 63 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 64 | def __init__(self, valid_methods, valid_query_string): |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 65 | """ |
| 66 | Authenticator initializer. Setup the initial state of the object, |
| 67 | while it waits for the config dictionary and database initialization. |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 68 | """ |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 69 | self.backend = None |
| 70 | self.config = None |
| 71 | self.db = None |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 72 | self.tokens_cache = dict() |
| 73 | self.next_db_prune_time = 0 # time when next cleaning of expired tokens must be done |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 74 | self.roles_to_operations_file = None |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 75 | # self.roles_to_operations_table = None |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 76 | self.resources_to_operations_mapping = {} |
| 77 | self.operation_to_allowed_roles = {} |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 78 | self.logger = logging.getLogger("nbi.authenticator") |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 79 | self.role_permissions = [] |
| 80 | self.valid_methods = valid_methods |
| 81 | self.valid_query_string = valid_query_string |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 82 | |
| 83 | def start(self, config): |
| 84 | """ |
| 85 | Method to configure the Authenticator object. This method should be called |
| 86 | after object creation. It is responsible by initializing the selected backend, |
| 87 | as well as the initialization of the database connection. |
| 88 | |
| 89 | :param config: dictionary containing the relevant parameters for this object. |
| 90 | """ |
| 91 | self.config = config |
| 92 | |
| 93 | try: |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 94 | if not self.db: |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 95 | if config["database"]["driver"] == "mongo": |
| 96 | self.db = dbmongo.DbMongo() |
| 97 | self.db.db_connect(config["database"]) |
| 98 | elif config["database"]["driver"] == "memory": |
| 99 | self.db = dbmemory.DbMemory() |
| 100 | self.db.db_connect(config["database"]) |
| 101 | else: |
| 102 | raise AuthException("Invalid configuration param '{}' at '[database]':'driver'" |
| 103 | .format(config["database"]["driver"])) |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 104 | if not self.backend: |
| 105 | if config["authentication"]["backend"] == "keystone": |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 106 | self.backend = AuthconnKeystone(self.config["authentication"], self.db, self.tokens_cache) |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 107 | elif config["authentication"]["backend"] == "internal": |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 108 | self.backend = AuthconnInternal(self.config["authentication"], self.db, self.tokens_cache) |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 109 | self._internal_tokens_prune() |
| 110 | else: |
| 111 | raise AuthException("Unknown authentication backend: {}" |
| 112 | .format(config["authentication"]["backend"])) |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 113 | |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 114 | if not self.roles_to_operations_file: |
| 115 | if "roles_to_operations" in config["rbac"]: |
| 116 | self.roles_to_operations_file = config["rbac"]["roles_to_operations"] |
| 117 | else: |
| Eduardo Sousa | 5c01e19 | 2019-05-08 02:35:47 +0100 | [diff] [blame] | 118 | possible_paths = ( |
| 119 | __file__[:__file__.rfind("auth.py")] + "roles_to_operations.yml", |
| 120 | "./roles_to_operations.yml" |
| 121 | ) |
| 122 | for config_file in possible_paths: |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 123 | if path.isfile(config_file): |
| 124 | self.roles_to_operations_file = config_file |
| 125 | break |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 126 | if not self.roles_to_operations_file: |
| 127 | raise AuthException("Invalid permission configuration: roles_to_operations file missing") |
| 128 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 129 | # load role_permissions |
| 130 | def load_role_permissions(method_dict): |
| 131 | for k in method_dict: |
| 132 | if k == "ROLE_PERMISSION": |
| 133 | for method in chain(method_dict.get("METHODS", ()), method_dict.get("TODO", ())): |
| 134 | permission = method_dict["ROLE_PERMISSION"] + method.lower() |
| 135 | if permission not in self.role_permissions: |
| 136 | self.role_permissions.append(permission) |
| 137 | elif k in ("TODO", "METHODS"): |
| 138 | continue |
| 139 | else: |
| 140 | load_role_permissions(method_dict[k]) |
| 141 | |
| 142 | load_role_permissions(self.valid_methods) |
| 143 | for query_string in self.valid_query_string: |
| 144 | for method in ("get", "put", "patch", "post", "delete"): |
| 145 | permission = query_string.lower() + ":" + method |
| 146 | if permission not in self.role_permissions: |
| 147 | self.role_permissions.append(permission) |
| 148 | |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 149 | except Exception as e: |
| 150 | raise AuthException(str(e)) |
| 151 | |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 152 | def stop(self): |
| 153 | try: |
| 154 | if self.db: |
| 155 | self.db.db_disconnect() |
| 156 | except DbException as e: |
| 157 | raise AuthException(str(e), http_code=e.http_code) |
| 158 | |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 159 | def create_admin_project(self): |
| 160 | """ |
| 161 | Creates a new project 'admin' into database if it doesn't exist. Useful for initialization. |
| 162 | :return: _id identity of the 'admin' project |
| 163 | """ |
| 164 | |
| 165 | # projects = self.db.get_one("projects", fail_on_empty=False, fail_on_more=False) |
| 166 | project_desc = {"name": "admin"} |
| 167 | projects = self.backend.get_project_list(project_desc) |
| 168 | if projects: |
| 169 | return projects[0]["_id"] |
| 170 | now = time() |
| 171 | project_desc["_id"] = str(uuid4()) |
| 172 | project_desc["_admin"] = {"created": now, "modified": now} |
| 173 | pid = self.backend.create_project(project_desc) |
| 174 | self.logger.info("Project '{}' created at database".format(project_desc["name"])) |
| 175 | return pid |
| 176 | |
| 177 | def create_admin_user(self, project_id): |
| 178 | """ |
| 179 | Creates a new user admin/admin into database if database is empty. Useful for initialization |
| 180 | :return: _id identity of the inserted data, or None |
| 181 | """ |
| 182 | # users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False) |
| 183 | users = self.backend.get_user_list() |
| 184 | if users: |
| 185 | return None |
| 186 | # user_desc = {"username": "admin", "password": "admin", "projects": [project_id]} |
| 187 | now = time() |
| 188 | user_desc = {"username": "admin", "password": "admin", "_admin": {"created": now, "modified": now}} |
| 189 | if project_id: |
| 190 | pid = project_id |
| 191 | else: |
| 192 | # proj = self.db.get_one("projects", {"name": "admin"}, fail_on_empty=False, fail_on_more=False) |
| 193 | proj = self.backend.get_project_list({"name": "admin"}) |
| 194 | pid = proj[0]["_id"] if proj else None |
| 195 | # role = self.db.get_one("roles", {"name": "system_admin"}, fail_on_empty=False, fail_on_more=False) |
| 196 | roles = self.backend.get_role_list({"name": "system_admin"}) |
| 197 | if pid and roles: |
| 198 | user_desc["project_role_mappings"] = [{"project": pid, "role": roles[0]["_id"]}] |
| 199 | uid = self.backend.create_user(user_desc) |
| 200 | self.logger.info("User '{}' created at database".format(user_desc["username"])) |
| 201 | return uid |
| 202 | |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 203 | def init_db(self, target_version='1.0'): |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 204 | """ |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 205 | 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] | 206 | and insert the predefined mappings between roles and permissions. |
| 207 | |
| 208 | :param target_version: schema version that should be present in the database. |
| 209 | :return: None if OK, exception if error or version is different. |
| 210 | """ |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 211 | |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 212 | records = self.backend.get_role_list() |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 213 | |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 214 | # Loading permissions to MongoDB if there is not any permission. |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 215 | if not records or (len(records) == 1 and records[0]["name"] == "admin"): |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 216 | with open(self.roles_to_operations_file, "r") as stream: |
| 217 | roles_to_operations_yaml = yaml.load(stream) |
| 218 | |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 219 | role_names = [] |
| 220 | for role_with_operations in roles_to_operations_yaml["roles"]: |
| 221 | # Verifying if role already exists. If it does, raise exception |
| 222 | if role_with_operations["name"] not in role_names: |
| 223 | role_names.append(role_with_operations["name"]) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 224 | else: |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 225 | raise AuthException("Duplicated role name '{}' at file '{}''" |
| 226 | .format(role_with_operations["name"], self.roles_to_operations_file)) |
| 227 | |
| 228 | if not role_with_operations["permissions"]: |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 229 | continue |
| 230 | |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 231 | for permission, is_allowed in role_with_operations["permissions"].items(): |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 232 | if not isinstance(is_allowed, bool): |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 233 | raise AuthException("Invalid value for permission '{}' at role '{}'; at file '{}'" |
| 234 | .format(permission, role_with_operations["name"], |
| 235 | self.roles_to_operations_file)) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 236 | |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 237 | # TODO chek permission is ok |
| 238 | if permission[-1] == ":": |
| 239 | raise AuthException("Invalid permission '{}' terminated in ':' for role '{}'; at file {}" |
| 240 | .format(permission, role_with_operations["name"], |
| 241 | self.roles_to_operations_file)) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 242 | |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 243 | if "default" not in role_with_operations["permissions"]: |
| 244 | role_with_operations["permissions"]["default"] = False |
| 245 | if "admin" not in role_with_operations["permissions"]: |
| 246 | role_with_operations["permissions"]["admin"] = False |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 247 | |
| 248 | now = time() |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 249 | role_with_operations["_admin"] = { |
| 250 | "created": now, |
| 251 | "modified": now, |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 252 | } |
| 253 | |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 254 | # self.db.create(self.roles_to_operations_table, role_with_operations) |
| 255 | self.backend.create_role(role_with_operations) |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 256 | self.logger.info("Role '{}' created at database".format(role_with_operations["name"])) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 257 | |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 258 | # Create admin project&user if required |
| 259 | pid = self.create_admin_project() |
| 260 | self.create_admin_user(pid) |
| 261 | |
| tierno | 1546f2a | 2019-08-20 15:38:11 +0000 | [diff] [blame] | 262 | # self.backend.update_user({"_id": "admin", |
| 263 | # "add_project_role_mappings": {"project": "admin", "role": "system_admin"}}) |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 264 | if self.config["authentication"]["backend"] == "keystone": |
| 265 | try: |
| 266 | self.backend.assign_role_to_user("admin", "admin", "system_admin") |
| 267 | except Exception: |
| 268 | pass |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 269 | |
| 270 | self.load_operation_to_allowed_roles() |
| 271 | |
| 272 | def load_operation_to_allowed_roles(self): |
| 273 | """ |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 274 | 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] | 275 | 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] | 276 | :return: None |
| 277 | """ |
| 278 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 279 | permissions = {oper: [] for oper in self.role_permissions} |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 280 | # records = self.db.get_list(self.roles_to_operations_table) |
| 281 | records = self.backend.get_role_list() |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 282 | |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 283 | ignore_fields = ["_id", "_admin", "name", "default"] |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 284 | for record in records: |
| delacruzramo | 01b15d3 | 2019-07-02 14:37:47 +0200 | [diff] [blame] | 285 | if not record.get("permissions"): |
| 286 | continue |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 287 | record_permissions = {oper: record["permissions"].get("default", False) for oper in self.role_permissions} |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 288 | operations_joined = [(oper, value) for oper, value in record["permissions"].items() |
| 289 | if oper not in ignore_fields] |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 290 | operations_joined.sort(key=lambda x: x[0].count(":")) |
| 291 | |
| 292 | for oper in operations_joined: |
| 293 | match = list(filter(lambda x: x.find(oper[0]) == 0, record_permissions.keys())) |
| 294 | |
| 295 | for m in match: |
| 296 | record_permissions[m] = oper[1] |
| 297 | |
| 298 | allowed_operations = [k for k, v in record_permissions.items() if v is True] |
| 299 | |
| 300 | for allowed_op in allowed_operations: |
| Eduardo Sousa | 5c01e19 | 2019-05-08 02:35:47 +0100 | [diff] [blame] | 301 | permissions[allowed_op].append(record["name"]) |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 302 | |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 303 | self.operation_to_allowed_roles = permissions |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 304 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 305 | def authorize(self, role_permission=None, query_string_operations=None): |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 306 | token = None |
| 307 | user_passwd64 = None |
| 308 | try: |
| 309 | # 1. Get token Authorization bearer |
| 310 | auth = cherrypy.request.headers.get("Authorization") |
| 311 | if auth: |
| 312 | auth_list = auth.split(" ") |
| 313 | if auth_list[0].lower() == "bearer": |
| 314 | token = auth_list[-1] |
| 315 | elif auth_list[0].lower() == "basic": |
| 316 | user_passwd64 = auth_list[-1] |
| 317 | if not token: |
| 318 | if cherrypy.session.get("Authorization"): |
| 319 | # 2. Try using session before request a new token. If not, basic authentication will generate |
| 320 | token = cherrypy.session.get("Authorization") |
| 321 | if token == "logout": |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 322 | token = None # force Unauthorized response to insert user password again |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 323 | elif user_passwd64 and cherrypy.request.config.get("auth.allow_basic_authentication"): |
| 324 | # 3. Get new token from user password |
| 325 | user = None |
| 326 | passwd = None |
| 327 | try: |
| 328 | user_passwd = standard_b64decode(user_passwd64).decode() |
| 329 | user, _, passwd = user_passwd.partition(":") |
| 330 | except Exception: |
| 331 | pass |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 332 | outdata = self.new_token(None, {"username": user, "password": passwd}) |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 333 | token = outdata["_id"] |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 334 | cherrypy.session['Authorization'] = token |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 335 | |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 336 | if not token: |
| 337 | raise AuthException("Needed a token or Authorization http header", |
| 338 | http_code=HTTPStatus.UNAUTHORIZED) |
| 339 | token_info = self.backend.validate_token(token) |
| 340 | # TODO add to token info remote host, port |
| 341 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 342 | if role_permission: |
| 343 | self.check_permissions(token_info, cherrypy.request.method, role_permission, |
| 344 | query_string_operations) |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 345 | return token_info |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 346 | except AuthException as e: |
| tierno | c844536 | 2019-06-14 12:07:15 +0000 | [diff] [blame] | 347 | if not isinstance(e, AuthExceptionUnauthorized): |
| 348 | if cherrypy.session.get('Authorization'): |
| 349 | del cherrypy.session['Authorization'] |
| 350 | cherrypy.response.headers["WWW-Authenticate"] = 'Bearer realm="{}"'.format(e) |
| tierno | e1eb3b2 | 2019-08-26 15:59:24 +0000 | [diff] [blame] | 351 | elif self.config.get("user_not_authorized"): |
| 352 | # TODO provide user_id, roles id (not name), project_id |
| 353 | return {"id": "fake-token-id-for-test", |
| 354 | "project_id": self.config.get("project_not_authorized", "admin"), |
| 355 | "username": self.config["user_not_authorized"], |
| 356 | "roles": ["system_admin"]} |
| tierno | c844536 | 2019-06-14 12:07:15 +0000 | [diff] [blame] | 357 | raise |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 358 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 359 | def new_token(self, token_info, indata, remote): |
| 360 | new_token_info = self.backend.authenticate( |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 361 | user=indata.get("username"), |
| 362 | password=indata.get("password"), |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 363 | token_info=token_info, |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 364 | project=indata.get("project_id") |
| 365 | ) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 366 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 367 | new_token_info["remote_port"] = remote.port |
| 368 | if not new_token_info.get("expires"): |
| 369 | new_token_info["expires"] = time() + 3600 |
| 370 | if not new_token_info.get("admin"): |
| 371 | new_token_info["admin"] = True if new_token_info.get("project_name") == "admin" else False |
| 372 | # TODO put admin in RBAC |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 373 | |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 374 | if remote.name: |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 375 | new_token_info["remote_host"] = remote.name |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 376 | elif remote.ip: |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 377 | new_token_info["remote_host"] = remote.ip |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 378 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 379 | self.tokens_cache[new_token_info["_id"]] = new_token_info |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 380 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 381 | # TODO call self._internal_tokens_prune(now) ? |
| 382 | return deepcopy(new_token_info) |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 383 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 384 | def get_token_list(self, token_info): |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 385 | if self.config["authentication"]["backend"] == "internal": |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 386 | return self._internal_get_token_list(token_info) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 387 | else: |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 388 | # TODO: check if this can be avoided. Backend may provide enough information |
| 389 | return [deepcopy(token) for token in self.tokens_cache.values() |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 390 | if token["username"] == token_info["username"]] |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 391 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 392 | def get_token(self, token_info, token): |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 393 | if self.config["authentication"]["backend"] == "internal": |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 394 | return self._internal_get_token(token_info, token) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 395 | else: |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 396 | # TODO: check if this can be avoided. Backend may provide enough information |
| 397 | token_value = self.tokens_cache.get(token) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 398 | if not token_value: |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 399 | raise AuthException("token not found", http_code=HTTPStatus.NOT_FOUND) |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 400 | if token_value["username"] != token_info["username"] and not token_info["admin"]: |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 401 | raise AuthException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 402 | return token_value |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 403 | |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 404 | def del_token(self, token): |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 405 | try: |
| 406 | self.backend.revoke_token(token) |
| 407 | self.tokens_cache.pop(token, None) |
| 408 | return "token '{}' deleted".format(token) |
| 409 | except KeyError: |
| 410 | raise AuthException("Token '{}' not found".format(token), http_code=HTTPStatus.NOT_FOUND) |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 411 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 412 | def check_permissions(self, token_info, method, role_permission=None, query_string_operations=None): |
| 413 | """ |
| 414 | Checks that operation has permissions to be done, base on the assigned roles to this user project |
| 415 | :param token_info: Dictionary that contains "roles" with a list of assigned roles. |
| 416 | This method fills the token_info["admin"] with True or False based on assigned tokens, if any allows admin |
| 417 | This will be used among others to hide or not the _admin content of topics |
| 418 | :param method: GET,PUT, POST, ... |
| 419 | :param role_permission: role permission name of the operation required |
| 420 | :param query_string_operations: list of possible admin query strings provided by user. It is checked that the |
| 421 | assigned role allows this query string for this method |
| 422 | :return: None if granted, exception if not allowed |
| 423 | """ |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 424 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 425 | roles_required = self.operation_to_allowed_roles[role_permission] |
| 426 | roles_allowed = [role["name"] for role in token_info["roles"]] |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 427 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 428 | # fills token_info["admin"] if some roles allows it |
| 429 | token_info["admin"] = False |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 430 | for role in roles_allowed: |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 431 | if role in self.operation_to_allowed_roles["admin:" + method.lower()]: |
| 432 | token_info["admin"] = True |
| tierno | a6bb45d | 2019-06-14 09:45:39 +0000 | [diff] [blame] | 433 | break |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 434 | |
| 435 | if "anonymous" in roles_required: |
| 436 | return |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 437 | operation_allowed = False |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 438 | for role in roles_allowed: |
| 439 | if role in roles_required: |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 440 | operation_allowed = True |
| 441 | # if query_string operations, check if this role allows it |
| 442 | if not query_string_operations: |
| 443 | return |
| 444 | for query_string_operation in query_string_operations: |
| 445 | if role not in self.operation_to_allowed_roles[query_string_operation]: |
| 446 | break |
| 447 | else: |
| 448 | return |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 449 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 450 | if not operation_allowed: |
| 451 | raise AuthExceptionUnauthorized("Access denied: lack of permissions.") |
| 452 | else: |
| 453 | raise AuthExceptionUnauthorized("Access denied: You have not permissions to use these admin query string") |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 454 | |
| Eduardo Sousa | 5c01e19 | 2019-05-08 02:35:47 +0100 | [diff] [blame] | 455 | def get_user_list(self): |
| 456 | return self.backend.get_user_list() |
| 457 | |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 458 | def _normalize_url(self, url, method): |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 459 | # DEPRECATED !!! |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 460 | # Removing query strings |
| 461 | normalized_url = url if '?' not in url else url[:url.find("?")] |
| 462 | normalized_url_splitted = normalized_url.split("/") |
| 463 | parameters = {} |
| 464 | |
| 465 | filtered_keys = [key for key in self.resources_to_operations_mapping.keys() |
| 466 | if method in key.split()[0]] |
| 467 | |
| 468 | for idx, path_part in enumerate(normalized_url_splitted): |
| 469 | tmp_keys = [] |
| 470 | for tmp_key in filtered_keys: |
| 471 | splitted = tmp_key.split()[1].split("/") |
| Eduardo Sousa | cc02e9a | 2019-03-20 17:32:36 +0000 | [diff] [blame] | 472 | if idx >= len(splitted): |
| 473 | continue |
| 474 | elif "<" in splitted[idx] and ">" in splitted[idx]: |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 475 | if splitted[idx] == "<artifactPath>": |
| 476 | tmp_keys.append(tmp_key) |
| 477 | continue |
| 478 | elif idx == len(normalized_url_splitted) - 1 and \ |
| 479 | len(normalized_url_splitted) != len(splitted): |
| 480 | continue |
| 481 | else: |
| 482 | tmp_keys.append(tmp_key) |
| 483 | elif splitted[idx] == path_part: |
| 484 | if idx == len(normalized_url_splitted) - 1 and \ |
| 485 | len(normalized_url_splitted) != len(splitted): |
| 486 | continue |
| 487 | else: |
| 488 | tmp_keys.append(tmp_key) |
| 489 | filtered_keys = tmp_keys |
| 490 | if len(filtered_keys) == 1 and \ |
| 491 | filtered_keys[0].split("/")[-1] == "<artifactPath>": |
| 492 | break |
| 493 | |
| 494 | if len(filtered_keys) == 0: |
| 495 | raise AuthException("Cannot make an authorization decision. URL not found. URL: {0}".format(url)) |
| 496 | elif len(filtered_keys) > 1: |
| 497 | raise AuthException("Cannot make an authorization decision. Multiple URLs found. URL: {0}".format(url)) |
| 498 | |
| 499 | filtered_key = filtered_keys[0] |
| 500 | |
| 501 | for idx, path_part in enumerate(filtered_key.split()[1].split("/")): |
| 502 | if "<" in path_part and ">" in path_part: |
| 503 | if path_part == "<artifactPath>": |
| 504 | parameters[path_part[1:-1]] = "/".join(normalized_url_splitted[idx:]) |
| 505 | else: |
| 506 | parameters[path_part[1:-1]] = normalized_url_splitted[idx] |
| 507 | |
| 508 | return filtered_key, parameters |
| 509 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 510 | def _internal_get_token_list(self, token_info): |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 511 | now = time() |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 512 | token_list = self.db.get_list("tokens", {"username": token_info["username"], "expires.gt": now}) |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 513 | return token_list |
| 514 | |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 515 | def _internal_get_token(self, token_info, token_id): |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 516 | 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] | 517 | if not token_value: |
| 518 | raise AuthException("token not found", http_code=HTTPStatus.NOT_FOUND) |
| tierno | 701018c | 2019-06-25 11:13:14 +0000 | [diff] [blame] | 519 | if token_value["username"] != token_info["username"] and not token_info["admin"]: |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 520 | raise AuthException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED) |
| 521 | return token_value |
| 522 | |
| tierno | 0ea204e | 2019-01-25 14:16:24 +0000 | [diff] [blame] | 523 | def _internal_tokens_prune(self, now=None): |
| 524 | now = now or time() |
| 525 | if not self.next_db_prune_time or self.next_db_prune_time >= now: |
| 526 | self.db.del_list("tokens", {"expires.lt": now}) |
| 527 | self.next_db_prune_time = self.periodin_db_pruning + now |
| Eduardo Sousa | 29933fc | 2018-11-14 06:36:35 +0000 | [diff] [blame] | 528 | self.tokens_cache.clear() # force to reload tokens from database |