Beispiel #1
0
    def GET(self):

        query_manager = managers.user_query_manager()
        users = query_manager.find_all()
        self._process_users(users)

        return self.ok(users)
Beispiel #2
0
    def GET(self):

        role_query_manager = managers.role_query_manager()
        user_query_manager = managers.user_query_manager()
        permissions_manager = managers.permission_manager()
        roles = role_query_manager.find_all()
        for role in roles:
            role['users'] = [
                u['login'] for u in
                user_query_manager.find_users_belonging_to_role(role['id'])
            ]

            resource_permission = {}
            # isolate schema change
            if role['permissions']:
                for item in role['permissions']:
                    resource = item['resource']
                    operations = item.get('permission', [])
                    resource_permission[resource] = [
                        permissions_manager.operation_value_to_name(o)
                        for o in operations
                    ]

            role['permissions'] = resource_permission

        for role in roles:
            role.update(serialization.link.child_link_obj(role['id']))

        return self.ok(roles)
Beispiel #3
0
    def get(self, request):
        """
        List all roles.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a list of roles
        :rtype: django.http.HttpResponse
        """
        role_query_manager = factory.role_query_manager()
        user_query_manager = factory.user_query_manager()
        permissions_manager = factory.permission_manager()
        roles = role_query_manager.find_all()
        for role in roles:
            role['users'] = [u['login'] for u in
                             user_query_manager.find_users_belonging_to_role(role['id'])]

            resource_permission = {}
            # isolate schema change
            if role['permissions']:
                for item in role['permissions']:
                    resource = item['resource']
                    operations = item.get('permission', [])
                    resource_permission[resource] = [permissions_manager.operation_value_to_name(o)
                                                     for o in operations]

            role['permissions'] = resource_permission

            link = {'_href': reverse('role_resource',
                    kwargs={'role_id': role['id']})}
            role.update(link)
        return generate_json_response_with_pulp_encoder(roles)
Beispiel #4
0
    def _check_username_password_local(self, username, password=None):
        """
        Check a username and password against the local database.
        Return None if the username and password are not valid

        :type username: str
        :param username: the login of the user

        :type password: str or None
        :param password: password of the user, None => do not validate the password

        :rtype: L{pulp.server.db.model.auth.User} instance or None
        :return: user corresponding to the credentials
        """
        user_query_manager = factory.user_query_manager()
        user = user_query_manager.find_by_login(username)
        if user is None:
            _logger.debug(_('User [%(u)s] specified in certificate was not found in the system') %
                          {'u': username})
            return None

        if user['password'] is None and password is not None:
            _logger.debug('This is an ldap user %s' % user)
            return None

        if password is not None:
            if not factory.password_manager().check_password(user['password'], password):
                _logger.debug('Password for user [%s] was incorrect' % username)
                return None

        return user
Beispiel #5
0
    def add_permissions_to_role(role_id, resource, operations):
        """
        Add permissions to a role.

        :param role_id:         role identifier
        :type  role_id:         str
        :param resource:        resource path to grant permissions to
        :type  resource:        str
        :param operations:      list or tuple
        :type  operations:      list of allowed operations being granted
        :raise MissingResource: if the given role does not exist
        """
        if role_id == SUPER_USER_ROLE:
            raise PulpDataException(_('super-users role cannot be changed'))

        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        current_ops = role['permissions'].setdefault(resource, [])
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        users = factory.user_query_manager().find_users_belonging_to_role(role_id)
        for user in users:
            factory.permission_manager().grant(resource, user['login'], operations)

        Role.get_collection().save(role, safe=True)
Beispiel #6
0
    def GET(self):

        role_query_manager = managers.role_query_manager()
        user_query_manager = managers.user_query_manager()
        permissions_manager = managers.permission_manager()
        roles = role_query_manager.find_all()
        for role in roles:
            role['users'] = [u['login'] for u in
                             user_query_manager.find_users_belonging_to_role(role['id'])]

            resource_permission = {}
            # isolate schema change
            if role['permissions']:
                for item in role['permissions']:
                    resource = item['resource']
                    operations = item.get('permission', [])
                    resource_permission[resource] = [permissions_manager.operation_value_to_name(o)
                                                     for o in operations]

            role['permissions'] = resource_permission

        for role in roles:
            role.update(serialization.link.child_link_obj(role['id']))

        return self.ok(roles)
Beispiel #7
0
    def test_syntactic_sugar_methods(self):
        """
        Tests the syntactic sugar methods for retrieving specific managers.
        """
        # Setup
        factory.initialize()

        # Test
        self.assertTrue(isinstance(factory.authentication_manager(), AuthenticationManager))
        self.assertTrue(isinstance(factory.cert_generation_manager(), CertGenerationManager))
        self.assertTrue(isinstance(factory.certificate_manager(), CertificateManager))
        self.assertTrue(isinstance(factory.password_manager(), PasswordManager))
        self.assertTrue(isinstance(factory.permission_manager(), PermissionManager))
        self.assertTrue(isinstance(factory.permission_query_manager(), PermissionQueryManager))
        self.assertTrue(isinstance(factory.role_manager(), RoleManager))
        self.assertTrue(isinstance(factory.role_query_manager(), RoleQueryManager))
        self.assertTrue(isinstance(factory.user_manager(), UserManager))             
        self.assertTrue(isinstance(factory.user_query_manager(), UserQueryManager))
        self.assertTrue(isinstance(factory.repo_manager(), RepoManager))
        self.assertTrue(isinstance(factory.repo_unit_association_manager(), RepoUnitAssociationManager))
        self.assertTrue(isinstance(factory.repo_publish_manager(), RepoPublishManager))
        self.assertTrue(isinstance(factory.repo_query_manager(), RepoQueryManager))
        self.assertTrue(isinstance(factory.repo_sync_manager(), RepoSyncManager))
        self.assertTrue(isinstance(factory.content_manager(), ContentManager))
        self.assertTrue(isinstance(factory.content_query_manager(), ContentQueryManager))
        self.assertTrue(isinstance(factory.content_upload_manager(), ContentUploadManager))
        self.assertTrue(isinstance(factory.consumer_manager(), ConsumerManager))
        self.assertTrue(isinstance(factory.topic_publish_manager(), TopicPublishManager))
