def test_specify_scopes(self):
        """
        Validates whether requested scopes are assigned
        """
        from api.oauth2.tokenview import OAuth2TokenView
        from api.view import MetadataView

        time.sleep(180)
        data = {
            'grant_type': 'password',
            'username': '******',
            'password': '******'
        }
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        self.assertIn('access_token', json.loads(response.content))
        access_token = json.loads(response.content)['access_token']

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertListEqual(sorted(response_content['roles']),
                             ['manage', 'read', 'write'])

        time.sleep(180)
        data['scope'] = 'read write'
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('access_token', response_content)
        access_token = response_content['access_token']

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('roles', response_content)
        self.assertListEqual(sorted(response_content['roles']),
                             ['read', 'write'])

        time.sleep(180)
        data = {
            'grant_type': 'password',
            'username': '******',
            'password': '******',
            'scope': 'read write manage'
        }
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'invalid_scope', HttpBadRequestException)
    def test_specify_scopes(self):
        """
        Validates whether requested scopes are assigned
        """
        from api.oauth2.tokenview import OAuth2TokenView
        from api.view import MetadataView

        time.sleep(180)
        data = {'grant_type': 'password',
                'username': '******',
                'password': '******'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        self.assertIn('access_token', json.loads(response.content))
        access_token = json.loads(response.content)['access_token']

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertListEqual(sorted(response_content['roles']), ['manage', 'read', 'write'])

        time.sleep(180)
        data['scope'] = 'read write'
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('access_token', response_content)
        access_token = response_content['access_token']

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('roles', response_content)
        self.assertListEqual(sorted(response_content['roles']), ['read', 'write'])

        time.sleep(180)
        data = {'grant_type': 'password',
                'username': '******',
                'password': '******',
                'scope': 'read write manage'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'invalid_scope', HttpBadRequestException)
    def test_metadata(self):
        """
        Validates the authentication related information at the API root's metadata.
        - The 'roles' key is already checked in the Scope-related tests
        """
        from ovs.dal.lists.bearertokenlist import BearerTokenList
        from api.oauth2.tokenview import OAuth2TokenView
        from api.view import MetadataView

        def _raise_exception(argument):
            _ = argument
            raise RuntimeError('foobar')

        result_data = {
            'authenticated': False,
            'authentication_state': None,
            'username': None,
            'userguid': None
        }

        time.sleep(180)
        data = {
            'grant_type': 'password',
            'username': '******',
            'password': '******'
        }
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('expires_in', response_content)
        self.assertIn('access_token', response_content)

        time.sleep(180)
        expiry = int(response_content['expires_in'])
        access_token = response_content['access_token']
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1')
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'unauthenticated'}.items()),
            response_content)

        time.sleep(180)
        header = 'Basic foobar'
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'invalid_authorization_type'
                  }.items()), response_content)

        time.sleep(180)
        header = 'Bearer foobar'
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'invalid_token'}.items()),
            response_content)

        time.sleep(180)
        user = UserList.get_user_by_username('admin')
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(
                result_data.items() + {
                    'authenticated': True,
                    'authentication_state': 'authenticated',
                    'username': user.username,
                    'userguid': user.guid
                }.items()), response_content)

        time.sleep(180)
        user.is_active = False
        user.save()
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'inactive_user'}.items()),
            response_content)
        user.is_active = True
        user.save()

        time.sleep(180)
        original_method = BearerTokenList.get_by_access_token
        BearerTokenList.get_by_access_token = staticmethod(_raise_exception)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'unexpected_exception'}.items()),
            response_content)

        time.sleep(180)
        BearerTokenList.get_by_access_token = staticmethod(original_method)
        time.sleep(expiry)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'token_expired'}.items()),
            response_content)
