Ticket #16827: patch_16827.diff

File patch_16827.diff, 1.9 KB (added by Zbigniew Siciarz, 9 years ago)

Provided test for the token length.

  • django/middleware/csrf.py

    diff --git a/django/middleware/csrf.py b/django/middleware/csrf.py
    index 37f92b1..c25e4d6 100644
    a b def get_token(request): 
    5959def _sanitize_token(token):
    6060    # Allow only alphanum, and ensure we return a 'str' for the sake of the post
    6161    # processing middleware.
    62     token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore')))
     62    # Token length is implied from using MD5 hash.
     63    if len(token) >= 32:
     64        token = ""
     65    else:
     66        token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore')))
    6367    if token == "":
    6468        # In case the cookie has been truncated to nothing at some point.
    6569        return _get_new_csrf_key()
  • tests/regressiontests/csrf_tests/tests.py

    diff --git a/tests/regressiontests/csrf_tests/tests.py b/tests/regressiontests/csrf_tests/tests.py
    index 6e6c87a..4eb6ba2 100644
    a b class CsrfViewMiddlewareTest(TestCase): 
    100100        self.assertEqual(csrf_cookie['path'], '/test/')
    101101        self.assertTrue('Cookie' in resp2.get('Vary',''))
    102102
     103    def test_process_view_token_too_long(self):
     104        u"""
     105        Check that if the token is longer than expected, it is ignored and
     106        a new token is created.
     107        """
     108        req = self._get_GET_no_csrf_cookie_request()
     109        req.COOKIES[settings.CSRF_COOKIE_NAME] = 'x' * 10000000
     110        CsrfViewMiddleware().process_view(req, token_view, (), {})
     111        resp = token_view(req)
     112        resp2 = CsrfViewMiddleware().process_response(req, resp)
     113        csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)
     114        self.assertEqual(len(csrf_cookie.value), 32)
     115
    103116    def test_process_response_get_token_not_used(self):
    104117        """
    105118        Check that if get_token() is not called, the view middleware does not
Back to Top