Beispiel #8
0
    def GET(self):

        query_manager = managers.user_query_manager()
        users = query_manager.find_all()
        self._process_users(users)

        return self.ok(users)
Beispiel #9
0
    def get(self, request, role_id):
        """
        Retrieve a specific role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str

        :return: Response containing the role
        :rtype: django.http.HttpResponse
        :raises: MissingResource if role ID does not exist
        """
        role = factory.role_query_manager().find_by_id(role_id)
        if role is None:
            raise pulp_exceptions.MissingResource(role_id)
        role['users'] = [u['login'] for u in
                         factory.user_query_manager().find_users_belonging_to_role(role['id'])]
        permissions_manager = factory.permission_manager()
        # isolate schema change
        resource_permission = {}
        for item in role['permissions']:
            resource = item['resource']
            operations = item.get('permission', [])
            resource_permission[resource] = [permissions_manager.operation_value_to_name(o)
                                             for o in operations]
        role['permissions'] = resource_permission

        link = {'_href': reverse('role_resource',
                kwargs={'role_id': role['id']})}
        role.update(link)
        return generate_json_response_with_pulp_encoder(role)
Beispiel #10
0
def _check_username_password_local(username, password=None):
    """
    Check a username and password against the local database.
    Return None if the username and password are not valid
    @type username: str
    @param username: the login of the user
    @type password: str or None
    @param password: password of the user, None => do not validate the password
    @rtype: L{pulp.server.db.model.User} instance or None
    @return: user corresponding to the credentials
    """
    user_query_manager = factory.user_query_manager()
    user = user_query_manager.find_by_login(username)
    if user is None:
        _log.error('User [%s] specified in certificate was not found in the system' %
                   username)
        return None
    if user['password'] is None and password is not None:
        _log.error('This is an ldap user %s' % user)
        return None
    if password is not None:
        if not factory.password_manager().check_password(user['password'], password):
            _log.error('Password for user [%s] was incorrect' % username)
            return None
    return user
Beispiel #11
0
    def GET(self, role_id):

        role = managers.role_query_manager().find_by_id(role_id)
        if role is None:
            raise exceptions.MissingResource(role_id)

        role['users'] = [
            u['login'] for u in managers.user_query_manager().
            find_users_belonging_to_role(role['id'])
        ]
        permissions_manager = managers.permission_manager()

        # isolate schema change
        resource_permission = {}
        for item in role['permissions']:
            resource = item['resource']
            operations = item.get('permission', [])
            resource_permission[resource] = [
                permissions_manager.operation_value_to_name(o)
                for o in operations
            ]
        role['permissions'] = resource_permission

        role.update(serialization.link.current_link_obj())
        return self.ok(role)
Beispiel #12
0
    def test_syntactic_sugar_methods(self):
        """
        Tests the syntactic sugar methods for retrieving specific managers.
        """
        # Setup
        factory.initialize()

        # Test
        self.assertTrue(isinstance(factory.authentication_manager(), AuthenticationManager))
        self.assertTrue(isinstance(factory.cert_generation_manager(), CertGenerationManager))
        self.assertTrue(isinstance(factory.certificate_manager(), CertificateManager))
        self.assertTrue(isinstance(factory.password_manager(), PasswordManager))
        self.assertTrue(isinstance(factory.permission_manager(), PermissionManager))
        self.assertTrue(isinstance(factory.permission_query_manager(), PermissionQueryManager))
        self.assertTrue(isinstance(factory.role_manager(), RoleManager))
        self.assertTrue(isinstance(factory.role_query_manager(), RoleQueryManager))
        self.assertTrue(isinstance(factory.user_manager(), UserManager))
        self.assertTrue(isinstance(factory.user_query_manager(), UserQueryManager))
        self.assertTrue(isinstance(factory.repo_manager(), RepoManager))
        self.assertTrue(isinstance(factory.repo_unit_association_manager(),
                                   RepoUnitAssociationManager))
        self.assertTrue(isinstance(factory.repo_publish_manager(), RepoPublishManager))
        self.assertTrue(isinstance(factory.repo_query_manager(), RepoQueryManager))
        self.assertTrue(isinstance(factory.repo_sync_manager(), RepoSyncManager))
        self.assertTrue(isinstance(factory.content_manager(), ContentManager))
        self.assertTrue(isinstance(factory.content_query_manager(), ContentQueryManager))
        self.assertTrue(isinstance(factory.content_upload_manager(), ContentUploadManager))
        self.assertTrue(isinstance(factory.consumer_manager(), ConsumerManager))
        self.assertTrue(isinstance(factory.topic_publish_manager(), TopicPublishManager))
Beispiel #13
0
    def delete_user(login):
        """
        Deletes the given user. Deletion of last superuser is not permitted.

        @param login: identifies the user being deleted
        @type  login: str

        @raise MissingResource: if the given user does not exist
        @raise InvalidValue: if login value is invalid
        """

        # Raise exception if login is invalid
        if login is None or invalid_type(login, basestring):
            raise InvalidValue(['login'])

        # Check whether user exists
        found = User.get_collection().find_one({'login': login})
        if found is None:
            raise MissingResource(login)

        # Make sure user is not the last super user
        if factory.user_query_manager().is_last_super_user(login):
            raise PulpDataException(_("The last superuser [%s] cannot be deleted" % login))

        # Revoke all permissions from the user
        permission_manager = factory.permission_manager()
        permission_manager.revoke_all_permissions_from_user(login)

        User.get_collection().remove({'login': login})
