예제 #1
0
    def process_request(self, request):  # pylint: disable=R1710
        """Process request for identity middleware.

        Args:
            request (object): The request object

        """
        # Get request ID
        request.req_id = request.META.get(RH_INSIGHTS_REQUEST_ID)

        if any([
                request.path.startswith(prefix)
                for prefix in settings.INTERNAL_API_PATH_PREFIXES
        ]):
            # This request is for a private API endpoint
            return

        if is_no_auth(request):
            return
        user = User()
        try:
            _, json_rh_auth = extract_header(request, self.header)
            user.username = json_rh_auth.get("identity",
                                             {}).get("user", {})["username"]
            user.account = json_rh_auth.get("identity", {})["account_number"]
            user.admin = json_rh_auth.get("identity",
                                          {}).get("user",
                                                  {}).get("is_org_admin")
            user.system = False
            if not user.admin:
                user.access = IdentityHeaderMiddleware._get_access_for_user()
        except (KeyError, JSONDecodeError):
            request_psk = request.META.get(RH_RBAC_PSK)
            account = request.META.get(RH_RBAC_ACCOUNT)
            client_id = request.META.get(RH_RBAC_CLIENT_ID)
            has_system_auth_headers = request_psk and account and client_id

            if has_system_auth_headers and validate_psk(
                    request_psk, client_id):
                user.username = client_id
                user.account = account
                user.admin = True
                user.system = True
            else:
                logger.error("Could not obtain identity on request.")
                return HttpResponseUnauthorizedRequest()
        except binascii.Error as error:
            logger.error("Could not decode header: %s.", error)
            raise error
        if user.username and user.account:
            request.user = user

            super().process_request(request)
            # We are now in the database context of the tenant
            assert request.tenant
예제 #2
0
    def process_request(self, request):  # pylint: disable=R1710
        """Process request for identity middleware.

        Args:
            request (object): The request object

        """
        # Get request ID
        request.req_id = request.META.get(RH_INSIGHTS_REQUEST_ID)

        if is_no_auth(request):
            return
        user = User()
        try:
            _, json_rh_auth = extract_header(request, self.header)
            user.username = json_rh_auth.get('identity',
                                             {}).get('user', {})['username']
            user.account = json_rh_auth.get('identity', {})['account_number']
            user.admin = json_rh_auth.get('identity',
                                          {}).get('user',
                                                  {}).get('is_org_admin')
            user.system = False
            if not user.admin:
                user.access = IdentityHeaderMiddleware._get_access_for_user()
        except (KeyError, JSONDecodeError):
            request_psk = request.META.get(RH_RBAC_PSK)
            account = request.META.get(RH_RBAC_ACCOUNT)
            client_id = request.META.get(RH_RBAC_CLIENT_ID)
            has_system_auth_headers = request_psk and account and client_id

            if has_system_auth_headers and validate_psk(
                    request_psk, client_id):
                user.username = client_id
                user.account = account
                user.admin = True
                user.system = True
            else:
                logger.error('Could not obtain identity on request.')
                return HttpResponseUnauthorizedRequest()
        except binascii.Error as error:
            logger.error('Could not decode header: %s.', error)
            raise error
        if user.username and user.account:
            request.user = user

            super().process_request(request)
            # We are now in the database context of the tenant
            assert request.tenant
예제 #3
0
    def setUp(self):
        """Set up the internal viewset tests."""
        super().setUp()

        self.client = APIClient()
        self.customer = self._create_customer_data()
        self.internal_request_context = self._create_request_context(
            self.customer, self.user_data, create_customer=False, is_internal=True, create_tenant=True
        )

        self.request = self.internal_request_context["request"]
        user = User()
        user.username = self.user_data["username"]
        user.account = self.customer_data["account_id"]
        self.request.user = user

        with tenant_context(self.tenant):
            self.group = Group(name="System Group", system=True)
            self.group.save()
            self.role = Role.objects.create(name="System Role", description="A role for a group.", system=True)
            self.policy = Policy.objects.create(name="System Policy", group=self.group)
            self.policy.roles.add(self.role)
            self.policy.save()
            self.group.policies.add(self.policy)
            self.group.save()
예제 #4
0
    def setUp(self):
        """Set up the access view tests."""
        super().setUp()
        request = self.request_context["request"]
        user = User()
        user.username = self.user_data["username"]
        user.account = self.customer_data["account_id"]
        request.user = user

        self.access_data = {
            "permission":
            "app:*:*",
            "resourceDefinitions": [{
                "attributeFilter": {
                    "key": "key1",
                    "operation": "equal",
                    "value": "value1"
                }
            }],
        }
        with tenant_context(self.tenant):
            self.principal = Principal(username=self.user_data["username"])
            self.principal.save()
            self.admin_principal = Principal(username="******")
            self.admin_principal.save()
            self.group = Group(name="groupA")
            self.group.save()
            self.group.principals.add(self.principal)
            self.group.save()
