def get_snapshots_data(self):
        """
        Getter used by SnapshotsTable model.
        """
        user_id = os_auth.get_user(self.request).id
        self.cache_user(user_id)
        owner = os_auth.get_user(self.request).project_id
        filters = {"owner": owner}

        snapshots_list = list()

        try:
            snapshots = api.glance.image_list_detailed(self.request)
            for snapshot in snapshots[0]:
                if snapshot.properties.get("image_type") == "snapshot":
                    if (all(
                            getattr(snapshot, attr) == value
                            for (attr, value) in filters.items())
                            and snapshot.properties.get("user_id") == user_id):
                        snapshot.user = self.users_cache[user_id]
                        snapshots_list.append(snapshot)

            return snapshots_list

        except Exception:
            snapshots_list = []
            exceptions.handle(self.request, _("Unable to retrieve snapshots"))
    def has_permission(self, request, instance_id):
        """
        Check if user have permission to access instances
        """
        instance = api.nova.server_get(request, instance_id)
        user_id = os_auth.get_user(request).id
        tenant_id = os_auth.get_user(request).project_id
        roles = [str(role["name"]) for role in os_auth.get_user(request).roles]

        if instance.tenant_id == tenant_id and (
                instance.user_id == user_id
                or settings.PROJECT_MANAGER_ROLE in roles):
            return True

        return False
Exemple #3
0
    def test_add_allowed_address_pair_button_disabled_to_other_tenant(self):
        # Current user tenant_id is 1 so select port whose tenant_id is
        # other than 1 for checking "Add Allowed Address Pair" button is not
        # displayed on the screen.
        user = auth_utils.get_user(self.request)

        # select port such that tenant_id is different from user's tenant_id.
        port = [p for p in self.ports.list()
                if p.tenant_id != user.tenant_id][0]

        self._stub_is_extension_supported({
            'allowed-address-pairs': False,
            'mac-learning': False
        })

        with mock.patch('openstack_auth.utils.get_user', return_value=user):
            url = reverse(
                'horizon:project:networks:ports:addallowedaddresspairs',
                args=[port.id])
            classes = 'btn data-table-action btn-default ajax-modal'
            link_name = "Add Allowed Address Pair"

            expected_string = \
                '<a id="allowed_address_pairs__action_AddAllowedAddressPair" ' \
                'class="%s" href="%s" title="Add Allowed Address Pair">' \
                '<span class="fa fa-plus"></span> %s</a>' \
                % (classes, url, link_name)

            res = self.client.get(
                reverse('horizon:project:networks:ports:detail',
                        args=[port.id]))

            self.assertNotIn(expected_string,
                             res.context_data['tab_group'].render())
Exemple #4
0
    def test_delete_address_pair_button_disabled_to_other_tenant(self):
        # Current user tenant_id is 1 so select port whose tenant_id is
        # other than 1 for checking "Delete Allowed Address Pair" button is
        # not displayed on the screen.
        user = auth_utils.get_user(self.request)

        # select port such that tenant_id is different from user's tenant_id.
        port = [p for p in self.ports.list()
                if p.tenant_id != user.tenant_id][0]

        self._stub_is_extension_supported({
            'allowed-address-pairs': False,
            'mac-learning': False
        })

        with mock.patch('openstack_auth.utils.get_user', return_value=user):
            classes = 'data-table-action btn-danger btn'

            expected_string = \
                '<button data-batch-action="true" ' \
                'id="allowed_address_pairs__action_delete" ' \
                'class="%s" name="action" help_text="This action cannot be ' \
                'undone." type="submit" ' \
                'value="allowed_address_pairs__delete">' \
                '<span class="fa fa-trash"></span>' \
                ' Delete</button>' % (classes)

            res = self.client.get(
                reverse('horizon:project:networks:ports:detail',
                        args=[port.id]))

            self.assertNotIn(expected_string,
                             res.context_data['tab_group'].render())