Beispiel #14
0
    def add_permissions_to_role(self, role_id, resource, operations):
        """
        Add permissions to a role. 

        @type role_id: str
        @param role_id: role identifier
        
        @type resource: str
        @param resource: resource path to grant permissions to
        
        @type operations: list of allowed operations being granted
        @param operations: list or tuple

        @raise MissingResource: if the given role does not exist
        """
        if role_id == self.super_user_role:
            raise PulpDataException(_('super-users role cannot be changed'))

        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        current_ops = role['permissions'].setdefault(resource, [])
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        users = factory.user_query_manager().find_users_belonging_to_role(
            role_id)
        for user in users:
            factory.permission_manager().grant(resource, user['login'],
                                               operations)

        Role.get_collection().save(role, safe=True)
Beispiel #15
0
    def GET(self, login):

        user = managers.user_query_manager().find_by_login(login)
        if user is None:
            raise exceptions.MissingResource(login)

        user.update(serialization.link.current_link_obj())

        return self.ok(user)
Beispiel #16
0
    def GET(self, login):

        user = managers.user_query_manager().find_by_login(login)
        if user is None:
            raise exceptions.MissingResource(login)

        user.update(serialization.link.current_link_obj())

        return self.ok(user)
Beispiel #17
0
        def _auth_decorator(self, *args, **kwargs):

            # Check Authentication

            # Run through each registered and enabled auth function
            is_consumer = False
            registered_auth_functions = [check_preauthenticated,
                                         password_authentication,
                                         user_cert_authentication,
                                         consumer_cert_authentication,
                                         oauth_authentication]

            user_authenticated = False
            for authenticate_user in registered_auth_functions:
                if authenticate_user == oauth_authentication:
                    userid, is_consumer = authenticate_user()
                else:
                    userid = authenticate_user()

                if userid is not None:
                    user_authenticated = True
                    if authenticate_user == consumer_cert_authentication:
                        is_consumer = True
                    break

            if not user_authenticated:
                raise PulpCodedAuthenticationException(error_code=error_codes.PLP0025)

            # Check Authorization
            principal_manager = factory.principal_manager()
            user_query_manager = factory.user_query_manager()
            if super_user_only and not user_query_manager.is_superuser(userid):
                raise PulpCodedAuthenticationException(error_code=error_codes.PLP0026, user=userid,
                                                       operation=OPERATION_NAMES[operation])
            # if the operation is None, don't check authorization
            elif operation is not None:
                if is_consumer:
                    if is_consumer_authorized(http.resource_path(), userid, operation):
                        # set default principal = SYSTEM
                        principal_manager.set_principal()
                    else:
                        raise PulpCodedAuthenticationException(error_code=error_codes.PLP0026,
                                                               user=userid,
                                                               operation=OPERATION_NAMES[operation])
                elif user_query_manager.is_authorized(http.resource_path(), userid, operation):
                    user = user_query_manager.find_by_login(userid)
                    principal_manager.set_principal(user)
                else:
                    raise PulpCodedAuthenticationException(error_code=error_codes.PLP0026,
                                                           user=userid,
                                                           operation=OPERATION_NAMES[operation])

            # Authentication and authorization succeeded. Call method and then clear principal.
            value = method(self, *args, **kwargs)
            principal_manager.clear_principal()
            return value
Beispiel #18
0
    def GET(self, login):

        user = managers.user_query_manager().find_by_login(login)
        if user is None:
            raise exceptions.MissingResource(login)

        user.update(serialization.link.current_link_obj())

        self.process_dictionary_against_whitelist(user, USER_WHITELIST)
        return self.ok(user)
Beispiel #19
0
    def GET(self, login):

        user = managers.user_query_manager().find_by_login(login)
        if user is None:
            raise exceptions.MissingResource(login)

        user.update(serialization.link.current_link_obj())

        self.process_dictionary_against_whitelist(user, USER_WHITELIST)
        return self.ok(user)
Beispiel #20
0
        def _auth_decorator(self, *args, **kwargs):

            # Check Authentication

            # Run through each registered and enabled auth function
            is_consumer = False
            registered_auth_functions = [
                check_preauthenticated, password_authentication,
                user_cert_authentication, consumer_cert_authentication,
                oauth_authentication
            ]

            user_authenticated = False
            for authenticate_user in registered_auth_functions:
                if authenticate_user == oauth_authentication:
                    userid, is_consumer = authenticate_user()
                else:
                    userid = authenticate_user()

                if userid is not None:
                    user_authenticated = True
                    if authenticate_user == consumer_cert_authentication:
                        is_consumer = True
                    break

            if not user_authenticated:
                raise AuthenticationFailed(auth_utils.CODE_FAILED)

            # Check Authorization

            principal_manager = factory.principal_manager()
            user_query_manager = factory.user_query_manager()

            if super_user_only and not user_query_manager.is_superuser(userid):
                raise AuthenticationFailed(auth_utils.CODE_PERMISSION)
            # if the operation is None, don't check authorization
            elif operation is not None:
                if is_consumer:
                    if is_consumer_authorized(http.resource_path(), userid,
                                              operation):
                        # set default principal = SYSTEM
                        principal_manager.set_principal()
                    else:
                        raise AuthenticationFailed(auth_utils.CODE_PERMISSION)
                elif user_query_manager.is_authorized(http.resource_path(),
                                                      userid, operation):
                    user = user_query_manager.find_by_login(userid)
                    principal_manager.set_principal(user)
                else:
                    raise AuthenticationFailed(auth_utils.CODE_PERMISSION)

            # Authentication and authorization succeeded. Call method and then clear principal.
            value = method(self, *args, **kwargs)
            principal_manager.clear_principal()
            return value
