+from random import choice as random_choice
+from time import time
+from uuid import uuid4
+
+from authconn import AuthException
+from authconn_keystone import AuthconnKeystone
+from osm_common import dbmongo
+from osm_common import dbmemory
+from osm_common.dbbase import DbException
+
+
+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.
+ """
+
+ periodin_db_pruning = 60 * 30 # for the internal backend only. every 30 minutes expired tokens will be pruned
+
+ def __init__(self):
+ """
+ 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.tokens_cache = dict()
+ self.next_db_prune_time = 0 # time when next cleaning of expired tokens must be done
+ self.resources_to_operations_file = None
+ self.roles_to_operations_file = None
+ self.resources_to_operations_mapping = {}
+ self.operation_to_allowed_roles = {}
+ self.logger = logging.getLogger("nbi.authenticator")
+
+ 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.backend:
+ if config["authentication"]["backend"] == "keystone":
+ self.backend = AuthconnKeystone(self.config["authentication"])
+ elif config["authentication"]["backend"] == "internal":
+ self._internal_tokens_prune()
+ else:
+ raise AuthException("Unknown authentication backend: {}"
+ .format(config["authentication"]["backend"]))
+ if not self.resources_to_operations_file:
+ if "resources_to_operations" in config["rbac"]:
+ self.resources_to_operations_file = config["rbac"]["resources_to_operations"]
+ else:
+ for config_file in (__file__[:__file__.rfind("auth.py")] + "resources_to_operations.yml",
+ "./resources_to_operations.yml"):
+ if path.isfile(config_file):
+ self.resources_to_operations_file = config_file
+ break
+ if not self.resources_to_operations_file:
+ raise AuthException("Invalid permission configuration: resources_to_operations file missing")
+ 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:
+ for config_file in (__file__[:__file__.rfind("auth.py")] + "roles_to_operations.yml",
+ "./roles_to_operations.yml"):
+ 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")
+ 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 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.
+ """
+ # Always reads operation to resource mapping from file (this is static, no need to store it in MongoDB)
+ # Operations encoding: "<METHOD> <URL>"
+ # Note: it is faster to rewrite the value than to check if it is already there or not
+ operations = []
+ with open(self.resources_to_operations_file, "r") as stream:
+ resources_to_operations_yaml = yaml.load(stream)
+
+ for resource, operation in resources_to_operations_yaml["resources_to_operations"].items():
+ operation_key = operation.replace(".", ":")
+ if operation_key not in operations:
+ operations.append(operation_key)
+ self.resources_to_operations_mapping[resource] = operation_key
+
+ records = self.db.get_list("roles_operations")
+
+ # Loading permissions to MongoDB. If there are permissions already in MongoDB, do nothing.
+ if len(records) == 0:
+ with open(self.roles_to_operations_file, "r") as stream:
+ roles_to_operations_yaml = yaml.load(stream)
+
+ roles = []
+ for role_with_operations in roles_to_operations_yaml["roles_to_operations"]:
+ # Verifying if role already exists. If it does, send warning to log and ignore it.
+ if role_with_operations["role"] not in roles:
+ roles.append(role_with_operations["role"])
+ else:
+ self.logger.warning("Duplicated role with name: {0}. Role definition is ignored."
+ .format(role_with_operations["role"]))
+ continue
+
+ operations = {}
+ root = None
+
+ if not role_with_operations["operations"]:
+ continue
+
+ for operation, is_allowed in role_with_operations["operations"].items():
+ if not isinstance(is_allowed, bool):
+ continue
+
+ if operation == ".":
+ root = is_allowed
+ continue
+
+ if len(operation) != 1 and operation[-1] == ".":
+ self.logger.warning("Invalid operation {0} terminated in '.'. "
+ "Operation will be discarded"
+ .format(operation))
+ continue
+
+ operation_key = operation.replace(".", ":")
+ if operation_key not in operations.keys():
+ operations[operation_key] = is_allowed
+ else:
+ self.logger.info("In role {0}, the operation {1} with the value {2} was discarded due to "
+ "repetition.".format(role_with_operations["role"], operation, is_allowed))
+
+ if not root:
+ root = False
+ self.logger.info("Root for role {0} not defined. Default value 'False' applied."
+ .format(role_with_operations["role"]))
+
+ now = time()
+ operation_to_roles_item = {
+ "_id": str(uuid4()),
+ "_admin": {
+ "created": now,
+ "modified": now,
+ },
+ "role": role_with_operations["role"],
+ "root": root
+ }
+
+ for operation, value in operations.items():
+ operation_to_roles_item[operation] = value
+
+ self.db.create("roles_operations", operation_to_roles_item)
+
+ permissions = {oper: [] for oper in operations}
+ records = self.db.get_list("roles_operations")
+
+ ignore_fields = ["_id", "_admin", "role", "root"]
+ roles = []
+ for record in records: