Esempio n. 1
0
    def test_invalid_grant_type(self):
        """This test ensures that invalid grant_type parameters get the
        appropriate error response.
        """

        # Generate a valid auth token
        with base.HybridSessionManager():
            authorization_code = auth_api.authorization_code_save({
                'user_id':
                2,
                'state':
                'test_state',
                'code':
                'test_valid_code',
                'expires_in':
                300
            })

        content_type = 'application/x-www-form-urlencoded'
        # POST with content: application/x-www-form-urlencoded
        response = self.app.post('/v1/openid/token',
                                 params={
                                     'code': authorization_code.code,
                                     'grant_type': 'invalid_grant_type'
                                 },
                                 content_type=content_type,
                                 expect_errors=True)

        # Assert that this is a successful response
        self.assertEqual(400, response.status_code)
        self.assertIsNotNone(response.json)
        self.assertEqual('unsupported_grant_type', response.json['error'])
        self.assertEqual(e_msg.INVALID_TOKEN_GRANT_TYPE,
                         response.json['error_description'])
Esempio n. 2
0
    def test_handle(self):
        """Assert that the handle method passes the correct values on."""
        worker_base = MockEmailWorkerBase({})

        with base.HybridSessionManager():
            session = db_api_base.get_session()
            user_1 = db_api_base.entity_get(models.User, 1, session=session)

            worker_base.handle(session=session,
                               author=user_1,
                               method='POST',
                               url='http://localhost/',
                               path='/test',
                               query_string='',
                               status=201,
                               resource='story',
                               resource_id=1)

            self.assertIsInstance(worker_base.handled_values['author'],
                                  models.User)
            self.assertEqual(1, worker_base.handled_values['author'].id)

            self.assertEqual(2, len(worker_base.handled_values['subscribers']))
            self.assertEqual('POST', worker_base.handled_values['method'])
            self.assertEqual(201, worker_base.handled_values['status'])
            self.assertEqual('/test', worker_base.handled_values['path'])
            self.assertEqual('story', worker_base.handled_values['resource'])
            self.assertEqual(1, worker_base.handled_values['resource_id'])
Esempio n. 3
0
    def test_valid_response_request(self, mock_post):
        """This test ensures that the authorize request against the oauth
        endpoint succeeds with expected values.
        """
        self._mock_response(mock_post, valid=True)

        random_state = six.text_type(uuid.uuid4())

        # Simple GET with various parameters
        response = self.get_json(path='/openid/authorize_return',
                                 expect_errors=True,
                                 state=random_state,
                                 **self.valid_params)

        # Try to pull the code out of the response
        location = response.headers.get('Location')
        location_url = urlparse.urlparse(location)
        parameters = urlparse.parse_qs(location_url[4])

        with base.HybridSessionManager():
            token = auth_api.authorization_code_get(parameters['code'])

        redirect_uri = self.valid_params['sb_redirect_uri']
        # Validate the redirect response
        self.assertValidRedirect(response=response,
                                 expected_status_code=302,
                                 redirect_uri=redirect_uri,
                                 state=token.state,
                                 code=token.code)
Esempio n. 4
0
    def test_expired_access_token_time(self):
        """This test ensures that an access token is seen as expired if
        storyboard is installed in multiple timezones.
        """

        expired = datetime.datetime.now(
            pytz.utc) - datetime.timedelta(minutes=6)

        # Store the old TZ info, if it exists.
        old_tz = None
        if 'TZ' in os.environ:
            old_tz = os.environ['TZ']

        # Convert now into every possible timezone out there :)
        for name in self.tested_timezones:

            # Override the 'default timezone' for the current runtime.
            os.environ['TZ'] = name

            # Create a token.
            with base.HybridSessionManager():
                authorization_code = auth_api.authorization_code_save({
                    'user_id':
                    2,
                    'state':
                    'test_state',
                    'code':
                    'test_valid_code',
                    'expires_in':
                    300,
                    'created_at':
                    expired
                })

            content_type = 'application/x-www-form-urlencoded'
            # POST with content: application/x-www-form-urlencoded
            response = self.app.post('/v1/openid/token',
                                     params={
                                         'code': authorization_code.code,
                                         'grant_type': 'authorization_code'
                                     },
                                     content_type=content_type,
                                     expect_errors=True)

            # Assert that this is a valid call.
            self.assertEqual(401, response.status_code)

            # Reset the timezone.
            if old_tz:
                os.environ['TZ'] = old_tz
            else:
                del os.environ['TZ']
