Ejemplo n.º 1
0
    def process_request(self, request):
        """Check before super."""
        connection.set_schema_to_public()

        if not is_no_auth(request):
            if hasattr(request, "user") and hasattr(request.user, "username"):
                username = request.user.username
                try:
                    if username not in USER_CACHE:
                        USER_CACHE[username] = User.objects.get(
                            username=username)
                        LOG.debug(f"User added to cache: {username}")
                except User.DoesNotExist:
                    return HttpResponseUnauthorizedRequest()
                if not request.user.admin and request.user.access is None:
                    LOG.warning(
                        "User %s is does not have permissions for Cost Management.",
                        username)
                    # For /user-access we do not want to raise the exception since the API will
                    # return a false boolean response that the platfrom frontend code is expecting.
                    if request.path != reverse("user-access"):
                        raise PermissionDenied()
            else:
                return HttpResponseUnauthorizedRequest()
        try:
            super().process_request(request)
        except OperationalError as err:
            LOG.error("Request resulted in OperationalError: %s", err)
            DB_CONNECTION_ERRORS_COUNTER.inc()
            return HttpResponseFailedDependency({
                "source": "Database",
                "exception": err
            })
Ejemplo n.º 2
0
 def process_exception(self, request, exception):
     """Raise 424 on InterfaceError."""
     if isinstance(exception, InterfaceError):
         DB_CONNECTION_ERRORS_COUNTER.inc()
         LOG.error("KokuTenantMiddleware InterfaceError exception: %s",
                   exception)
         return HttpResponseFailedDependency({
             "source": "Database",
             "exception": exception
         })
Ejemplo n.º 3
0
 def process_exception(self, request, exception):  # pylint: disable=R0201,R1710
     """Raise 424 on InterfaceError."""
     if isinstance(exception, InterfaceError):
         DB_CONNECTION_ERRORS_COUNTER.inc()
         LOG.error('KokuTenantMiddleware InterfaceError exception: %s',
                   exception)
         return HttpResponseFailedDependency({
             'source': 'Database',
             'exception': exception
         })
Ejemplo n.º 4
0
    def process_request(self, request):  # pylint: disable=R1710
        """Check before super."""
        connection.set_schema_to_public()

        if not is_no_auth(request):
            if hasattr(request, "user") and hasattr(request.user, "username"):
                username = request.user.username
                try:
                    User.objects.get(username=username)
                except User.DoesNotExist:
                    return HttpResponseUnauthorizedRequest()
                if not request.user.admin and request.user.access is None:
                    LOG.warning("User %s is does not have permissions for Cost Management.", username)
                    raise PermissionDenied()
            else:
                return HttpResponseUnauthorizedRequest()
        try:
            super().process_request(request)
        except OperationalError as err:
            LOG.error("Request resulted in OperationalError: %s", err)
            DB_CONNECTION_ERRORS_COUNTER.inc()
            return HttpResponseFailedDependency({"source": "Database", "exception": err})
Ejemplo n.º 5
0
 def process_request(self, request):  # pylint: disable=R1710
     """Check before super."""
     if not is_no_auth(request):
         if hasattr(request, 'user') and hasattr(request.user, 'username'):
             username = request.user.username
             try:
                 User.objects.get(username=username)
             except User.DoesNotExist:
                 return HttpResponseUnauthorizedRequest()
             if not request.user.admin and request.user.access is None:
                 raise PermissionDenied()
         else:
             return HttpResponseUnauthorizedRequest()
     try:
         super().process_request(request)
     except OperationalError as err:
         LOG.error('Request resulted in OperationalError: %s', err)
         DB_CONNECTION_ERRORS_COUNTER.inc()
         return HttpResponseFailedDependency({
             'source': 'Database',
             'exception': err
         })