Beispiel #21
0
    def setUp(self):
        super(AuthControllersTests, self).setUp()
        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.role_manager = manager_factory.role_manager()
        self.role_query_manager = manager_factory.role_query_manager()
        self.permission_manager = manager_factory.permission_manager()
        self.permission_query_manager = manager_factory.permission_query_manager()
        self.password_manager = manager_factory.password_manager()

        self.role_manager.ensure_super_user_role()
        self.user_manager.ensure_admin()
Beispiel #22
0
    def setUp(self):
        super(UserManagerTests, self).setUp()

        # Hardcoded to /var/lib/pulp, so change here to avoid permissions issues
        self.default_sn_path = SerialNumber.PATH
        SerialNumber.PATH = '/tmp/sn.dat'
        sn = SerialNumber()
        sn.reset()

        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.cert_generation_manager = manager_factory.cert_generation_manager()
Beispiel #23
0
    def setUp(self):
        super(UserManagerTests, self).setUp()

        # Hardcoded to /var/lib/pulp, so change here to avoid permissions issues
        self.default_sn_path = SerialNumber.PATH
        SerialNumber.PATH = '/tmp/sn.dat'
        sn = SerialNumber()
        sn.reset()

        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.role_manager = manager_factory.role_manager()
        self.cert_generation_manager = manager_factory.cert_generation_manager()
Beispiel #24
0
    def setUp(self):
        super(AuthControllersTests, self).setUp()
        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.role_manager = manager_factory.role_manager()
        self.role_query_manager = manager_factory.role_query_manager()
        self.permission_manager = manager_factory.permission_manager()
        self.permission_query_manager = manager_factory.permission_query_manager(
        )
        self.password_manager = manager_factory.password_manager()

        self.role_manager.ensure_super_user_role()
        self.user_manager.ensure_admin()
Beispiel #25
0
    def setUp(self):
        super(PermissionManagerTests, self).setUp()

        self.alpha_num = string.letters + string.digits

        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.role_manager = manager_factory.role_manager()
        self.role_query_manager = manager_factory.role_query_manager()
        self.permission_manager = manager_factory.permission_manager()
        self.permission_query_manager = manager_factory.permission_query_manager()

        self.role_manager.ensure_super_user_role()
        manager_factory.principal_manager().clear_principal()
Beispiel #26
0
    def setUp(self):
        super(RoleManagerTests, self).setUp()

        self.alpha_num = string.letters + string.digits

        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.role_manager = manager_factory.role_manager()
        self.role_query_manager = manager_factory.role_query_manager()
        self.permission_manager = manager_factory.permission_manager()
        self.permission_query_manager = manager_factory.permission_query_manager()

        self.role_manager.ensure_super_user_role()
        manager_factory.principal_manager().clear_principal()
Beispiel #27
0
    def get_admins():
        """
        Get a list of users with the super-user role.

        :return: list of users who are admins.
        :rtype:  list of User
        """
        user_query_manager = factory.user_query_manager()

        try:
            super_users = user_query_manager.find_users_belonging_to_role(SUPER_USER_ROLE)
            return super_users
        except MissingResource:
            return None
Beispiel #28
0
    def remove_permissions_from_role(role_id, resource, operations):
        """
        Remove permissions from a role.

        :param role_id:         role identifier
        :type  role_id:         str
        :param resource:        resource path to revoke permissions from
        :type  resource:        str
        :param operations:      list or tuple
        :type  operations:      list of allowed operations being revoked
        :raise InvalidValue: if some params are invalid
        :raise PulpDataException: if role is a superuser role
        """
        if role_id == SUPER_USER_ROLE:
            raise PulpDataException(_('super-users role cannot be changed'))

        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise InvalidValue(['role_id'])

        resource_permission = {}
        current_ops = []
        for item in role['permissions']:
            if item['resource'] == resource:
                resource_permission = item
                current_ops = resource_permission['permission']

        if not current_ops:
            return
        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        users = factory.user_query_manager().find_users_belonging_to_role(
            role_id)
        for user in users:
            other_roles = factory.role_query_manager().get_other_roles(
                role, user['roles'])
            user_ops = _operations_not_granted_by_roles(
                resource, operations, other_roles)
            factory.permission_manager().revoke(resource, user['login'],
                                                user_ops)

        # in no more allowed operations, remove the resource
        if not current_ops:
            role['permissions'].remove(resource_permission)

        Role.get_collection().save(role, safe=True)
Beispiel #29
0
    def get(self, request, role_id):
        """
        List Users belonging to a role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str

        :return: Response containing the users
        :rtype: django.http.HttpResponse
        """
        user_query_manager = factory.user_query_manager()
        role_users = user_query_manager.find_users_belonging_to_role(role_id)
        return generate_json_response_with_pulp_encoder(role_users)
Beispiel #30
0
    def GET(self):

        role_query_manager = managers.role_query_manager()
        roles = role_query_manager.find_all()
        for role in roles:
            role['users'] = [u['login'] for u in
                             managers.user_query_manager().find_users_belonging_to_role(role['id'])]
            for resource, operations in role['permissions'].items():
                role['permissions'][resource] = [operation_to_name(o)
                                                 for o in operations]

        for role in roles:
            role.update(serialization.link.child_link_obj(role['id']))

        return self.ok(roles)
Beispiel #31
0
    def GET(self, role_id):

        role = managers.role_query_manager().find_by_id(role_id)
        if role is None:
            raise exceptions.MissingResource(role_id)

        role['users'] = [u['login'] for u in
                         managers.user_query_manager().find_users_belonging_to_role(role['id'])]
        permissions_manager = managers.permission_manager()
        for resource, operations in role['permissions'].items():
            role['permissions'][resource] = [permissions_manager.operation_value_to_name(o)
                                             for o in operations]

        role.update(serialization.link.current_link_obj())
        return self.ok(role)
