Exemplo n.º 1
0
 def PUT(self, request, tenantId):
     try:
         info = InfoManager.InfoManager().get_information(tenantId)
         self.set_info(info)
         info2 = self.info.parse(request.body)
         if info2 != None:
             t = InfoManager.InfoManager().updateWindowSize(tenantId, info2.windowsize)
             logger.debug("Window size updated for tenant: %s", tenantId)
             return HttpResponse(json.dumps({"windowsize": info2.windowsize}, indent=4))
         else:
             return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     "windowsize could not be parsed"}}, indent=4))
     except ObjectDoesNotExist as err:
         t = TenantInfo(tenantId=tenantId, windowsize=5)
         t.save()
         info = InfoManager.InfoManager().get_information(tenantId)
         self.set_info(info)
         info2 = self.info.parse(request.body)
         t = InfoManager.InfoManager().updateWindowSize(tenantId, info2.windowsize)
         return HttpResponse(json.dumps({"windowsize": info2.windowsize}, indent=4))
     except ValidationError as ex:
             return HttpResponse(json.dumps({"badRequest": {"code": 400, "message":
                 ex.messages[0]}}, indent=4), status=400)
     except ValueError as ex:
             return HttpResponse(json.dumps({"badRequest": {"code": 400, "message":
                 ex.message}}, indent=4), status=400)
Exemplo n.º 2
0
 def PUT(self, request, tenantId, serverId, ruleId):
     try:
         rule = RuleManager.RuleManager().update_specific_rule(tenantId, serverId, ruleId, request.body)
         logger.debug("Rule updated: %s", ruleId)
         return HttpResponse(json.dumps(vars(rule), indent=4))
     except ValueError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except ValidationError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except KeyError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except AttributeError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except TypeError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except ObjectDoesNotExist as err:
         return HttpResponse(json.dumps({"itemNotFound": {"code": 404, "message":
                     str(err)}}, indent=4), status=404)
     except Exception as err:
         return HttpResponseServerError(json.dumps({"serverFault": {"code": 500, "message":
                     str(err)}}, indent=4))
Exemplo n.º 3
0
 def DELETE(self, request, tenantId, ruleId):
     try:
         RuleManager.RuleManager().delete_rule(ruleId)
         logger.debug("Rule deleted: %s", ruleId)
         return HttpResponse()
     except Exception as err:
         return HttpResponseServerError(json.dumps({"serverFault": {"code": 500, "message":
                     str(err)}}, indent=4))
Exemplo n.º 4
0
 def DELETE(self, request, tenantId, serverId, ruleId):
     try:
         RuleManager.RuleManager().delete_specific_rule(tenantId, serverId, ruleId)
         logger.debug("Rule deleted: %s", ruleId)
         return HttpResponse()
     except ObjectDoesNotExist as err:
         return HttpResponse(json.dumps({"itemNotFound": {"code": 404, "message":
                     str(err)}}, indent=4), status=404)
     except Exception as err:
         return HttpResponseServerError(json.dumps({"serverFault": {"code": 500, "message":
                     str(err)}}, indent=4))
Exemplo n.º 5
0
 def POST(self, request, tenantId):
     try:
         rule = RuleManager.RuleManager().create_general_rule(tenantId, request.body)
         logger.debug("Rule created: %s", rule.ruleId)
         return HttpResponse(json.dumps(vars(rule), indent=4))
     except ValueError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except Exception as err:
         return HttpResponseServerError(json.dumps({"serverFault": {"code": 500, "message":
                     str(err)}}, indent=4))
Exemplo n.º 6
0
 def DELETE(self, request, tenantId, serverId, subscriptionId):
     try:
         ruleManager = RuleManager.RuleManager()
         ruleManager.orionClient = orion_client.orion_client()
         ruleManager.unsubscribe_to_rule(serverId, subscriptionId)
         logger.debug("Subscription deleted %s for server: %s", subscriptionId, serverId)
         return HttpResponse()
     except ObjectDoesNotExist as err:
         return HttpResponse(json.dumps({"itemNotFound": {"code": 404, "message":
             str(err)}}, indent=4), status=404)
     except Exception as err:
         return HttpResponseServerError(json.dumps({"serverFault": {"code": 500, "message":
                     str(err)}}, indent=4))