예제 #5
0
    def setUp(self):
        """Set up the access view tests."""
        super().setUp()
        request = self.request_context['request']
        user = User()
        user.username = self.user_data['username']
        user.account = self.customer_data['account_id']
        request.user = user

        self.access_data = {
            'permission':
            'app:*:*',
            'resourceDefinitions': [{
                'attributeFilter': {
                    'key': 'key1',
                    'operation': 'equal',
                    'value': 'value1'
                }
            }]
        }
        with tenant_context(self.tenant):
            self.principal = Principal(username=self.user_data['username'])
            self.principal.save()
            self.admin_principal = Principal(username="******")
            self.admin_principal.save()
            self.group = Group(name='groupA')
            self.group.save()
            self.group.principals.add(self.principal)
            self.group.save()
예제 #6
0
    def setUp(self):
        """Set up the permission viewset tests."""
        super().setUp()
        request = self.request_context["request"]
        user = User()
        user.username = self.user_data["username"]
        user.account = self.customer_data["account_id"]
        request.user = user

        self.display_fields = {
            "application", "resource_type", "verb", "permission"
        }

        with tenant_context(self.tenant):
            self.permissionA = Permission.objects.create(
                permission="rbac:roles:read")
            self.permissionB = Permission.objects.create(permission="rbac:*:*")
            self.permissionC = Permission.objects.create(permission="acme:*:*")
            self.permissionD = Permission.objects.create(
                permission="acme:*:write")
            self.permissionE = Permission.objects.create(permission="*:*:*")
            self.permissionF = Permission.objects.create(permission="*:bar:*")
            self.permissionG = Permission.objects.create(permission="*:*:baz")
            self.permissionH = Permission.objects.create(
                permission="*:bar:baz")
            self.permissionI = Permission.objects.create(
                permission="foo:bar:*", description="Description test.")
예제 #7
0
    def setUp(self):
        """Set up the group viewset tests."""
        super().setUp()
        request = self.request_context["request"]
        user = User()
        user.username = self.user_data["username"]
        user.account = self.customer_data["account_id"]
        request.user = user
        self.dummy_role_id = uuid4()

        with tenant_context(self.tenant):
            self.principal = Principal(username=self.user_data["username"])
            self.principal.save()
            self.principalB = Principal(username="******")
            self.principalB.save()
            self.principalC = Principal(
                username="******")
            self.principalC.save()
            self.group = Group(name="groupA")
            self.group.save()
            self.role = Role.objects.create(name="roleA",
                                            description="A role for a group.")
            self.policy = Policy.objects.create(name="policyA",
                                                group=self.group)
            self.policy.roles.add(self.role)
            self.policy.save()
            self.group.policies.add(self.policy)
            self.group.principals.add(self.principal, self.principalB)
            self.group.save()

            self.defGroup = Group(name="groupDef",
                                  platform_default=True,
                                  system=True)
            self.defGroup.save()
            self.defGroup.principals.add(self.principal)
            self.defGroup.save()

            self.emptyGroup = Group(name="groupE")
            self.emptyGroup.save()

            self.groupB = Group.objects.create(name="groupB")
            self.groupB.principals.add(self.principal)
            self.policyB = Policy.objects.create(name="policyB",
                                                 group=self.groupB)
            self.roleB = Role.objects.create(name="roleB")
            self.policyB.roles.add(self.roleB)
            self.policyB.save()

            # role that's not assigned to principal
            self.roleOrphan = Role.objects.create(name="roleOrphan")

            # group that associates with multipal roles
            self.groupMultiRole = Group.objects.create(name="groupMultiRole")
            self.policyMultiRole = Policy.objects.create(
                name="policyMultiRole")
            self.policyMultiRole.roles.add(self.role)
            self.policyMultiRole.roles.add(self.roleB)
            self.groupMultiRole.policies.add(self.policyMultiRole)