Beispiel #32
0
Datei: cud.py Projekt: nbetm/pulp
    def remove_permissions_from_role(role_id, resource, operations):
        """
        Remove permissions from a role.

        :param role_id:         role identifier
        :type  role_id:         str
        :param resource:        resource path to revoke permissions from
        :type  resource:        str
        :param operations:      list or tuple
        :type  operations:      list of allowed operations being revoked
        :raise InvalidValue: if some params are invalid
        :raise PulpDataException: if role is a superuser role
        """
        if role_id == SUPER_USER_ROLE:
            raise PulpDataException(_('super-users role cannot be changed'))

        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise InvalidValue(['role_id'])

        resource_permission = {}
        current_ops = []
        for item in role['permissions']:
            if item['resource'] == resource:
                resource_permission = item
                current_ops = resource_permission['permission']

        if not current_ops:
            return
        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        users = factory.user_query_manager().find_users_belonging_to_role(role_id)
        for user in users:
            other_roles = factory.role_query_manager().get_other_roles(role, user['roles'])
            user_ops = _operations_not_granted_by_roles(resource,
                                                        operations,
                                                        other_roles)
            factory.permission_manager().revoke(resource, user['login'], user_ops)

        # in no more allowed operations, remove the resource
        if not current_ops:
            role['permissions'].remove(resource_permission)

        Role.get_collection().save(role, safe=True)
Beispiel #33
0
    def get(self, request):
        """
        List all users.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a list of users
        :rtype: django.http.HttpResponse
        """
        query_manager = factory.user_query_manager()
        users = query_manager.find_all()

        for user in users:
            serialize(user)

        return generate_json_response_with_pulp_encoder(users)
Beispiel #34
0
    def add_permissions_to_role(role_id, resource, operations):
        """
        Add permissions to a role.

        :param role_id:         role identifier
        :type  role_id:         str
        :param resource:        resource path to grant permissions to
        :type  resource:        str
        :param operations:      list or tuple
        :type  operations:      list of allowed operations being granted
        :raise InvalidValue: if some params are invalid
        :raise PulpDataException: if role is a superuser role
        """
        if role_id == SUPER_USER_ROLE:
            raise PulpDataException(_('super-users role cannot be changed'))

        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise InvalidValue(['role_id'])
        if not role['permissions']:
            role['permissions'] = []

        resource_permission = {}
        current_ops = []
        for item in role['permissions']:
            if item['resource'] == resource:
                resource_permission = item
                current_ops = resource_permission['permission']

        if not resource_permission:
            resource_permission = dict(resource=resource,
                                       permission=current_ops)
            role['permissions'].append(resource_permission)

        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        users = factory.user_query_manager().find_users_belonging_to_role(
            role_id)
        for user in users:
            factory.permission_manager().grant(resource, user['login'],
                                               operations)

        Role.get_collection().save(role, safe=True)
Beispiel #35
0
    def get(self, request):
        """
        List all users.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a list of users
        :rtype: django.http.HttpResponse
        """
        query_manager = factory.user_query_manager()
        users = query_manager.find_all()

        for user in users:
            serialize(user)

        return generate_json_response_with_pulp_encoder(users)
Beispiel #36
0
    def remove_permissions_from_role(self, role_id, resource, operations):
        """
        Remove permissions from a role. 
        
        @type role_id: str
        @param role_id: role identifier
    
        @type resource: str
        @param resource: resource path to revoke permissions from
        
        @type operations: list of allowed operations being revoked
        @param operations: list or tuple
        
        @raise MissingResource: if the given role does not exist
        """
        if role_id == self.super_user_role:
            raise PulpDataException(_('super-users role cannot be changed'))

        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        current_ops = role['permissions'].get(resource, [])
        if not current_ops:
            return
        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        users = factory.user_query_manager().find_users_belonging_to_role(
            role_id)
        for user in users:
            other_roles = factory.role_query_manager().get_other_roles(
                role, user['roles'])
            user_ops = _operations_not_granted_by_roles(
                resource, operations, other_roles)
            factory.permission_manager().revoke(resource, user['login'],
                                                user_ops)

        # in no more allowed operations, remove the resource
        if not current_ops:
            del role['permissions'][resource]

        Role.get_collection().save(role, safe=True)
Beispiel #37
0
    def get(self, request):
        """
        List all users.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a list of users
        :rtype: django.http.HttpResponse
        """
        query_manager = factory.user_query_manager()
        users = query_manager.find_all()

        for user in users:
            add_link(user)
            process_dictionary_against_whitelist(user, USER_WHITELIST)

        return generate_json_response_with_pulp_encoder(users)
Beispiel #38
0
    def GET(self):

        role_query_manager = managers.role_query_manager()
        roles = role_query_manager.find_all()
        for role in roles:
            role['users'] = [
                u['login'] for u in managers.user_query_manager().
                find_users_belonging_to_role(role['id'])
            ]
            for resource, operations in role['permissions'].items():
                role['permissions'][resource] = [
                    operation_to_name(o) for o in operations
                ]

        for role in roles:
            role.update(serialization.link.child_link_obj(role['id']))

        return self.ok(roles)