Exemple #4
0
def build_router_urls():
    """
    Creates a router instance to generate API urls for Customer and Internal API
    """
    routes = []
    path = '/'.join([os.path.dirname(__file__), 'backend', 'views'])
    for filename in os.listdir(path):
        if os.path.isfile('/'.join([path, filename])) and filename.endswith('.py'):
            name = filename.replace('.py', '')
            module = imp.load_source(name, '/'.join([path, filename]))
            for member in inspect.getmembers(module):
                if inspect.isclass(member[1]) \
                        and member[1].__module__ == name \
                        and 'ViewSet' in [base.__name__ for base in member[1].__bases__]:
                    routes.append({'prefix': member[1].prefix,
                                   'viewset': member[1],
                                   'base_name': member[1].base_name})
    router = SimpleRouter()
    for route in routes:
        router.register(**route)
    return router.urls

urlpatterns = patterns('',
                       url(r'^oauth2/token/', OAuth2TokenView.as_view()),
                       url(r'^oauth2/redirect/', OAuth2RedirectView.as_view()),
                       url(r'^relay/', relay),
                       url(r'^swagger.json', OpenAPIView.as_view()),
                       url(r'^$', MetadataView.as_view()),
                       url(r'', include(build_router_urls())))
Exemple #5
0
    """
    routes = []
    path = '/'.join([os.path.dirname(__file__), 'backend', 'views'])
    for filename in os.listdir(path):
        if os.path.isfile('/'.join([path, filename
                                    ])) and filename.endswith('.py'):
            name = filename.replace('.py', '')
            mod = imp.load_source(name, '/'.join([path, filename]))
            for member_name, member in inspect.getmembers(
                    mod, predicate=inspect.isclass):
                if member.__module__ == name and 'ViewSet' in [
                        base.__name__ for base in member.__bases__
                ]:
                    routes.append({
                        'prefix': member.prefix,
                        'viewset': member,
                        'base_name': member.base_name
                    })
    router = OVSRouter()
    for route in routes:
        router.register(**route)
    return router.urls


urlpatterns = patterns('', url(r'^oauth2/token/', OAuth2TokenView.as_view()),
                       url(r'^oauth2/redirect/', OAuth2RedirectView.as_view()),
                       url(r'^relay/', relay),
                       url(r'^swagger.json', OpenAPIView.as_view()),
                       url(r'^$', MetadataView.as_view()),
                       url(r'', include(build_router_urls())))
    def test_metadata(self):
        """
        Validates the authentication related information at the API root's metadata.
        - The 'roles' key is already checked in the Scope-related tests
        """
        from ovs.dal.lists.bearertokenlist import BearerTokenList
        from api.oauth2.tokenview import OAuth2TokenView
        from api.view import MetadataView

        def _raise_exception(argument):
            _ = argument
            raise RuntimeError('foobar')

        result_data = {'authenticated': False,
                       'authentication_state': None,
                       'username': None,
                       'userguid': None}

        time.sleep(180)
        data = {'grant_type': 'password',
                'username': '******',
                'password': '******'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('expires_in', response_content)
        self.assertIn('access_token', response_content)

        time.sleep(180)
        expiry = int(response_content['expires_in'])
        access_token = response_content['access_token']
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1')
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'unauthenticated'}.items()), response_content)

        time.sleep(180)
        header = 'Basic foobar'
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'invalid_authorization_type'}.items()), response_content)

        time.sleep(180)
        header = 'Bearer foobar'
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'invalid_token'}.items()), response_content)

        time.sleep(180)
        user = UserList.get_user_by_username('admin')
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authenticated': True,
                                                                  'authentication_state': 'authenticated',
                                                                  'username': user.username,
                                                                  'userguid': user.guid}.items()), response_content)

        time.sleep(180)
        user.is_active = False
        user.save()
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'inactive_user'}.items()), response_content)
        user.is_active = True
        user.save()

        time.sleep(180)
        original_method = BearerTokenList.get_by_access_token
        BearerTokenList.get_by_access_token = staticmethod(_raise_exception)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'unexpected_exception'}.items()), response_content)

        time.sleep(180)
        BearerTokenList.get_by_access_token = staticmethod(original_method)
        time.sleep(expiry)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'token_expired'}.items()), response_content)