예제 #8
0
    def setUp(self):
        """Set up the group viewset tests."""
        super().setUp()
        request = self.request_context['request']
        user = User()
        user.username = self.user_data['username']
        user.account = self.customer_data['account_id']
        request.user = user
        self.dummy_role_id = uuid4()

        with tenant_context(self.tenant):
            self.principal = Principal(username=self.user_data['username'])
            self.principal.save()
            self.principalB = Principal(username='******')
            self.principalB.save()
            self.principalC = Principal(
                username='******')
            self.principalC.save()
            self.group = Group(name='groupA')
            self.group.save()
            self.role = Role.objects.create(name='roleA',
                                            description='A role for a group.')
            self.policy = Policy.objects.create(name='policyA',
                                                group=self.group)
            self.policy.roles.add(self.role)
            self.policy.save()
            self.group.policies.add(self.policy)
            self.group.principals.add(self.principal, self.principalB)
            self.group.save()

            self.defGroup = Group(name='groupDef',
                                  platform_default=True,
                                  system=True)
            self.defGroup.save()
            self.defGroup.principals.add(self.principal)
            self.defGroup.save()

            self.emptyGroup = Group(name='groupE')
            self.emptyGroup.save()

            self.groupB = Group.objects.create(name='groupB')
            self.groupB.principals.add(self.principal)
            self.policyB = Policy.objects.create(name='policyB',
                                                 group=self.groupB)
            self.roleB = Role.objects.create(name='roleB')
            self.policyB.roles.add(self.roleB)
            self.policyB.save()

            # role that's not assigned to principal
            self.roleOrphan = Role.objects.create(name='roleOrphan')

            # group that associates with multipal roles
            self.groupMultiRole = Group.objects.create(name='groupMultiRole')
            self.policyMultiRole = Policy.objects.create(
                name='policyMultiRole')
            self.policyMultiRole.roles.add(self.role)
            self.policyMultiRole.roles.add(self.roleB)
            self.groupMultiRole.policies.add(self.policyMultiRole)
예제 #9
0
    def setUp(self):
        """Set up the principal viewset tests."""
        super().setUp()
        request = self.request_context["request"]
        user = User()
        user.username = self.user_data["username"]
        user.account = self.customer_data["account_id"]
        request.user = user

        with tenant_context(self.tenant):
            self.principal = Principal(username="******")
            self.principal.save()
예제 #10
0
    def setUp(self):
        """Set up the principal viewset tests."""
        super().setUp()
        request = self.request_context['request']
        user = User()
        user.username = self.user_data['username']
        user.account = self.customer_data['account_id']
        request.user = user

        with tenant_context(self.tenant):
            self.principal = Principal(username='******')
            self.principal.save()
예제 #11
0
 def setUp(self):
     """Set up middleware tests."""
     super().setUp()
     self.user_data = self._create_user_data()
     self.customer = self._create_customer_data()
     self.schema_name = create_schema_name(self.customer["account_id"])
     self.request_context = self._create_request_context(
         self.customer, self.user_data, create_customer=False)
     self.request = self.request_context["request"]
     self.request.path = "/api/v1/providers/"
     user = User()
     user.username = self.user_data["username"]
     user.account = self.customer_data["account_id"]
     self.request.user = user
예제 #12
0
    def setUp(self):
        """Set up the policy viewset tests."""
        super().setUp()
        request = self.request_context['request']
        user = User()
        user.username = self.user_data['username']
        user.account = self.customer_data['account_id']
        request.user = user

        with tenant_context(self.tenant):
            self.principal = Principal(username=self.user_data['username'])
            self.principal.save()
            self.group = Group(name='groupA')
            self.group.save()
            self.group.principals.add(self.principal)
            self.group.save()
예제 #13
0
    def setUp(self):
        """Set up the policy viewset tests."""
        super().setUp()
        request = self.request_context["request"]
        user = User()
        user.username = self.user_data["username"]
        user.account = self.customer_data["account_id"]
        request.user = user

        with tenant_context(self.tenant):
            self.principal = Principal(username=self.user_data["username"])
            self.principal.save()
            self.group = Group(name="groupA")
            self.group.save()
            self.group.principals.add(self.principal)
            self.group.save()
            Permission.objects.create(permission="app:*:*")
예제 #14
0
    def setUp(self):
        """Set up the role viewset tests."""
        super().setUp()
        request = self.request_context['request']
        user = User()
        user.username = self.user_data['username']
        user.account = self.customer_data['account_id']
        request.user = user

        sys_role_config = {'name': 'system_role', 'system': True}

        def_role_config = {'name': 'default_role', 'platform_default': True}

        self.display_fields = {
            'applications', 'description', 'uuid', 'name', 'system', 'created',
            'policyCount', 'accessCount', 'modified', 'platform_default'
        }

        with tenant_context(self.tenant):
            self.principal = Principal(username=self.user_data['username'])
            self.principal.save()
            self.policy = Policy.objects.create(name='policyA')
            self.group = Group(name='groupA', description='groupA description')
            self.group.save()
            self.group.principals.add(self.principal)
            self.group.policies.add(self.policy)
            self.group.save()

            self.sysRole = Role(**sys_role_config)
            self.sysRole.save()

            self.defRole = Role(**def_role_config)
            self.defRole.save()
            self.defRole.save()

            self.policy.roles.add(self.defRole, self.sysRole)
            self.policy.save()

            self.access = Access.objects.create(permission='app:*:*',
                                                role=self.defRole)