Exemplo n.º 7
0
 def POST(self, request, tenantId, serverId):
     try:
         ruleManager = RuleManager.RuleManager()
         ruleManager.orionClient = orion_client.orion_client()
         subscriptionId = ruleManager.subscribe_to_rule(tenantId, serverId, request.body)
         logger.debug("Subscrition created %s for server: %s", subscriptionId, serverId)
         return HttpResponse(json.dumps({"serverId": serverId, "subscriptionId": str(subscriptionId)}, indent=4))
     except ObjectDoesNotExist as err:
         return HttpResponse(json.dumps({"itemNotFound": {"code": 404, "message":
                     str(err)}}, indent=4), status=404)
     except Conflict as err:
         return HttpResponse(json.dumps({"conflict": {"code": 409, "message":
                     err.message}}, indent=4), status=409)
     except ValidationError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     err.messages[0]}}, indent=4))
     except Exception as err:
         return HttpResponseServerError(json.dumps({"serverFault": {"code": 500, "message":
                     str(err)}}, indent=4))
Exemplo n.º 8
0
 def checkToken(self, admin_token, token, tenant_id, url, auth_api):
     """checks if a token is valid against a url using an admin token."""
     logger.debug("Starting Authentication of token %s ", token)
     try:
         if not token:
             raise Unauthorized("Token is empty")
         auth_result = self.get_info_token(url, admin_token, token, auth_api)
         if auth_result:
             if tenant_id == auth_result.tenant["id"]:
                 logger.debug('The token is valid')
             else:
                 logger.error("TenantId %s ", tenant_id)
                 logger.error("Token TenantId %s ", auth_result.tenant["id"])
                 raise Unauthorized("Token is not valid for specified tenant %s" % tenant_id)
     except Unauthorized as unauth:
         logger.error(unauth)
         raise unauth
     except InternalServerError as internalError:
         raise AuthorizationFailure("Token could not have enough permissions to access tenant: %s" % tenant_id)
     except Exception as ex:
         raise ex
Exemplo n.º 9
0
 def POST(self, request, tenantId, serverId):
     try:
         rule = RuleManager.RuleManager().create_specific_rule(tenantId, serverId, request.body)
         logger.debug("Rule created: %s", rule.ruleId)
         return HttpResponse(json.dumps({"serverId": serverId, "ruleId": rule.ruleId}, indent=4))
     except ValueError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except ValidationError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except KeyError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except AttributeError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except TypeError as err:
         return HttpResponseBadRequest(json.dumps({"badRequest": {"code": 400, "message":
                     str(err)}}, indent=4))
     except Exception as err:
         return HttpResponseServerError(json.dumps({"serverFault": {"code": 500, "message":
                     str(err)}}, indent=4))
Exemplo n.º 10
0
    def get_auth_token(self, username, password, tenant_id, **kwargs):
        """
        Init the variables related to authorization, needed to execute tests
        :return: The auth token retrieved
        """
        if self.auth_token is None:

            cred_kwargs = {
                'auth_url': self.identity_url,
                'username': username,
                'password': password
            }

            # Currently, both v2 and v3 Identity API versions are supported
            if self.api_version == AUTH_API_V2:
                cred_kwargs['tenant_name'] = kwargs.get('tenant_name')
            elif self.api_version == AUTH_API_V3:
                cred_kwargs['user_domain_name'] = kwargs.get(
                    'user_domain_name')

            # Instantiate a Password object
            try:
                identity_package = 'keystoneclient.auth.identity.%s' % self.api_version.replace(
                    '.0', '')
                identity_module = __import__(identity_package,
                                             fromlist=['Password'])
                password_class = getattr(identity_module, 'Password')
                logger.debug("Authentication with %s", password_class)
                credentials = password_class(**cred_kwargs)
            except (ImportError, AttributeError) as e:
                raise e
            # Get auth token
            logger.debug("Getting auth token for tenant %s...", tenant_id)
            try:
                auth_sess = self.session.Session(
                    auth=credentials, timeout=DEFAULT_REQUEST_TIMEOUT)
                self.auth_token = auth_sess.get_token()
                logger.debug("Admin token generated: %s", self.auth_token)

            except Exception as e:
                logger.error("No auth token (%s)", e.message)
                raise (e)

        return self.auth_token