Ejemplo n.º 6
0
    def process_request(self, request):  # noqa: C901
        """Process request for csrf checks.
        Args:
            request (object): The request object
        """
        connection.set_schema_to_public()

        if is_no_auth(request):
            request.user = User("", "")
            return

        try:
            rh_auth_header, json_rh_auth = extract_header(request, self.header)
        except (KeyError, JSONDecodeError):
            LOG.warning("Could not obtain identity on request.")
            return
        except binascii.Error as error:
            LOG.error("Error decoding authentication header: %s", str(error))
            raise PermissionDenied()

        is_cost_management = json_rh_auth.get("entitlements", {}).get(
            "cost_management", {}).get("is_entitled", False)
        skip_entitlement = is_no_entitled(request)
        if not skip_entitlement and not is_cost_management:
            LOG.warning("User is not entitled for Cost Management.")
            raise PermissionDenied()

        account = json_rh_auth.get("identity", {}).get("account_number")
        user = json_rh_auth.get("identity", {}).get("user", {})
        username = user.get("username")
        email = user.get("email")
        is_admin = user.get("is_org_admin")
        req_id = None

        if username and email and account:
            # Get request ID
            req_id = request.META.get("HTTP_X_RH_INSIGHTS_REQUEST_ID")
            # Check for customer creation & user creation
            query_string = ""
            if request.META["QUERY_STRING"]:
                query_string = "?{}".format(request.META["QUERY_STRING"])
            stmt = {
                "method": request.method,
                "path": request.path + query_string,
                "request_id": req_id,
                "account": account,
                "username": username,
                "is_admin": is_admin,
            }
            LOG.info(stmt)
            try:
                if account not in IdentityHeaderMiddleware.customer_cache:
                    IdentityHeaderMiddleware.customer_cache[
                        account] = Customer.objects.filter(
                            account_id=account).get()
                    LOG.debug(f"Customer added to cache: {account}")
                customer = IdentityHeaderMiddleware.customer_cache[account]
            except Customer.DoesNotExist:
                customer = IdentityHeaderMiddleware.create_customer(account)
            except OperationalError as err:
                LOG.error("IdentityHeaderMiddleware exception: %s", err)
                DB_CONNECTION_ERRORS_COUNTER.inc()
                return HttpResponseFailedDependency({
                    "source": "Database",
                    "exception": err
                })

            try:
                if username not in USER_CACHE:
                    user = User.objects.get(username=username)
                    USER_CACHE[username] = user
                    LOG.debug(f"User added to cache: {username}")
                else:
                    user = USER_CACHE[username]
            except User.DoesNotExist:
                user = IdentityHeaderMiddleware.create_user(
                    username, email, customer, request)

            user.identity_header = {
                "encoded": rh_auth_header,
                "decoded": json_rh_auth
            }
            user.admin = is_admin
            user.req_id = req_id

            cache = caches["rbac"]
            user_access = cache.get(user.uuid)

            if not user_access:
                if settings.DEVELOPMENT and request.user.req_id == "DEVELOPMENT":
                    # passthrough for DEVELOPMENT_IDENTITY env var.
                    LOG.warning(
                        "DEVELOPMENT is Enabled. Bypassing access lookup for user: %s",
                        json_rh_auth)
                    user_access = request.user.access
                else:
                    try:
                        user_access = self._get_access(user)
                    except RbacConnectionError as err:
                        return HttpResponseFailedDependency({
                            "source": "Rbac",
                            "exception": err
                        })
                cache.set(user.uuid, user_access, self.rbac.cache_ttl)
            user.access = user_access
            request.user = user