def has_role(request, name):
    """
    Check if the current user has a given role
    """
    for role in os_auth.get_user(request).roles:
        if role["name"] == name:
            return True

    return False
 def get_user_role(self, user_id):
     try:
         user = auth_utils.get_user(self.request)
     except Exception:
         redirect = self.get_redirect_url()
         exceptions.handle(self.request,
                           _('Unable to retrieve role list.'),
                           redirect=redirect)
     role_names = [role['name'] for role in user.roles]
     return role_names
    def allowed(self, request, user_alerts=None):
        """
        Define if the current user is allowed to mark alerts as read.
        """
        roles = os_auth.get_user(request).roles

        for r in roles:
            if r["name"] == settings.PROJECT_MANAGER_ROLE:
                return True

        return False
Exemple #8
0
def check(actions, request, target={}):
    """Check user permission.

    Check if the user has permission to the action according
    to policy setting.

    :param actions: list of scope and action to do policy checks on,
        the composition of which is (scope, action)

        * scope: service type managing the policy for action

        * action: string representing the action to be checked

            this should be colon separated for clarity.
            i.e.

                | compute:create_instance
                | compute:attach_volume
                | volume:attach_volume

        for a policy action that requires a single action, actions
        should look like

            | "(("compute", "compute:create_instance"),)"

        for a multiple action check, actions should look like
            | "(("identity", "identity:list_users"),
            |   ("identity", "identity:list_roles"))"

    :param request: django http request object. If not specified, credentials
                    must be passed.
    :param target: dictionary representing the object of the action
                      for object creation this should be a dictionary
                      representing the location of the object e.g.
                      {'tenant_id': object.tenant_id}
    :returns: boolean if the user has permission or not for the actions.
    """
    user = auth_utils.get_user(request)
    credentials = _user_to_credentials(request, user)

    enforcer = _get_enforcer()

    for action in actions:
        scope, action = action[0], action[1]
        if scope in enforcer:
            # if any check fails return failure
            if not enforcer[scope].enforce(action, target, credentials):
                return False
        # if no policy for scope, allow action, underlying API will
        # ultimately block the action if not permitted, treat as though
        # allowed
    return True
    def delete(self, request, obj_id):
        """
        Action called to define if the current user is allowed to mark alerts as read.
        """
        gerenuk_config = gerenuk.Config()
        gerenuk_config.load(settings.GERENUK_CONF)
        gerenuk_api = gerenuk.api.AlertsAPI(gerenuk_config)

        project = os_auth.get_user(request).project_id
        unread_alerts = gerenuk_api.get_unread_alerts(project)
        read_ids = list()

        for i in range(0, min(1, len(unread_alerts))):
            read_ids.append(unread_alerts[i]["id"])

        gerenuk_api.tag_alerts_as_read([int(obj_id)])
    def get_instances_data(self):
        """
        Getter used by InstancesTable model.
        """
        user_id = os_auth.get_user(self.request).id
        self.cache_user(user_id)

        instances_list = []
        instances, self._more = api.nova.server_list(self.request)

        for instance in instances:
            if hasattr(instance, "user_id"):
                if (user_id == instance.user_id):
                    instance.user = self.users_cache[user_id]
                    instances_list.append(instance)

        return instances_list
Exemple #11
0
def check(actions, request, target={}):
    """
    Check if the user has permission to the action according
    to policy setting.

    :param actions: list of scope and action to do policy checks on, the
                    composition of which is (scope, action)

        scope: service type managing the policy for action
        action: string representing the action to be checked

            this should be colon separated for clarity.
            i.e. compute:create_instance
                 compute:attach_volume
                 volume:attach_volume

       for a policy action that requires a single action:
           actions should look like "(("compute", "compute:create_instance"),)"
       for a multiple action check:
           actions should look like "(("identity", "identity:list_users"),
                                      ("identity", "identity:list_roles"))"

    :param request: django http request object. If not specified, credentials
                    must be passed.
    :param target: dictionary representing the object of the action
                      for object creation this should be a dictionary
                      representing the location of the object e.g.
                      {'tenant_id': object.tenant_id}
    :returns: boolean if the user has permission or not for the actions.
    """
    user = auth_utils.get_user(request)
    credentials = _user_to_credentials(request, user)

    enforcer = _get_enforcer()

    for action in actions:
        scope, action = action[0], action[1]
        if scope in enforcer:
            # if any check fails return failure
            if not enforcer[scope].enforce(action, target, credentials):
                return False
        # if no policy for scope, allow action, underlying API will
        # ultimately block the action if not permitted, treat as though
        # allowed
    return True