Beispiel #39
0
    def delete_role(role_id):
        """
        Deletes the given role. This has the side-effect of revoking any permissions granted
        to the role from the users in the role, unless those permissions are also granted
        through another role the user is a memeber of.

        :param role_id:         identifies the role being deleted
        :type  role_id:         str
        :raise InvalidValue:    if any of the fields are unacceptable
        :raise MissingResource: if the given role does not exist
        :raise PulpDataException: if role is a superuser role
        """
        # Raise exception if role id is invalid
        if role_id is None or not isinstance(role_id, basestring):
            raise InvalidValue(['role_id'])

        # Check whether role exists
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        # Make sure role is not a superuser role
        if role_id == SUPER_USER_ROLE:
            raise PulpDataException(_('Role %s cannot be changed') % role_id)

        # Remove respective roles from users
        users = factory.user_query_manager().find_users_belonging_to_role(
            role_id)

        for item in role['permissions']:
            for user in users:
                other_roles = factory.role_query_manager().get_other_roles(
                    role, user['roles'])
                user_ops = _operations_not_granted_by_roles(
                    item['resource'], item['permission'], other_roles)
                factory.permission_manager().revoke(item['resource'],
                                                    user['login'], user_ops)

        for user in users:
            user['roles'].remove(role_id)
            factory.user_manager().update_user(user['login'],
                                               Delta(user, 'roles'))

        Role.get_collection().remove({'id': role_id}, safe=True)
Beispiel #40
0
    def get(self, resuest, login):
        """
        Retrieve a specific user.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param login: login for the requested user
        :type login: str

        :return: Response containing the user
        :rtype: django.http.HttpResponse
        :raises: MissingResource if login does not exist
        """
        user = factory.user_query_manager().find_by_login(login)
        if user is None:
            raise pulp_exceptions.MissingResource(login)

        user = serialize(user)
        return generate_json_response_with_pulp_encoder(user)
    def test_get(self):
        # Setup
        user_query_manager = manager_factory.user_query_manager()
        cert_generation_manager = manager_factory.cert_generation_manager()
        
        user = user_query_manager.find_by_login(login='******')

        # Test
        status, body = self.post('/v2/actions/login/')

        # Verify
        self.assertEqual(200, status)

        certificate = manager_factory.certificate_manager(content=str(body['key']+body['certificate']))
        cn = certificate.subject()['CN']
        username, id = cert_generation_manager.decode_admin_user(cn)

        self.assertEqual(username, user['login'])
        self.assertEqual(id, user['id'])
Beispiel #42
0
    def remove_user_from_role(self, role_id, login):
        """
        Remove a user from a role. This has the side-effect of revoking all the
        permissions granted to the role from the user, unless the permissions are
        also granted by another role.
        
        @type role_id: str
        @param role_id: role identifier
    
        @type login: str
        @param login: name of user
        
        @rtype: bool
        @return: True on success
                        
        @raise MissingResource: if the given role or user does not exist
        """
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        if role_id == self.super_user_role and factory.user_query_manager(
        ).is_last_super_user(login):
            raise PulpDataException(
                _('%s cannot be empty, and %s is the last member') %
                (self.super_user_role, login))

        if role_id not in user['roles']:
            return

        user['roles'].remove(role_id)
        User.get_collection().save(user, safe=True)

        for resource, operations in role['permissions'].items():
            other_roles = factory.role_query_manager().get_other_roles(
                role, user['roles'])
            user_ops = _operations_not_granted_by_roles(
                resource, operations, other_roles)
            factory.permission_manager().revoke(resource, login, user_ops)
Beispiel #43
0
Datei: cud.py Projekt: nbetm/pulp
    def add_permissions_to_role(role_id, resource, operations):
        """
        Add permissions to a role.

        :param role_id:         role identifier
        :type  role_id:         str
        :param resource:        resource path to grant permissions to
        :type  resource:        str
        :param operations:      list or tuple
        :type  operations:      list of allowed operations being granted
        :raise InvalidValue: if some params are invalid
        :raise PulpDataException: if role is a superuser role
        """
        if role_id == SUPER_USER_ROLE:
            raise PulpDataException(_('super-users role cannot be changed'))

        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise InvalidValue(['role_id'])
        if not role['permissions']:
            role['permissions'] = []

        resource_permission = {}
        current_ops = []
        for item in role['permissions']:
            if item['resource'] == resource:
                resource_permission = item
                current_ops = resource_permission['permission']

        if not resource_permission:
            resource_permission = dict(resource=resource, permission=current_ops)
            role['permissions'].append(resource_permission)

        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        users = factory.user_query_manager().find_users_belonging_to_role(role_id)
        for user in users:
            factory.permission_manager().grant(resource, user['login'], operations)

        Role.get_collection().save(role, safe=True)
Beispiel #44
0
    def get(self, resuest, login):
        """
        Retrieve a specific user.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param login: login for the requested user
        :type login: str

        :return: Response containing the user
        :rtype: django.http.HttpResponse
        :raises: MissingResource if login does not exist
        """
        user = factory.user_query_manager().find_by_login(login)
        if user is None:
            raise pulp_exceptions.MissingResource(login)

        user = serialize(user)
        return generate_json_response_with_pulp_encoder(user)
Beispiel #45
0
    def GET(self, role_id):

        manager = managers.role_query_manager()
        role = manager.find_by_id(role_id)
        if role is None:
            raise exceptions.MissingResource(role_id)

        role['users'] = [
            u['login'] for u in managers.user_query_manager().
            find_users_belonging_to_role(role['id'])
        ]
        for resource, operations in role['permissions'].items():
            role['permissions'][resource] = [
                operation_to_name(o) for o in operations
            ]

        role.update(serialization.link.current_link_obj())

        return self.ok(role)
