Exemple #1
0
 def _assert_recreate_jwt_from_cookies(self, response, can_recreate):
     """
     Verifies that a JWT can be properly recreated from the 2 separate
     JWT-related cookies using the JwtAuthCookieMiddleware middleware.
     """
     self.request.COOKIES = response.cookies
     JwtAuthCookieMiddleware().process_request(self.request)
     self.assertEqual(
         cookies_api.jwt_cookies.jwt_cookie_name() in self.request.COOKIES,
         can_recreate,
     )
Exemple #2
0
class TestJwtAuthCookieMiddleware(TestCase):
    def setUp(self):
        super(TestJwtAuthCookieMiddleware, self).setUp()
        self.request = RequestFactory().get('/')
        self.middleware = JwtAuthCookieMiddleware()

    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_do_not_use_jwt_cookies(self, mock_set_custom_metric):
        self.middleware.process_request(self.request)
        self.assertIsNone(self.request.COOKIES.get(jwt_cookie_name()))
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie',
                                                       'not-requested')

    @ddt.data(
        (jwt_cookie_header_payload_name(), jwt_cookie_signature_name()),
        (jwt_cookie_signature_name(), jwt_cookie_header_payload_name()),
    )
    @ddt.unpack
    @patch('edx_rest_framework_extensions.auth.jwt.middleware.log')
    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_missing_cookies(self, set_cookie_name, missing_cookie_name,
                             mock_set_custom_metric, mock_log):
        self.request.META[USE_JWT_COOKIE_HEADER] = 'true'
        self.request.COOKIES[set_cookie_name] = 'test'
        self.middleware.process_request(self.request)
        self.assertIsNone(self.request.COOKIES.get(jwt_cookie_name()))
        mock_log.warning.assert_called_once_with(
            '%s cookie is missing. JWT auth cookies will not be reconstituted.'
            % missing_cookie_name)
        mock_set_custom_metric.assert_called_once_with(
            'request_jwt_cookie', 'missing-{}'.format(missing_cookie_name))

    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_no_cookies(self, mock_set_custom_metric):
        self.request.META[USE_JWT_COOKIE_HEADER] = 'true'
        self.middleware.process_request(self.request)
        self.assertIsNone(self.request.COOKIES.get(jwt_cookie_name()))
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie',
                                                       'missing-both')

    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_success(self, mock_set_custom_metric):
        self.request.META[USE_JWT_COOKIE_HEADER] = 'true'
        self.request.COOKIES[
            jwt_cookie_header_payload_name()] = 'header.payload'
        self.request.COOKIES[jwt_cookie_signature_name()] = 'signature'
        self.middleware.process_request(self.request)
        self.assertEqual(self.request.COOKIES[jwt_cookie_name()],
                         'header.payload.signature')
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie',
                                                       'success')