Exemple #12
0
 def test_check_credentials_default(self):
     policy.reset()
     enforcer = policy._get_enforcer()
     scope = enforcer['with_default']
     user = utils.get_user()
     credentials = policy._user_to_credentials(user)
     target = {
         'project_id': user.project_id,
         'tenant_id': user.project_id,
         'user_id': user.id,
         'domain_id': user.user_domain_id,
         'user.domain_id': user.user_domain_id,
         'group.domain_id': user.user_domain_id,
         'project.domain_id': user.user_domain_id,
     }
     is_valid = policy._check_credentials(scope, 'action', target,
                                          credentials)
     self.assertFalse(is_valid)
Exemple #13
0
 def test_check_credentials_default(self):
     policy.reset()
     enforcer = policy._get_enforcer()
     scope = enforcer['with_default']
     user = utils.get_user()
     credentials = policy._user_to_credentials(user)
     target = {
         'project_id': user.project_id,
         'tenant_id': user.project_id,
         'user_id': user.id,
         'domain_id': user.user_domain_id,
         'user.domain_id': user.user_domain_id,
         'group.domain_id': user.user_domain_id,
         'project.domain_id': user.user_domain_id,
     }
     is_valid = policy._check_credentials(scope, 'action', target,
                                          credentials)
     self.assertFalse(is_valid)
    def get_data(self):
        """
        Getter used by the InstancesTable model
        """
        instances_list = []
        instances, self._more = api.nova.server_list(self.request)
        users_cache = dict()

        # Get current user information
        current_user_id = os_auth.get_user(self.request).id

        # Add allowed instances to result list
        for instance in instances:
            if (hasattr(instance, "user_id")
                    and instance.user_id == current_user_id):
                # Look for unkonw user
                user_id = instance.user_id
                self.cache_user(user_id)

                # Get info
                info = self.get_statistics(instance.id)
                instance.user = self.users_cache[user_id]

                try:
                    instance.vcpu = str(
                        float(info[instance.id]["vcpu"]
                              ["weekly"])) + "% (last week)"
                except KeyError:
                    try:
                        instance.vcpu = str(
                            float(info[instance.id]["vcpu"]
                                  ["daily"])) + "% (last day)"
                    except KeyError:
                        try:
                            instance.vcpu = str(
                                float(info[instance.id]["vcpu"]
                                      ["hourly"])) + "% (last hour)"
                        except KeyError:
                            instance.vcpu = "N/A"

                instances_list.append(instance)

        return instances_list
    def get_volumes_data(self):
        """
        Getter used by VolumesTable model.
        """
        user_id = os_auth.get_user(self.request).id
        self.cache_user(user_id)
        filters = {"user_id": user_id}

        cinder = api.cinder.cinderclient(self.request)
        unfiltred_volumes = cinder.volumes.list()
        volumes_list = list()

        for volume in unfiltred_volumes:
            if all(
                    getattr(volume, attr) == value
                    for (attr, value) in filters.items()):
                volume.user = self.users_cache[user_id]
                volumes_list.append(volume)

        return volumes_list
Exemple #16
0
    def dispatch(self, request, url):
        if not url:
            url = '/'

        if request.method not in self.http_method_names:
            return http.HttpResponseNotAllowed(request.method)

        if not self._can_access_kibana():
            error_msg = (_('User %s does not have sufficient '
                           'privileges to access Kibana')
                         % auth_utils.get_user(request))
            LOG.error(error_msg)
            return http.HttpResponseForbidden(content=error_msg)

        # passing kbn version explicitly for kibana >= 4.3.x
        headers = {
            'X-Auth-Token': request.user.token.id,
            'kbn-version': request.META.get('HTTP_KBN_VERSION', '')
        }

        return self.read(request.method, url, request.body, headers)