Exemplo n.º 11
0
    def get_auth_token(self, username, password, tenant_id, auth_api, url, **kwargs):
        """
        Init the variables related to authorization, needed to execute tests
        :return: The auth token retrieved
        """

        cred_kwargs = {
            'auth_url': url,
            'username': username,
            'password': password
        }

        # Currently, both v2 and v3 Identity API versions are supported
        if auth_api == AUTH_API_V2:
            cred_kwargs['tenant_name'] = kwargs.get('tenant_name')
        elif auth_api == AUTH_API_V3:
            cred_kwargs['user_domain_name'] = kwargs.get('user_domain_name')

        # Instantiate a Password object
        try:
            identity_package = 'keystoneclient.auth.identity.%s' % auth_api.replace('.0', '')
            identity_module = __import__(identity_package, fromlist=['Password'])
            password_class = getattr(identity_module, 'Password')
            logger.debug("Authentication with %s", password_class)
            credentials = password_class(**cred_kwargs)
        except (ImportError, AttributeError) as e:
                raise e
        # Get auth token
        logger.debug("Getting auth token for tenant %s...", tenant_id)
        try:
            auth_sess = self.session.Session(auth=credentials, timeout=DEFAULT_REQUEST_TIMEOUT)
            auth_token = auth_sess.get_token()
            logger.debug("Admin token generated:" + auth_token)

        except (KeystoneClientException, KeystoneConnectionRefused) as e:
            logger.error("No auth token (%s)", e.message)
            raise(e)

        return auth_token
Exemplo n.º 12
0
    def get_auth_token(self, username, password, tenant_id, **kwargs):
        """
        Init the variables related to authorization, needed to execute tests
        :return: The auth token retrieved
        """
        if self.auth_token is None:

            cred_kwargs = {"auth_url": self.identity_url, "username": username, "password": password}

            # Currently, both v2 and v3 Identity API versions are supported
            if self.api_version == AUTH_API_V2:
                cred_kwargs["tenant_name"] = kwargs.get("tenant_name")
            elif self.api_version == AUTH_API_V3:
                cred_kwargs["user_domain_name"] = kwargs.get("user_domain_name")

            # Instantiate a Password object
            try:
                identity_package = "keystoneclient.auth.identity.%s" % self.api_version.replace(".0", "")
                identity_module = __import__(identity_package, fromlist=["Password"])
                password_class = getattr(identity_module, "Password")
                logger.debug("Authentication with %s", password_class)
                credentials = password_class(**cred_kwargs)
            except (ImportError, AttributeError) as e:
                raise e
            # Get auth token
            logger.debug("Getting auth token for tenant %s...", tenant_id)
            try:
                auth_sess = self.session.Session(auth=credentials, timeout=DEFAULT_REQUEST_TIMEOUT)
                self.auth_token = auth_sess.get_token()
                logger.debug("Admin token generated: %s", self.auth_token)

            except Exception as e:
                logger.error("No auth token (%s)", e.message)
                raise (e)

        return self.auth_token