Esempio n. 5
0
    def test_get_preference(self):
        """Assert that the get_preference method functions as expected."""
        worker_base = MockEmailWorkerBase({})

        with base.HybridSessionManager():
            session = db_api_base.get_session()
            user_1 = db_api_base.entity_get(models.User, 1, session=session)

            foo_value = worker_base.get_preference('foo', user_1)
            self.assertEqual('bar', foo_value)

            no_value = worker_base.get_preference('no_value', user_1)
            self.assertIsNone(no_value)
Esempio n. 6
0
    def test_get_subscribers(self):
        """Assert that the get_subscribers method functions as expected."""
        worker_base = MockEmailWorkerBase({})

        with base.HybridSessionManager():
            session = db_api_base.get_session()

            # Users 1 and 3 are subscribed to this story, user 1 as digest
            # and user 3 as individual emails.
            subscribers = worker_base.get_subscribers(session, 'story', 1)
            self.assertEqual(2, len(subscribers))
            self.assertEqual(1, subscribers[0].id)
            self.assertEqual(3, subscribers[1].id)
Esempio n. 7
0
    def test_valid_access_token_time(self):
        """Assert that a newly created access token is valid if storyboard is
        installed in a multitude of timezones.
        """

        # Store the old TZ info, if it exists.
        old_tz = None
        if 'TZ' in os.environ:
            old_tz = os.environ['TZ']

        # Convert now into every possible timezone out there :)
        for name in self.tested_timezones:

            # Override the 'default timezone' for the current runtime.
            os.environ['TZ'] = name

            # Create a token.
            with base.HybridSessionManager():
                authorization_code = auth_api.authorization_code_save({
                    'user_id':
                    2,
                    'state':
                    'test_state',
                    'code':
                    'test_valid_code',
                    'expires_in':
                    300
                })

            response = self.app.post(
                '/v1/openid/token',
                params={
                    'code': authorization_code.code,
                    'grant_type': 'authorization_code'
                },
                content_type='application/x-www-form-urlencoded',
                expect_errors=True)

            # Assert that this is a valid call.
            self.assertEqual(200, response.status_code)

            # Reset the timezone.
            if old_tz:
                os.environ['TZ'] = old_tz
            else:
                del os.environ['TZ']
Esempio n. 8
0
    def test_resolve_by_name(self):
        '''Assert that resolve_resource_by_name works.'''

        worker = TestWorkerPlugin({})

        with base.HybridSessionManager():
            session = db_api_base.get_session()

            task = worker.resolve_resource_by_name(session, 'task', 1)
            self.assertIsNotNone(task)
            self.assertEqual(1, task.id)

            project_group = worker.resolve_resource_by_name(
                session, 'project_group', 1)
            self.assertIsNotNone(project_group)
            self.assertEqual(1, project_group.id)

            project = worker.resolve_resource_by_name(session, 'project', 1)
            self.assertIsNotNone(project)
            self.assertEqual(1, project.id)

            user = worker.resolve_resource_by_name(session, 'user', 1)
            self.assertIsNotNone(user)
            self.assertEqual(1, user.id)

            team = worker.resolve_resource_by_name(session, 'team', 1)
            self.assertIsNotNone(team)
            self.assertEqual(1, team.id)

            story = worker.resolve_resource_by_name(session, 'story', 1)
            self.assertIsNotNone(story)
            self.assertEqual(1, story.id)

            branch = worker.resolve_resource_by_name(session, 'branch', 1)
            self.assertIsNotNone(branch)
            self.assertEqual(1, branch.id)

            milestone = worker.resolve_resource_by_name(
                session, 'milestone', 1)
            self.assertIsNotNone(milestone)
            self.assertEqual(1, milestone.id)
