+from time import time
+from os import path
+
+from osm_nbi.authconn import AuthException, AuthconnException, AuthExceptionUnauthorized
+from osm_nbi.authconn_keystone import AuthconnKeystone
+from osm_nbi.authconn_internal import AuthconnInternal
+from osm_common import dbmemory, dbmongo, msglocal, msgkafka
+from osm_common.dbbase import DbException
+from osm_nbi.validation import is_valid_uuid
+from itertools import chain
+from uuid import uuid4
+
+
+class Authenticator:
+ """
+ This class should hold all the mechanisms for User Authentication and
+ Authorization. Initially it should support Openstack Keystone as a
+ backend through a plugin model where more backends can be added and a
+ RBAC model to manage permissions on operations.
+ This class must be threading safe
+ """
+
+ periodin_db_pruning = 60 * 30 # for the internal backend only. every 30 minutes expired tokens will be pruned
+ token_limit = 500 # when reached, the token cache will be cleared
+
+ def __init__(self, valid_methods, valid_query_string):
+ """
+ Authenticator initializer. Setup the initial state of the object,
+ while it waits for the config dictionary and database initialization.
+ """
+ self.backend = None
+ self.config = None
+ self.db = None
+ self.msg = None
+ self.tokens_cache = dict()
+ self.next_db_prune_time = 0 # time when next cleaning of expired tokens must be done
+ self.roles_to_operations_file = None
+ # self.roles_to_operations_table = None
+ self.resources_to_operations_mapping = {}
+ self.operation_to_allowed_roles = {}
+ self.logger = logging.getLogger("nbi.authenticator")
+ self.role_permissions = []
+ self.valid_methods = valid_methods
+ self.valid_query_string = valid_query_string
+ self.system_admin_role_id = None # system_role id
+ self.test_project_id = None # test_project_id
+
+ def start(self, config):
+ """
+ Method to configure the Authenticator object. This method should be called
+ after object creation. It is responsible by initializing the selected backend,
+ as well as the initialization of the database connection.
+
+ :param config: dictionary containing the relevant parameters for this object.
+ """
+ self.config = config
+
+ try:
+ if not self.db:
+ if config["database"]["driver"] == "mongo":
+ self.db = dbmongo.DbMongo()
+ self.db.db_connect(config["database"])
+ elif config["database"]["driver"] == "memory":
+ self.db = dbmemory.DbMemory()
+ self.db.db_connect(config["database"])
+ else:
+ raise AuthException("Invalid configuration param '{}' at '[database]':'driver'"
+ .format(config["database"]["driver"]))
+ if not self.msg:
+ if config["message"]["driver"] == "local":
+ self.msg = msglocal.MsgLocal()
+ self.msg.connect(config["message"])
+ elif config["message"]["driver"] == "kafka":
+ self.msg = msgkafka.MsgKafka()
+ self.msg.connect(config["message"])
+ else:
+ raise AuthException("Invalid configuration param '{}' at '[message]':'driver'"
+ .format(config["message"]["driver"]))
+ if not self.backend:
+ if config["authentication"]["backend"] == "keystone":
+ self.backend = AuthconnKeystone(self.config["authentication"], self.db, self.role_permissions)
+ elif config["authentication"]["backend"] == "internal":
+ self.backend = AuthconnInternal(self.config["authentication"], self.db, self.role_permissions)
+ self._internal_tokens_prune()
+ else:
+ raise AuthException("Unknown authentication backend: {}"
+ .format(config["authentication"]["backend"]))
+
+ if not self.roles_to_operations_file:
+ if "roles_to_operations" in config["rbac"]:
+ self.roles_to_operations_file = config["rbac"]["roles_to_operations"]
+ else:
+ possible_paths = (
+ __file__[:__file__.rfind("auth.py")] + "roles_to_operations.yml",
+ "./roles_to_operations.yml"
+ )
+ for config_file in possible_paths:
+ if path.isfile(config_file):
+ self.roles_to_operations_file = config_file
+ break
+ if not self.roles_to_operations_file:
+ raise AuthException("Invalid permission configuration: roles_to_operations file missing")
+
+ # load role_permissions
+ def load_role_permissions(method_dict):
+ for k in method_dict:
+ if k == "ROLE_PERMISSION":
+ for method in chain(method_dict.get("METHODS", ()), method_dict.get("TODO", ())):
+ permission = method_dict["ROLE_PERMISSION"] + method.lower()
+ if permission not in self.role_permissions:
+ self.role_permissions.append(permission)
+ elif k in ("TODO", "METHODS"):
+ continue
+ elif method_dict[k]:
+ load_role_permissions(method_dict[k])
+
+ load_role_permissions(self.valid_methods)
+ for query_string in self.valid_query_string:
+ for method in ("get", "put", "patch", "post", "delete"):
+ permission = query_string.lower() + ":" + method
+ if permission not in self.role_permissions:
+ self.role_permissions.append(permission)
+
+ # get ids of role system_admin and test project
+ role_system_admin = self.db.get_one("roles", {"name": "system_admin"}, fail_on_empty=False)
+ if role_system_admin:
+ self.system_admin_role_id = role_system_admin["_id"]
+ test_project_name = self.config["authentication"].get("project_not_authorized", "admin")
+ test_project = self.db.get_one("projects", {"name": test_project_name}, fail_on_empty=False)
+ if test_project:
+ self.test_project_id = test_project["_id"]
+
+ except Exception as e:
+ raise AuthException(str(e))
+
+ def stop(self):
+ try:
+ if self.db:
+ self.db.db_disconnect()
+ except DbException as e:
+ raise AuthException(str(e), http_code=e.http_code)
+
+ def create_admin_project(self):
+ """
+ Creates a new project 'admin' into database if it doesn't exist. Useful for initialization.
+ :return: _id identity of the 'admin' project
+ """
+
+ # projects = self.db.get_one("projects", fail_on_empty=False, fail_on_more=False)
+ project_desc = {"name": "admin"}
+ projects = self.backend.get_project_list(project_desc)
+ if projects:
+ return projects[0]["_id"]
+ now = time()
+ project_desc["_id"] = str(uuid4())
+ project_desc["_admin"] = {"created": now, "modified": now}
+ pid = self.backend.create_project(project_desc)
+ self.logger.info("Project '{}' created at database".format(project_desc["name"]))
+ return pid
+
+ def create_admin_user(self, project_id):
+ """
+ Creates a new user admin/admin into database if database is empty. Useful for initialization
+ :return: _id identity of the inserted data, or None
+ """
+ # users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
+ users = self.backend.get_user_list()
+ if users:
+ return None
+ # user_desc = {"username": "admin", "password": "admin", "projects": [project_id]}
+ now = time()
+ user_desc = {"username": "admin", "password": "admin", "_admin": {"created": now, "modified": now}}
+ if project_id:
+ pid = project_id
+ else:
+ # proj = self.db.get_one("projects", {"name": "admin"}, fail_on_empty=False, fail_on_more=False)
+ proj = self.backend.get_project_list({"name": "admin"})
+ pid = proj[0]["_id"] if proj else None
+ # role = self.db.get_one("roles", {"name": "system_admin"}, fail_on_empty=False, fail_on_more=False)
+ roles = self.backend.get_role_list({"name": "system_admin"})
+ if pid and roles:
+ user_desc["project_role_mappings"] = [{"project": pid, "role": roles[0]["_id"]}]
+ uid = self.backend.create_user(user_desc)
+ self.logger.info("User '{}' created at database".format(user_desc["username"]))
+ return uid
+
+ def init_db(self, target_version='1.0'):
+ """
+ Check if the database has been initialized, with at least one user. If not, create the required tables
+ and insert the predefined mappings between roles and permissions.
+
+ :param target_version: schema version that should be present in the database.
+ :return: None if OK, exception if error or version is different.
+ """
+
+ records = self.backend.get_role_list()
+
+ # Loading permissions to AUTH. At lease system_admin must be present.
+ if not records or not next((r for r in records if r["name"] == "system_admin"), None):
+ with open(self.roles_to_operations_file, "r") as stream:
+ roles_to_operations_yaml = yaml.load(stream, Loader=yaml.Loader)
+
+ role_names = []
+ for role_with_operations in roles_to_operations_yaml["roles"]:
+ # Verifying if role already exists. If it does, raise exception
+ if role_with_operations["name"] not in role_names:
+ role_names.append(role_with_operations["name"])
+ else:
+ raise AuthException("Duplicated role name '{}' at file '{}''"
+ .format(role_with_operations["name"], self.roles_to_operations_file))
+
+ if not role_with_operations["permissions"]:
+ continue
+
+ for permission, is_allowed in role_with_operations["permissions"].items():
+ if not isinstance(is_allowed, bool):
+ raise AuthException("Invalid value for permission '{}' at role '{}'; at file '{}'"
+ .format(permission, role_with_operations["name"],
+ self.roles_to_operations_file))
+
+ # TODO check permission is ok
+ if permission[-1] == ":":
+ raise AuthException("Invalid permission '{}' terminated in ':' for role '{}'; at file {}"
+ .format(permission, role_with_operations["name"],
+ self.roles_to_operations_file))
+
+ if "default" not in role_with_operations["permissions"]:
+ role_with_operations["permissions"]["default"] = False
+ if "admin" not in role_with_operations["permissions"]:
+ role_with_operations["permissions"]["admin"] = False
+
+ now = time()
+ role_with_operations["_admin"] = {
+ "created": now,
+ "modified": now,
+ }
+
+ # self.db.create(self.roles_to_operations_table, role_with_operations)
+ try:
+ self.backend.create_role(role_with_operations)
+ self.logger.info("Role '{}' created".format(role_with_operations["name"]))
+ except (AuthException, AuthconnException) as e:
+ if role_with_operations["name"] == "system_admin":
+ raise
+ self.logger.error("Role '{}' cannot be created: {}".format(role_with_operations["name"], e))