Exemplo n.º 13
0
    def checkToken(self, admin_token, token, tenant_id):
        """checks if a token is valid against a url using an admin token."""

        token_db = None
        try:
            if not token:
                raise Unauthorized("Token is empty")
            logger.debug("Starting Authentication of token %s ", token)

            try:
                token_db = self.get_token_from_memory(token)
                if self.api_version == AUTH_API_V2:
                    time_to_review = token_db['createdAt'] + timezone.timedelta(
                        seconds=int(settings.SECURITY_LEVEL_SECONDS_V2[
                            settings.SECURITY_LEVEL]))
                elif self.api_version == AUTH_API_V3:
                    time_to_review = token_db['createdAt'] + timezone.timedelta(
                        seconds=int(settings.SECURITY_LEVEL_SECONDS_V3[
                            settings.SECURITY_LEVEL]))

                logger.debug(
                    "Token {0} is present in memory, should be checked at {1}".
                    format(token, time_to_review))
                expires = dateparse.parse_datetime(token_db['expires'])
                if timezone.now() > expires or timezone.now(
                ) > time_to_review or tenant_id is not token_db["tenant"]:
                    logger.debug(
                        "Token %s should be checked against keystone.", token)
                else:
                    return token
            except KeyError:

                logger.debug("Token %s is not present in DB", token)
                pass

            auth_result = self.get_info_token(admin_token, token)
            if auth_result:
                if tenant_id == auth_result.tenant["id"]:
                    # STORE TOKEN IN MEMORY
                    createdAt = timezone.now()
                    token_db = self.user_tokens.setdefault(
                        token, {
                            'id': auth_result.id,
                            'expires': auth_result.expires,
                            'username': auth_result.username,
                            'tenant': auth_result.tenant["id"],
                            'createdAt': createdAt
                        })

                    self.user_tokens[token] = token_db
                    return token

                else:
                    logger.error("TenantId %s ", tenant_id)
                    logger.error("Token TenantId %s ",
                                 auth_result.tenant["id"])
                    raise Unauthorized(
                        "Token is not valid for specified tenant %s" %
                        tenant_id)

        except AuthorizationFailure as ex:
            if re.search(self.auth_token, ex.message) or re.search(
                    AUTH_TOKEN_ERROR_MESSAGE, ex.message):
                self.auth_token = None
                logger.debug(
                    "Admin token has expired, setting global to None.")
            elif re.search(token, ex.message) and token_db:
                self.user_tokens.pop(token)
            raise ex
        except Unauthorized as unauth:
            logger.debug(unauth)
            raise unauth
        except InternalServerError as internalError:
            raise AuthorizationFailure(
                "Token could not have enough permissions to access tenant: %s"
                % tenant_id)
        except Exception as ex:
            raise ex
Exemplo n.º 14
0
    def checkToken(self, admin_token, token, tenant_id):
        """checks if a token is valid against a url using an admin token."""

        token_db = None
        try:
            if not token:
                raise Unauthorized("Token is empty")
            logger.debug("Starting Authentication of token %s ", token)

            try:
                token_db = self.get_token_from_memory(token)
                if self.api_version == AUTH_API_V2:
                    time_to_review = token_db["createdAt"] + timezone.timedelta(
                        seconds=int(settings.SECURITY_LEVEL_SECONDS_V2[settings.SECURITY_LEVEL])
                    )
                elif self.api_version == AUTH_API_V3:
                    time_to_review = token_db["createdAt"] + timezone.timedelta(
                        seconds=int(settings.SECURITY_LEVEL_SECONDS_V3[settings.SECURITY_LEVEL])
                    )

                logger.debug("Token {0} is present in memory, should be checked at {1}".format(token, time_to_review))
                expires = dateparse.parse_datetime(token_db["expires"])
                if timezone.now() > expires or timezone.now() > time_to_review or tenant_id is not token_db["tenant"]:
                    logger.debug("Token %s should be checked against keystone.", token)
                else:
                    return token
            except KeyError:

                logger.debug("Token %s is not present in DB", token)
                pass

            auth_result = self.get_info_token(admin_token, token)
            if auth_result:
                if tenant_id == auth_result.tenant["id"]:
                    # STORE TOKEN IN MEMORY
                    createdAt = timezone.now()
                    token_db = self.user_tokens.setdefault(
                        token,
                        {
                            "id": auth_result.id,
                            "expires": auth_result.expires,
                            "username": auth_result.username,
                            "tenant": auth_result.tenant["id"],
                            "createdAt": createdAt,
                        },
                    )

                    self.user_tokens[token] = token_db
                    return token

                else:
                    logger.error("TenantId %s ", tenant_id)
                    logger.error("Token TenantId %s ", auth_result.tenant["id"])
                    raise Unauthorized("Token is not valid for specified tenant %s" % tenant_id)

        except AuthorizationFailure as ex:
            if re.search(self.auth_token, ex.message) or re.search(AUTH_TOKEN_ERROR_MESSAGE, ex.message):
                self.auth_token = None
                logger.debug("Admin token has expired, setting global to None.")
            elif re.search(token, ex.message) and token_db:
                self.user_tokens.pop(token)
            raise ex
        except Unauthorized as unauth:
            logger.debug(unauth)
            raise unauth
        except InternalServerError as internalError:
            raise AuthorizationFailure("Token could not have enough permissions to access tenant: %s" % tenant_id)
        except Exception as ex:
            raise ex