Exemple #17
0
    def dispatch(self, request, url):
        if not url:
            url = '/'

        if request.method not in self.http_method_names:
            return http.HttpResponseNotAllowed(request.method)

        if not self._can_access_kibana():
            error_msg = (_('User %s does not have sufficient '
                           'privileges to access Kibana') %
                         auth_utils.get_user(request))
            LOG.error(error_msg)
            return http.HttpResponseForbidden(content=error_msg)

        # passing kbn version explicitly for kibana >= 4.3.x
        headers = {
            'X-Auth-Token': request.user.token.id,
            'kbn-version': request.META.get('HTTP_KBN_VERSION', ''),
            'Cookie': request.META.get('HTTP_COOKIE', '')
        }

        return self.read(request.method, url, request.body, headers)
    def _add_project_user_role(self, request, project_id):
        try:
            role_list = {role.name: role.id
                         for role in project_identity.role_list(request)}

            user = auth_utils.get_user(request)
            role_name_list = [role['name'] for role in user.roles]

            for role_name in role_name_list:
                if role_name in getattr(nec_set,
                                        'DISINHERITED_ROLES', []):
                    continue

                project_identity.add_project_user_role(
                    request,
                    project=project_id,
                    user=user,
                    role=role_list.get(role_name))
            return True
        except Exception:
            exceptions.handle(request, ignore=True)
            return False
        finally:
            auth_utils.remove_project_cache(request.user.token.id)
Exemple #19
0
def check(actions, request, target=None):
    """Check user permission.

    Check if the user has permission to the action according
    to policy setting.

    :param actions: list of scope and action to do policy checks on,
        the composition of which is (scope, action). Multiple actions
        are treated as a logical AND.

        * scope: service type managing the policy for action

        * action: string representing the action to be checked

            this should be colon separated for clarity.
            i.e.

                | compute:create_instance
                | compute:attach_volume
                | volume:attach_volume

        for a policy action that requires a single action, actions
        should look like

            | "(("compute", "compute:create_instance"),)"

        for a multiple action check, actions should look like
            | "(("identity", "identity:list_users"),
            |   ("identity", "identity:list_roles"))"

    :param request: django http request object. If not specified, credentials
                    must be passed.
    :param target: dictionary representing the object of the action
                      for object creation this should be a dictionary
                      representing the location of the object e.g.
                      {'project_id': object.project_id}
    :returns: boolean if the user has permission or not for the actions.
    """
    if target is None:
        target = {}
    user = auth_utils.get_user(request)

    # Several service policy engines default to a project id check for
    # ownership. Since the user is already scoped to a project, if a
    # different project id has not been specified use the currently scoped
    # project's id.
    #
    # The reason is the operator can edit the local copies of the service
    # policy file. If a rule is removed, then the default rule is used. We
    # don't want to block all actions because the operator did not fully
    # understand the implication of editing the policy file. Additionally,
    # the service APIs will correct us if we are too permissive.
    if target.get('project_id') is None:
        target['project_id'] = user.project_id
    if target.get('tenant_id') is None:
        target['tenant_id'] = target['project_id']
    # same for user_id
    if target.get('user_id') is None:
        target['user_id'] = user.id

    domain_id_keys = [
        'domain_id',
        'project.domain_id',
        'user.domain_id',
        'group.domain_id'
    ]
    # populates domain id keys with user's current domain id
    for key in domain_id_keys:
        if target.get(key) is None:
            target[key] = user.user_domain_id

    credentials = _user_to_credentials(user)
    domain_credentials = _domain_to_credentials(request, user)
    # if there is a domain token use the domain_id instead of the user's domain
    if domain_credentials:
        credentials['domain_id'] = domain_credentials.get('domain_id')

    enforcer = _get_enforcer()

    for action in actions:
        scope, action = action[0], action[1]
        if scope in enforcer:
            # this is for handling the v3 policy file and will only be
            # needed when a domain scoped token is present
            if scope == 'identity' and domain_credentials:
                # use domain credentials
                if not _check_credentials(enforcer[scope],
                                          action,
                                          target,
                                          domain_credentials):
                    return False

            # use project credentials
            if not _check_credentials(enforcer[scope],
                                      action, target, credentials):
                return False

        # if no policy for scope, allow action, underlying API will
        # ultimately block the action if not permitted, treat as though
        # allowed
    return True