Beispiel #46
0
    def remove_permissions_from_role(self, role_id, resource, operations):
        """
        Remove permissions from a role. 
        
        @type role_id: str
        @param role_id: role identifier
    
        @type resource: str
        @param resource: resource path to revoke permissions from
        
        @type operations: list of allowed operations being revoked
        @param operations: list or tuple
        
        @raise MissingResource: if the given role does not exist
        """
        if role_id == self.super_user_role:
            raise PulpDataException(_('super-users role cannot be changed'))

        role = Role.get_collection().find_one({'id' : role_id})
        if role is None:
            raise MissingResource(role_id)
        
        current_ops = role['permissions'].get(resource, [])
        if not current_ops:
            return
        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)
            
        users = factory.user_query_manager().find_users_belonging_to_role(role_id)
        for user in users:
            other_roles = factory.role_query_manager().get_other_roles(role, user['roles'])
            user_ops = _operations_not_granted_by_roles(resource,
                                                    operations,
                                                    other_roles)
            factory.permission_manager().revoke(resource, user['login'], user_ops)
        
        # in no more allowed operations, remove the resource
        if not current_ops:
            del role['permissions'][resource]
        
        Role.get_collection().save(role, safe=True)
Beispiel #47
0
    def remove_user_from_role(role_id, login):
        """
        Remove a user from a role. This has the side-effect of revoking all the
        permissions granted to the role from the user, unless the permissions are
        also granted by another role.

        :param role_id:         role identifier
        :type  role_id:         str
        :param login:           name of user
        :type  login:           str
        :raise MissingResource: if the given role or user does not exist
        """
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        if role_id == SUPER_USER_ROLE and factory.user_query_manager(
        ).is_last_super_user(login):
            raise PulpDataException(
                _('%(role)s cannot be empty, and %(login)s is the last member')
                % {
                    'role': SUPER_USER_ROLE,
                    'login': login
                })

        if role_id not in user['roles']:
            return

        user['roles'].remove(role_id)
        User.get_collection().save(user, safe=True)

        for item in role['permissions']:
            other_roles = factory.role_query_manager().get_other_roles(
                role, user['roles'])
            user_ops = _operations_not_granted_by_roles(
                item['resource'], item['permission'], other_roles)
            factory.permission_manager().revoke(item['resource'], login,
                                                user_ops)
Beispiel #48
0
    def test_get(self):
        # Setup
        user_query_manager = manager_factory.user_query_manager()
        cert_generation_manager = manager_factory.cert_generation_manager()

        user = user_query_manager.find_by_login(login='******')

        # Test
        status, body = self.post('/v2/actions/login/')

        # Verify
        self.assertEqual(200, status)

        certificate = manager_factory.certificate_manager(
            content=str(body['key'] + body['certificate']))
        cn = certificate.subject()['CN']
        username, id = cert_generation_manager.decode_admin_user(cn)

        self.assertEqual(username, user['login'])
        self.assertEqual(id, user['id'])