Esempio n. 9
0
    def test_handle_email(self, get_smtp_client):
        """Make sure that events from the queue are sent as emails."""
        dummy_smtp = mock.Mock(smtplib.SMTP)
        worker_base = SubscriptionEmailWorker({})
        get_smtp_client.return_value.__enter__ = dummy_smtp

        with base.HybridSessionManager():
            session = db_api_base.get_session()
            author = db_api_base.entity_get(models.User, 2, session=session)
            story = db_api_base.entity_get(models.Story, 1, session=session)
            story_dict = story.as_dict()
            story_after_dict = copy.copy(story_dict)
            story_after_dict['title'] = 'New Test Title'

            subscribers = worker_base.get_subscribers(session, 'story', 1)
            self.assertEqual(2, len(subscribers))

            worker_base.handle_email(session=session,
                                     author=author,
                                     subscribers=subscribers,
                                     method='PUT',
                                     url='http://localhost/',
                                     path='/stories/1',
                                     query_string='',
                                     status=200,
                                     resource='story',
                                     resource_id=1,
                                     resource_before=story_dict,
                                     resource_after=story_after_dict)
            # There should be two subscribers, but only one should get an
            # email since the other is a digest receiver.

            subscribed_user = db_api_base.entity_get(models.User,
                                                     3,
                                                     session=session)
            self.assertEqual(dummy_smtp.return_value.sendmail.call_count, 1)
            self.assertEqual(
                dummy_smtp.return_value.sendmail.call_args[1]['to_addrs'],
                subscribed_user.email)
Esempio n. 10
0
    def test_valid_refresh_token(self):
        """This test ensures that a valid refresh token can be converted into
        a valid access token, and cleans up after itself.
        """

        # Generate a valid access code
        with base.HybridSessionManager():
            authorization_code = auth_api.authorization_code_save({
                'user_id':
                2,
                'state':
                'test_state',
                'code':
                'test_valid_code'
            })

        content_type = 'application/x-www-form-urlencoded'
        # Generate an auth and a refresh token.
        resp_1 = self.app.post('/v1/openid/token',
                               params={
                                   'code': authorization_code.code,
                                   'grant_type': 'authorization_code'
                               },
                               content_type=content_type,
                               expect_errors=True)

        # Assert that this is a successful response
        self.assertEqual(200, resp_1.status_code)

        # Assert that the token came back in the response
        t1 = resp_1.json

        # Assert that both are in the database.
        with base.HybridSessionManager():
            access_token = \
                token_api.access_token_get_by_token(t1['access_token'])
        self.assertIsNotNone(access_token)

        with base.HybridSessionManager():
            refresh_token = refresh_tokens.refresh_token_get_by_token(
                t1['refresh_token'])

        self.assertIsNotNone(refresh_token)

        content_type = 'application/x-www-form-urlencoded'
        # Issue a refresh token request.
        resp_2 = self.app.post('/v1/openid/token',
                               params={
                                   'refresh_token': t1['refresh_token'],
                                   'grant_type': 'refresh_token'
                               },
                               content_type=content_type,
                               expect_errors=True)

        # Assert that the response is good.
        self.assertEqual(200, resp_2.status_code)

        # Assert that the token came back in the response
        t2 = resp_2.json
        self.assertIsNotNone(t2['access_token'])
        self.assertIsNotNone(t2['expires_in'])
        self.assertIsNotNone(t2['id_token'])
        self.assertIsNotNone(t2['refresh_token'])
        self.assertIsNotNone(t2['token_type'])
        self.assertEqual('Bearer', t2['token_type'])

        # Assert that the access token is in the database
        with base.HybridSessionManager():
            new_access_token = \
                token_api.access_token_get_by_token(t2['access_token'])
        self.assertIsNotNone(new_access_token)

        # Assert that system configured values is owned by the correct user.
        self.assertEqual(2, new_access_token.user_id)
        self.assertEqual(t2['id_token'], new_access_token.user_id)
        self.assertEqual(t2['expires_in'], CONF.oauth.access_token_ttl)
        self.assertEqual(t2['expires_in'], new_access_token.expires_in)
        self.assertEqual(t2['access_token'], new_access_token.access_token)

        # Assert that the refresh token is in the database

        with base.HybridSessionManager():
            new_refresh_token = refresh_tokens.refresh_token_get_by_token(
                t2['refresh_token'])

        self.assertIsNotNone(new_refresh_token)

        # Assert that system configured values is owned by the correct user.
        self.assertEqual(2, new_refresh_token.user_id)
        self.assertEqual(CONF.oauth.refresh_token_ttl,
                         new_refresh_token.expires_in)
        self.assertEqual(t2['refresh_token'], new_refresh_token.refresh_token)

        # Assert that the old access tokens are no longer in the database and
        # have been cleaned up.

        with base.HybridSessionManager():
            no_access_token = \
                token_api.access_token_get_by_token(t1['access_token'])
        with base.HybridSessionManager():
            no_refresh_token = \
                refresh_tokens.refresh_token_get_by_token(t1['refresh_token'])

        self.assertIsNone(no_refresh_token)
        self.assertIsNone(no_access_token)