예제 #15
0
    def setUp(self):
        """Set up the role viewset tests."""
        super().setUp()
        request = self.request_context["request"]
        user = User()
        user.username = self.user_data["username"]
        user.account = self.customer_data["account_id"]
        request.user = user

        sys_role_config = {
            "name": "system_role",
            "display_name": "system_display",
            "system": True
        }

        def_role_config = {
            "name": "default_role",
            "display_name": "default_display",
            "platform_default": True
        }

        self.display_fields = {
            "applications",
            "description",
            "uuid",
            "name",
            "display_name",
            "system",
            "created",
            "policyCount",
            "accessCount",
            "modified",
            "platform_default",
        }

        with tenant_context(self.tenant):
            self.principal = Principal(username=self.user_data["username"])
            self.principal.save()
            self.policy = Policy.objects.create(name="policyA")
            self.group = Group(name="groupA", description="groupA description")
            self.group.save()
            self.group.principals.add(self.principal)
            self.group.policies.add(self.policy)
            self.group.save()

            self.sysRole = Role(**sys_role_config)
            self.sysRole.save()

            self.defRole = Role(**def_role_config)
            self.defRole.save()
            self.defRole.save()

            self.policy.roles.add(self.defRole, self.sysRole)
            self.policy.save()

            self.permission = Permission.objects.create(permission="app:*:*")
            self.permission2 = Permission.objects.create(permission="app2:*:*")
            self.access = Access.objects.create(permission=self.permission,
                                                role=self.defRole)
            self.access2 = Access.objects.create(permission=self.permission2,
                                                 role=self.defRole)

            self.access3 = Access.objects.create(permission=self.permission2,
                                                 role=self.sysRole)
            Permission.objects.create(permission="cost-management:*:*")

        # Create permission in public schema
        with tenant_context(Tenant.objects.get(schema_name="public")):
            Permission.objects.create(permission="cost-management:*:*")
            Permission.objects.create(permission="app:*:*")
            Permission.objects.create(permission="app2:*:*")
예제 #16
0
    def process_request(self, request):  # pylint: disable=R1710
        """Process request for identity middleware.

        Args:
            request (object): The request object

        """
        # Get request ID
        request.req_id = request.META.get(RH_INSIGHTS_REQUEST_ID)

        if any([request.path.startswith(prefix) for prefix in settings.INTERNAL_API_PATH_PREFIXES]):
            # This request is for a private API endpoint
            return

        if is_no_auth(request):
            return
        user = User()
        try:
            _, json_rh_auth = extract_header(request, self.header)
            user.account = json_rh_auth.get("identity", {})["account_number"]
            user_info = json_rh_auth.get("identity", {}).get("user", {})
            user.username = user_info["username"]
            user.admin = user_info.get("is_org_admin")
            user.internal = user_info.get("is_internal")
            user.user_id = user_info.get("user_id")
            user.system = False
            if not user.admin:
                try:
                    schema_name = create_schema_name(user.account)
                    tenant = Tenant.objects.filter(schema_name=schema_name).get()
                except Tenant.DoesNotExist:
                    request.user = user
                    tenant = self.get_tenant(model=None, hostname=None, request=request)

                user.access = IdentityHeaderMiddleware._get_access_for_user(user.username, tenant)
            # Cross account request check
            internal = json_rh_auth.get("identity", {}).get("internal", {})
            if internal != {}:
                cross_account = internal.get("cross_access", False)
                if cross_account:
                    if not (user.internal and user_info.get("email").endswith("@redhat.com")):
                        logger.error("Cross accout request permission denied. Requester is not internal user.")
                        return HttpResponseUnauthorizedRequest()
                    user.username = f"{user.account}-{user.user_id}"
        except (KeyError, JSONDecodeError):
            request_psk = request.META.get(RH_RBAC_PSK)
            account = request.META.get(RH_RBAC_ACCOUNT)
            client_id = request.META.get(RH_RBAC_CLIENT_ID)
            has_system_auth_headers = request_psk and account and client_id

            if has_system_auth_headers and validate_psk(request_psk, client_id):
                user.username = client_id
                user.account = account
                user.admin = True
                user.system = True
            else:
                logger.error("Could not obtain identity on request.")
                return HttpResponseUnauthorizedRequest()
        except binascii.Error as error:
            logger.error("Could not decode header: %s.", error)
            raise error
        if user.username and user.account:
            request.user = user

            super().process_request(request)
            # We are now in the database context of the tenant
            assert request.tenant