Beispiel #49
0
    def remove_user_from_role(self, role_id, login):
        """
        Remove a user from a role. This has the side-effect of revoking all the
        permissions granted to the role from the user, unless the permissions are
        also granted by another role.
        
        @type role_id: str
        @param role_id: role identifier
    
        @type login: str
        @param login: name of user
        
        @rtype: bool
        @return: True on success
                        
        @raise MissingResource: if the given role or user does not exist
        """
        role = Role.get_collection().find_one({'id' : role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login' : login})
        if user is None:
            raise MissingResource(login)

        if role_id == self.super_user_role and factory.user_query_manager().is_last_super_user(login):
            raise PulpDataException(_('%s cannot be empty, and %s is the last member') %
                                     (self.super_user_role, login))

        if role_id not in user['roles']:
            return
        
        user['roles'].remove(role_id)
        User.get_collection().save(user, safe=True)

        for resource, operations in role['permissions'].items():
            other_roles = factory.role_query_manager().get_other_roles(role, user['roles'])
            user_ops = _operations_not_granted_by_roles(resource,
                                                        operations,
                                                        other_roles)
            factory.permission_manager().revoke(resource, login, user_ops)
Beispiel #50
0
    def GET(self, role_id):

        role = managers.role_query_manager().find_by_id(role_id)
        if role is None:
            raise exceptions.MissingResource(role_id)

        role['users'] = [u['login'] for u in
                         managers.user_query_manager().find_users_belonging_to_role(role['id'])]
        permissions_manager = managers.permission_manager()

        # isolate schema change
        resource_permission = {}
        for item in role['permissions']:
            resource = item['resource']
            operations = item.get('permission', [])
            resource_permission[resource] = [permissions_manager.operation_value_to_name(o)
                                             for o in operations]
        role['permissions'] = resource_permission

        role.update(serialization.link.current_link_obj())
        return self.ok(role)
Beispiel #51
0
 def ensure_admin(self):
     """
     This function ensures that there is at least one super user for the system.
     If no super users are found, the default admin user (from the pulp config)
     is looked up or created and added to the super users role.
     """
     user_query_manager = factory.user_query_manager()
     role_manager = factory.role_manager()
     
     super_users = user_query_manager.find_users_belonging_to_role(role_manager.super_user_role)
     if super_users:
         return
     
     default_login = config.config.get('server', 'default_login')
     
     admin = User.get_collection().find_one({'login' : default_login})
     if admin is None:
         default_password = config.config.get('server', 'default_password')
         admin = factory.user_manager().create_user(login=default_login, password=default_password)
     
     role_manager.add_user_to_role(role_manager.super_user_role, default_login)
Beispiel #52
0
Datei: cud.py Projekt: nbetm/pulp
    def delete_role(role_id):
        """
        Deletes the given role. This has the side-effect of revoking any permissions granted
        to the role from the users in the role, unless those permissions are also granted
        through another role the user is a memeber of.

        :param role_id:         identifies the role being deleted
        :type  role_id:         str
        :raise InvalidValue:    if any of the fields are unacceptable
        :raise MissingResource: if the given role does not exist
        :raise PulpDataException: if role is a superuser role
        """
        # Raise exception if role id is invalid
        if role_id is None or not isinstance(role_id, basestring):
            raise InvalidValue(['role_id'])

        # Check whether role exists
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        # Make sure role is not a superuser role
        if role_id == SUPER_USER_ROLE:
            raise PulpDataException(_('Role %s cannot be changed') % role_id)

        # Remove respective roles from users
        users = factory.user_query_manager().find_users_belonging_to_role(role_id)

        for item in role['permissions']:
            for user in users:
                other_roles = factory.role_query_manager().get_other_roles(role, user['roles'])
                user_ops = _operations_not_granted_by_roles(item['resource'],
                                                            item['permission'], other_roles)
                factory.permission_manager().revoke(item['resource'], user['login'], user_ops)

        for user in users:
            user['roles'].remove(role_id)
            factory.user_manager().update_user(user['login'], Delta(user, 'roles'))

        Role.get_collection().remove({'id': role_id}, safe=True)
Beispiel #53
0
def _check_username_password_ldap(username, password=None):
    """
    Check a username and password against the ldap server.
    Return None if the username and password are not valid
    @type username: str
    @param username: the login of the user
    @type password: str or None
    @param password: password of the user, None => do not validate the password
    @rtype: L{pulp.server.db.model.User} instance or None
    @return: user corresponding to the credentials
    """
    ldap_uri = "ldap://localhost"
    if config.has_option('ldap', 'uri'):
        ldap_uri = config.get("ldap", "uri")
    else:
        _log.info("No valid server found, default to localhost")
    ldap_base = "dc=localhost"
    if config.has_option('ldap', 'base'):
        ldap_base = config.get('ldap', 'base')
    else:
        _log.info("No valid base found, default to localhost")
    ldap_filter = None
    if config.has_option('ldap', 'filter'):
        ldap_filter = config.get('ldap', 'filter')
    ldap_tls = False
    if config.has_option('ldap', 'tls'):
        ldap_tls = config.getboolean('ldap', 'tls')
    ldap_server = ldap_connection.LDAPConnection(server=ldap_uri, tls=ldap_tls)
    ldap_server.connect()
    user = None
    if password is not None:
        user = ldap_server.authenticate_user(ldap_base, username, password,
                                             filter=ldap_filter)
    else:
        user_query_manager = factory.user_query_manager()
        user = user_query_manager.find_by_login(username)
    if user is None:
        return None
    return user
Beispiel #54
0
Datei: cud.py Projekt: omps/pulp
    def ensure_admin(self):
        """
        This function ensures that there is at least one super user for the system.
        If no super users are found, the default admin user (from the pulp config)
        is looked up or created and added to the super users role.
        """
        user_query_manager = factory.user_query_manager()
        role_manager = factory.role_manager()

        super_users = user_query_manager.find_users_belonging_to_role(
            SUPER_USER_ROLE)
        if super_users:
            return

        default_login = config.config.get('server', 'default_login')

        admin = User.get_collection().find_one({'login': default_login})
        if admin is None:
            default_password = config.config.get('server', 'default_password')
            admin = UserManager.create_user(login=default_login,
                                            password=default_password)

        role_manager.add_user_to_role(SUPER_USER_ROLE, default_login)
Beispiel #55
0
def _verify_auth(self, operation, super_user_only, method, *args, **kwargs):
    """
    Internal method for checking authentication and authorization. This code
    is kept outside of the decorator which calls it so that it can be mocked.
    This allows for the decorator itself which calls here to have assertions
    made about the operation and super_user values set in the view code.

    An operation of None means not to check authorization; only check
    authentication.

    The super_user_only flag set to True means that only members of the
    built in SuperUsers role are authorized.

    :type operation: int or None
    :param operation: The operation a user needs permission for, or None to
                      skip authorization.

    :type super_user_only: bool
    :param super_user_only: Only authorize a user if they are a super user.
    """
    # Check Authentication

    # Run through each registered and enabled auth function
    is_consumer = False
    registered_auth_functions = [
        check_preauthenticated, password_authentication,
        user_cert_authentication, consumer_cert_authentication,
        oauth_authentication
    ]

    user_authenticated = False
    for authenticate_user in registered_auth_functions:
        if authenticate_user == oauth_authentication:
            userid, is_consumer = authenticate_user()
        else:
            userid = authenticate_user()

        if userid is not None:
            user_authenticated = True
            if authenticate_user == consumer_cert_authentication:
                is_consumer = True
            break

    if not user_authenticated:
        raise PulpCodedAuthenticationException(error_code=error_codes.PLP0025)

    # Check Authorization

    principal_manager = factory.principal_manager()
    user_query_manager = factory.user_query_manager()

    if super_user_only and not user_query_manager.is_superuser(userid):
        raise PulpCodedAuthenticationException(
            error_code=error_codes.PLP0026,
            user=userid,
            operation=OPERATION_NAMES[operation])
    # if the operation is None, don't check authorization
    elif operation is not None:
        if is_consumer:
            if is_consumer_authorized(http.resource_path(), userid, operation):
                # set default principal = SYSTEM
                principal_manager.set_principal()
            else:
                raise PulpCodedAuthenticationException(
                    error_code=error_codes.PLP0026,
                    user=userid,
                    operation=OPERATION_NAMES[operation])
        elif user_query_manager.is_authorized(http.resource_path(), userid,
                                              operation):
            user = user_query_manager.find_by_login(userid)
            principal_manager.set_principal(user)
        else:
            raise PulpCodedAuthenticationException(
                error_code=error_codes.PLP0026,
                user=userid,
                operation=OPERATION_NAMES[operation])

    # Authentication and authorization succeeded. Call method and then clear principal.
    value = method(self, *args, **kwargs)
    principal_manager.clear_principal()
    return value