Exemple #20
0
def check(actions, request, target=None):
    """Check user permission.

    Check if the user has permission to the action according
    to policy setting.

    :param actions: list of scope and action to do policy checks on,
        the composition of which is (scope, action)

        * scope: service type managing the policy for action

        * action: string representing the action to be checked

            this should be colon separated for clarity.
            i.e.

                | compute:create_instance
                | compute:attach_volume
                | volume:attach_volume

        for a policy action that requires a single action, actions
        should look like

            | "(("compute", "compute:create_instance"),)"

        for a multiple action check, actions should look like
            | "(("identity", "identity:list_users"),
            |   ("identity", "identity:list_roles"))"

    :param request: django http request object. If not specified, credentials
                    must be passed.
    :param target: dictionary representing the object of the action
                      for object creation this should be a dictionary
                      representing the location of the object e.g.
                      {'project_id': object.project_id}
    :returns: boolean if the user has permission or not for the actions.
    """
    if target is None:
        target = {}
    user = auth_utils.get_user(request)

    # Several service policy engines default to a project id check for
    # ownership. Since the user is already scoped to a project, if a
    # different project id has not been specified use the currently scoped
    # project's id.
    #
    # The reason is the operator can edit the local copies of the service
    # policy file. If a rule is removed, then the default rule is used. We
    # don't want to block all actions because the operator did not fully
    # understand the implication of editing the policy file. Additionally,
    # the service APIs will correct us if we are too permissive.
    if target.get('project_id') is None:
        target['project_id'] = user.project_id
    # same for user_id
    if target.get('user_id') is None:
        target['user_id'] = user.id
    # same for domain_id
    if target.get('domain_id') is None:
        target['domain_id'] = user.domain_id

    credentials = _user_to_credentials(request, user)

    enforcer = _get_enforcer()

    for action in actions:
        scope, action = action[0], action[1]
        if scope in enforcer:
            # if any check fails return failure
            if not enforcer[scope].enforce(action, target, credentials):
                # to match service implementations, if a rule is not found,
                # use the default rule for that service policy
                #
                # waiting to make the check because the first call to
                # enforce loads the rules
                if action not in enforcer[scope].rules:
                    if not enforcer[scope].enforce('default', target,
                                                   credentials):
                        return False
                else:
                    return False
        # if no policy for scope, allow action, underlying API will
        # ultimately block the action if not permitted, treat as though
        # allowed
    return True
Exemple #21
0
def check(actions, request, target=None):
    """Check user permission.

    Check if the user has permission to the action according
    to policy setting.

    :param actions: list of scope and action to do policy checks on,
        the composition of which is (scope, action). Multiple actions
        are treated as a logical AND.

        * scope: service type managing the policy for action

        * action: string representing the action to be checked

            this should be colon separated for clarity.
            i.e.

                | compute:create_instance
                | compute:attach_volume
                | volume:attach_volume

        for a policy action that requires a single action, actions
        should look like

            | "(("compute", "compute:create_instance"),)"

        for a multiple action check, actions should look like
            | "(("identity", "identity:list_users"),
            |   ("identity", "identity:list_roles"))"

    :param request: django http request object. If not specified, credentials
                    must be passed.
    :param target: dictionary representing the object of the action
                      for object creation this should be a dictionary
                      representing the location of the object e.g.
                      {'project_id': object.project_id}
    :returns: boolean if the user has permission or not for the actions.
    """
    if target is None:
        target = {}
    user = auth_utils.get_user(request)

    # Several service policy engines default to a project id check for
    # ownership. Since the user is already scoped to a project, if a
    # different project id has not been specified use the currently scoped
    # project's id.
    #
    # The reason is the operator can edit the local copies of the service
    # policy file. If a rule is removed, then the default rule is used. We
    # don't want to block all actions because the operator did not fully
    # understand the implication of editing the policy file. Additionally,
    # the service APIs will correct us if we are too permissive.
    if target.get('project_id') is None:
        target['project_id'] = user.project_id
    if target.get('tenant_id') is None:
        target['tenant_id'] = target['project_id']
    # same for user_id
    if target.get('user_id') is None:
        target['user_id'] = user.id

    domain_id_keys = [
        'domain_id', 'project.domain_id', 'user.domain_id', 'group.domain_id'
    ]
    # populates domain id keys with user's current domain id
    for key in domain_id_keys:
        if target.get(key) is None:
            target[key] = user.user_domain_id

    credentials = _user_to_credentials(user)
    domain_credentials = _domain_to_credentials(request, user)
    # if there is a domain token use the domain_id instead of the user's domain
    if domain_credentials:
        credentials['domain_id'] = domain_credentials.get('domain_id')

    enforcer = _get_enforcer()

    for action in actions:
        scope, action = action[0], action[1]
        if scope in enforcer:
            # this is for handling the v3 policy file and will only be
            # needed when a domain scoped token is present
            if scope == 'identity' and domain_credentials:
                # use domain credentials
                if not _check_credentials(enforcer[scope], action, target,
                                          domain_credentials):
                    return False

            # use project credentials
            if not _check_credentials(enforcer[scope], action, target,
                                      credentials):
                return False

        # if no policy for scope, allow action, underlying API will
        # ultimately block the action if not permitted, treat as though
        # allowed
    return True