Ejemplo n.º 7
0
    def process_request(self, request):  # noqa: C901
        """Process request for csrf checks.

        Args:
            request (object): The request object

        """
        connection.set_schema_to_public()

        if is_no_auth(request):
            request.user = User("", "")
            return
        try:
            rh_auth_header, json_rh_auth = extract_header(request, self.header)
        except (KeyError, JSONDecodeError):
            LOG.warning("Could not obtain identity on request.")
            return
        except binascii.Error as error:
            LOG.error("Error decoding authentication header: %s", str(error))
            raise PermissionDenied()

        is_openshift = json_rh_auth.get("entitlements",
                                        {}).get("openshift",
                                                {}).get("is_entitled", False)
        if not is_openshift:
            raise PermissionDenied()

        account = json_rh_auth.get("identity", {}).get("account_number")
        user = json_rh_auth.get("identity", {}).get("user", {})
        username = user.get("username")
        email = user.get("email")
        is_admin = user.get("is_org_admin")
        if username and email and account:
            # Get request ID
            req_id = request.META.get("HTTP_X_RH_INSIGHTS_REQUEST_ID")
            # Check for customer creation & user creation
            query_string = ""
            if request.META["QUERY_STRING"]:
                query_string = "?{}".format(request.META["QUERY_STRING"])
            stmt = (f"{request.method}: {request.path}{query_string}"
                    f" -- ACCOUNT: {account} USER: {username}"
                    f" ORG_ADMIN: {is_admin} REQ_ID: {req_id}")
            LOG.info(stmt)
            try:
                customer = Customer.objects.filter(account_id=account).get()
            except Customer.DoesNotExist:
                customer = IdentityHeaderMiddleware._create_customer(account)
            except OperationalError as err:
                LOG.error("IdentityHeaderMiddleware exception: %s", err)
                DB_CONNECTION_ERRORS_COUNTER.inc()
                return HttpResponseFailedDependency({
                    "source": "Database",
                    "exception": err
                })

            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = IdentityHeaderMiddleware._create_user(
                    username, email, customer, request)

            user.identity_header = {
                "encoded": rh_auth_header,
                "decoded": json_rh_auth
            }
            user.admin = is_admin
            user.req_id = req_id

            cache = caches["rbac"]
            user_access = cache.get(user.uuid)
            if not user_access:
                try:
                    user_access = self._get_access(user)
                except RbacConnectionError as err:
                    return HttpResponseFailedDependency({
                        "source": "Rbac",
                        "exception": err
                    })
                cache.set(user.uuid, user_access, self.rbac.cache_ttl)
            user.access = user_access
            request.user = user
Ejemplo n.º 8
0
    def process_request(self, request):  # noqa: C901
        """Process request for csrf checks.

        Args:
            request (object): The request object

        """
        if is_no_auth(request):
            request.user = User('', '')
            return
        try:
            rh_auth_header, json_rh_auth = extract_header(request, self.header)
        except (KeyError, JSONDecodeError):
            LOG.warning('Could not obtain identity on request.')
            return
        except binascii.Error as error:
            LOG.error('Error decoding authentication header: %s', str(error))
            raise PermissionDenied()

        is_openshift = (json_rh_auth.get('entitlements',
                                         {}).get('openshift',
                                                 {}).get('is_entitled', False))
        if not is_openshift:
            raise PermissionDenied()

        account = json_rh_auth.get('identity', {}).get('account_number')
        user = json_rh_auth.get('identity', {}).get('user', {})
        username = user.get('username')
        email = user.get('email')
        is_admin = user.get('is_org_admin')
        if username and email and account:
            # Check for customer creation & user creation
            query_string = ''
            if request.META['QUERY_STRING']:
                query_string = '?{}'.format(request.META['QUERY_STRING'])
            stmt = (f'API: {request.path}{query_string}'
                    f' -- ACCOUNT: {account} USER: {username}')
            LOG.info(stmt)
            try:
                customer = Customer.objects.filter(account_id=account).get()
            except Customer.DoesNotExist:
                customer = IdentityHeaderMiddleware._create_customer(account)
            except OperationalError as err:
                LOG.error('IdentityHeaderMiddleware exception: %s', err)
                DB_CONNECTION_ERRORS_COUNTER.inc()
                return HttpResponseFailedDependency({
                    'source': 'Database',
                    'exception': err
                })

            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = IdentityHeaderMiddleware._create_user(
                    username, email, customer, request)

            user.identity_header = {
                'encoded': rh_auth_header,
                'decoded': json_rh_auth
            }
            user.admin = is_admin

            cache = caches['rbac']
            user_access = cache.get(user.uuid)
            if not user_access:
                try:
                    user_access = self._get_access(user)
                except RbacConnectionError as err:
                    return HttpResponseFailedDependency({
                        'source': 'Rbac',
                        'exception': err
                    })
                cache.set(user.uuid, user_access, self.rbac.cache_ttl)
            user.access = user_access
            request.user = user