class TestJwtAuthCookieMiddleware(TestCase):
    def setUp(self):
        super(TestJwtAuthCookieMiddleware, self).setUp()
        self.request = RequestFactory().get('/')
        self.middleware = JwtAuthCookieMiddleware()

    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_do_not_use_jwt_cookies(self, mock_set_custom_metric):
        self.middleware.process_request(self.request)
        self.assertIsNone(self.request.COOKIES.get(jwt_cookie_name()))
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie', 'not-requested')

    @ddt.data(
        (jwt_cookie_header_payload_name(), jwt_cookie_signature_name()),
        (jwt_cookie_signature_name(), jwt_cookie_header_payload_name()),
    )
    @ddt.unpack
    @patch('edx_rest_framework_extensions.auth.jwt.middleware.log')
    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_missing_cookies(
            self, set_cookie_name, missing_cookie_name, mock_set_custom_metric, mock_log
    ):
        self.request.META[USE_JWT_COOKIE_HEADER] = 'true'
        self.request.COOKIES[set_cookie_name] = 'test'
        self.middleware.process_request(self.request)
        self.assertIsNone(self.request.COOKIES.get(jwt_cookie_name()))
        mock_log.warning.assert_called_once_with(
            '%s cookie is missing. JWT auth cookies will not be reconstituted.' %
            missing_cookie_name
        )
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie', 'missing-{}'.format(missing_cookie_name))

    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_no_cookies(self, mock_set_custom_metric):
        self.request.META[USE_JWT_COOKIE_HEADER] = 'true'
        self.middleware.process_request(self.request)
        self.assertIsNone(self.request.COOKIES.get(jwt_cookie_name()))
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie', 'missing-both')

    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_success(self, mock_set_custom_metric):
        self.request.META[USE_JWT_COOKIE_HEADER] = 'true'
        self.request.COOKIES[jwt_cookie_header_payload_name()] = 'header.payload'
        self.request.COOKIES[jwt_cookie_signature_name()] = 'signature'
        self.middleware.process_request(self.request)
        self.assertEqual(self.request.COOKIES[jwt_cookie_name()], 'header.payload.signature')
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie', 'success')
Exemple #4
0
 def _assert_recreate_jwt_from_cookies(self, response, can_recreate):
     """
     If can_recreate is True, verifies that a JWT can be properly recreated
     from the 2 separate JWT-related cookies using the
     JwtAuthCookieMiddleware middleware and returns the recreated JWT.
     If can_recreate is False, verifies that a JWT cannot be recreated.
     """
     self._copy_cookies_to_request(response, self.request)
     JwtAuthCookieMiddleware().process_view(self.request, None, None, None)
     assert (cookies_api.jwt_cookies.jwt_cookie_name()
             in self.request.COOKIES) == can_recreate
     if can_recreate:
         jwt_string = self.request.COOKIES[
             cookies_api.jwt_cookies.jwt_cookie_name()]
         jwt = jwt_decode_handler(jwt_string)
         assert jwt['scopes'] == ['user_id', 'email', 'profile']
 def setUp(self):
     super(TestJwtAuthCookieMiddleware, self).setUp()
     self.request = RequestFactory().get('/')
     self.middleware = JwtAuthCookieMiddleware()
Exemple #6
0
 def setUp(self):
     super(TestJwtAuthCookieMiddleware, self).setUp()
     self.request = RequestFactory().get('/')
     self.middleware = JwtAuthCookieMiddleware()