Esempio n. 11
0
    def test_valid_access_request(self):
        """This test ensures that the access token request may execute
        properly with a valid token.
        """

        # Generate a valid auth token
        with base.HybridSessionManager():
            authorization_code = auth_api.authorization_code_save({
                'user_id':
                2,
                'state':
                'test_state',
                'code':
                'test_valid_code'
            })

        content_type = 'application/x-www-form-urlencoded'
        # POST with content: application/x-www-form-urlencoded
        response = self.app.post('/v1/openid/token',
                                 params={
                                     'code': authorization_code.code,
                                     'grant_type': 'authorization_code'
                                 },
                                 content_type=content_type,
                                 expect_errors=True)

        # Assert that this is a successful response
        self.assertEqual(200, response.status_code)

        # Assert that the token came back in the response
        token = response.json
        self.assertIsNotNone(token['access_token'])
        self.assertIsNotNone(token['expires_in'])
        self.assertIsNotNone(token['id_token'])
        self.assertIsNotNone(token['refresh_token'])
        self.assertIsNotNone(token['token_type'])
        self.assertEqual('Bearer', token['token_type'])

        # Assert that the access token is in the database
        with base.HybridSessionManager():
            access_token = \
                token_api.access_token_get_by_token(token['access_token'])
        self.assertIsNotNone(access_token)

        # Assert that system configured values is owned by the correct user.
        self.assertEqual(2, access_token.user_id)
        self.assertEqual(token['id_token'], access_token.user_id)
        self.assertEqual(token['expires_in'], CONF.oauth.access_token_ttl)
        self.assertEqual(token['expires_in'], access_token.expires_in)
        self.assertEqual(token['access_token'], access_token.access_token)

        # Assert that the refresh token is in the database
        with base.HybridSessionManager():
            refresh_token = \
                refresh_tokens.refresh_token_get_by_token(
                    token['refresh_token'])

        self.assertIsNotNone(refresh_token)

        # Assert that system configured values is owned by the correct user.
        self.assertEqual(2, refresh_token.user_id)
        self.assertEqual(CONF.oauth.refresh_token_ttl,
                         refresh_token.expires_in)
        self.assertEqual(token['refresh_token'], refresh_token.refresh_token)

        # Assert that the authorization code is no longer in the database.
        with base.HybridSessionManager():
            none_code = \
                auth_api.authorization_code_get(authorization_code.code)
        self.assertIsNone(none_code)