def region_list(request):
    return auth_utils.get_user(request).available_services_regions
Exemple #23
0
 def post(self, *args, **kwargs):
     req = super(RequestFactoryWithMessages, self).post(*args, **kwargs)
     req.user = utils.get_user(req)
     req.session = []
     req._messages = default_storage(req)
     return req
Exemple #24
0
def check(actions, request, target={}):
    """Check user permission.

    Check if the user has permission to the action according
    to policy setting.

    :param actions: list of scope and action to do policy checks on,
        the composition of which is (scope, action)

        * scope: service type managing the policy for action

        * action: string representing the action to be checked

            this should be colon separated for clarity.
            i.e.

                | compute:create_instance
                | compute:attach_volume
                | volume:attach_volume

        for a policy action that requires a single action, actions
        should look like

            | "(("compute", "compute:create_instance"),)"

        for a multiple action check, actions should look like
            | "(("identity", "identity:list_users"),
            |   ("identity", "identity:list_roles"))"

    :param request: django http request object. If not specified, credentials
                    must be passed.
    :param target: dictionary representing the object of the action
                      for object creation this should be a dictionary
                      representing the location of the object e.g.
                      {'tenant_id': object.tenant_id}
    :returns: boolean if the user has permission or not for the actions.
    """
    user = auth_utils.get_user(request)

    # Several service policy engines default to a project id check for
    # ownership. Since the user is already scoped to a project, if a
    # different project id has not been specified use the currently scoped
    # project's id.
    #
    # The reason is the operator can edit the local copies of the service
    # policy file. If a rule is removed, then the default rule is used. We
    # don't want to block all actions because the operator did not fully
    # understand the implication of editing the policy file. Additionally,
    # the service APIs will correct us if we are too permissive.
    if 'project_id' not in target:
        target['project_id'] = user.project_id
    # same for user_id
    if 'user_id' not in target:
        target['user_id'] = user.id

    credentials = _user_to_credentials(request, user)

    enforcer = _get_enforcer()

    for action in actions:
        scope, action = action[0], action[1]
        if scope in enforcer:
            # if any check fails return failure
            if not enforcer[scope].enforce(action, target, credentials):
                # to match service implementations, if a rule is not found,
                # use the default rule for that service policy
                #
                # waiting to make the check because the first call to
                # enforce loads the rules
                if action not in enforcer[scope].rules:
                    if not enforcer[scope].enforce('default',
                                                   target, credentials):
                        return False
                else:
                    return False
        # if no policy for scope, allow action, underlying API will
        # ultimately block the action if not permitted, treat as though
        # allowed
    return True
Exemple #25
0
 def _get_user_roles(self):
     user = auth_utils.get_user(self.request)
     return [role['name'] for role in user.roles]
Exemple #26
0
 def post(self, *args, **kwargs):
     req = super(RequestFactoryWithMessages, self).post(*args, **kwargs)
     req.user = utils.get_user(req)
     req.session = []
     req._messages = default_storage(req)
     return req
Exemple #27
0
 def post(self, *args, **kwargs):
     req = super().post(*args, **kwargs)
     req.user = utils.get_user(req)
     req.session = []
     req._messages = default_storage(req)
     return req