class TestJwtAuthCookieMiddleware(TestCase):
    def setUp(self):
        super(TestJwtAuthCookieMiddleware, self).setUp()
        self.request = RequestFactory().get('/')
        self.request.session = 'mock session'
        self.middleware = JwtAuthCookieMiddleware()

    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_do_not_use_jwt_cookies(self, mock_set_custom_metric):
        self.middleware.process_view(self.request, None, None, None)
        self.assertIsNone(self.request.COOKIES.get(jwt_cookie_name()))
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie',
                                                       'not-requested')

    @ddt.data(
        (jwt_cookie_header_payload_name(), jwt_cookie_signature_name()),
        (jwt_cookie_signature_name(), jwt_cookie_header_payload_name()),
    )
    @ddt.unpack
    @patch('edx_rest_framework_extensions.auth.jwt.middleware.log')
    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_missing_cookies(self, set_cookie_name, missing_cookie_name,
                             mock_set_custom_metric, mock_log):
        self.request.META[USE_JWT_COOKIE_HEADER] = 'true'
        self.request.COOKIES[set_cookie_name] = 'test'
        self.middleware.process_view(self.request, None, None, None)
        self.assertIsNone(self.request.COOKIES.get(jwt_cookie_name()))
        mock_log.warning.assert_called_once_with(
            '%s cookie is missing. JWT auth cookies will not be reconstituted.'
            % missing_cookie_name)
        mock_set_custom_metric.assert_called_once_with(
            'request_jwt_cookie', 'missing-{}'.format(missing_cookie_name))

    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_no_cookies(self, mock_set_custom_metric):
        self.request.META[USE_JWT_COOKIE_HEADER] = 'true'
        self.middleware.process_view(self.request, None, None, None)
        self.assertIsNone(self.request.COOKIES.get(jwt_cookie_name()))
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie',
                                                       'missing-both')

    @patch('edx_django_utils.monitoring.set_custom_metric')
    def test_success(self, mock_set_custom_metric):
        self.request.META[USE_JWT_COOKIE_HEADER] = 'true'
        self.request.COOKIES[
            jwt_cookie_header_payload_name()] = 'header.payload'
        self.request.COOKIES[jwt_cookie_signature_name()] = 'signature'
        self.middleware.process_view(self.request, None, None, None)
        self.assertEqual(self.request.COOKIES[jwt_cookie_name()],
                         'header.payload.signature')
        mock_set_custom_metric.assert_called_once_with('request_jwt_cookie',
                                                       'success')

    _LOG_WARN_AUTHENTICATION_FAILED = 0
    _LOG_WARN_MISSING_JWT_AUTHENTICATION_CLASS = 1

    @patch('edx_rest_framework_extensions.auth.jwt.middleware.log')
    @ddt.data(
        ('/nopermissionsrequired/', True, True, True, None),
        ('/nopermissionsrequired/', True, False, False, None),
        ('/nopermissionsrequired/', False, False, True,
         _LOG_WARN_AUTHENTICATION_FAILED),
        ('/nopermissionsrequired/', False, False, False, None),
        ('/unauthenticated/', True, False, True,
         _LOG_WARN_MISSING_JWT_AUTHENTICATION_CLASS),
        ('/unauthenticated/', True, False, False, None),
    )
    @ddt.unpack
    def test_set_request_user_with_use_jwt_cookie(
        self,
        url,
        is_cookie_valid,
        is_request_user_set,
        is_toggle_enabled,
        log_warning,
        mock_log,
    ):
        header = {USE_JWT_COOKIE_HEADER: 'true'}
        self.client.cookies = _get_test_cookie(is_cookie_valid=is_cookie_valid)
        check_user_middleware_assertion_class = (
            'CheckRequestUserForJwtAuthMiddleware' if is_request_user_set else
            'CheckRequestUserAnonymousForJwtAuthMiddleware')
        with override_settings(
                ROOT_URLCONF=
                'edx_rest_framework_extensions.auth.jwt.tests.test_middleware',
                MIDDLEWARE=
            (
                'django.contrib.sessions.middleware.SessionMiddleware',
                'edx_rest_framework_extensions.auth.jwt.middleware.JwtAuthCookieMiddleware',
                'django.contrib.auth.middleware.AuthenticationMiddleware',
                'edx_rest_framework_extensions.auth.jwt.tests.test_middleware.{}'
                .format(check_user_middleware_assertion_class),
            ),
                EDX_DRF_EXTENSIONS={
                    ENABLE_SET_REQUEST_USER_FOR_JWT_COOKIE: is_toggle_enabled,
                }):
            response = self.client.get(url, **header)
            self.assertEqual(200, response.status_code)

            if log_warning == self._LOG_WARN_AUTHENTICATION_FAILED:
                mock_log.warning.assert_called_once_with(
                    'Jwt Authentication failed and request.user could not be set.'
                )
            elif log_warning == self._LOG_WARN_MISSING_JWT_AUTHENTICATION_CLASS:
                mock_log.warning.assert_called_once_with(
                    'Jwt Authentication expected, but view %s is not using a JwtAuthentication class.',
                    ANY)
            else:
                mock_log.warn.assert_not_called()
Exemple #8
0
 def setUp(self):
     super().setUp()
     self.request = RequestFactory().get('/')
     self.request.session = 'mock session'
     self.middleware = JwtAuthCookieMiddleware()  # pylint: disable=no-value-for-parameter