Esempio n. 1
0
    def test_append_random_comment(self):
        html = '''<html>
    <head><title>Test</title></head>
    <body><p>Test body.</p></body>
</html>'''

        @append_random_comment
        def test_view(request):
            return HttpResponse(html)

        request = RequestFactory().get('/')
        response = test_view(request)
        self.assertNotEqual(force_text(response.content), html)
        self.assertIn('<!-- ', force_text(response.content))
        self.assertIn(' -->', force_text(response.content))
Esempio n. 2
0
    def test_unicode_characters(self):
        html = '''<!doctype html>
<html>
    <head>
        <title>Page title</title>
    </head>
    <body>
        <h1>Test</h1>
        <p>{0}</p>
    </body>
</html>'''.format(''.join(chr(x) for x in range(9999)))
        response = HttpResponse(html, content_type='text/html')
        request = RequestFactory().get('/')
        middleware = RandomCommentMiddleware()
        response = middleware.process_response(request, response)
        self.assertNotEqual(force_text(response.content), force_text(html))
 def _get_val():
     token = get_token(request)
     if token is None:
         # In order to be able to provide debugging info in the
         # case of misconfiguration, we use a sentinel value
         # instead of returning an empty dict.
         return 'NOTPROVIDED'
     else:
         key = force_bytes(get_random_string(16))
         aes = AES.new(key)
         pad_length = 16 - (len(token) % 16 or 16)
         padding = ''.join('#' for _ in range(pad_length))
         value = base64.b64encode(
             aes.encrypt('{0}{1}'.format(token, padding))
         )
         token = '$'.join((force_text(key), force_text(value)))
         return force_text(token)
Esempio n. 4
0
 def test_round_trip_loop(self):
     '''
     Checks a wide range of input tokens and keys
     '''
     for _ in range(1000):
         request = RequestFactory().get('/')
         csrf_token = get_random_string(32)
         request.META['CSRF_COOKIE'] = csrf_token
         token = force_text(csrf(request)['csrf_token'])
         request = RequestFactory().post(
             '/', {'csrfmiddlewaretoken': token})
         middleware = CSRFCryptMiddleware()
         middleware.process_request(request)
         self.assertEqual(
             force_text(request.POST.get('csrfmiddlewaretoken')),
             force_text(csrf_token)
         )
Esempio n. 5
0
 def process_response(self, request, response):
     if not getattr(response, 'streaming', False) \
             and response['Content-Type'] == 'text/html' \
             and isinstance(response.content, string_types):
         comment = '<!-- {0} -->'.format(
             get_random_string(random.choice(range(12, 25))))
         response.content = '{0}{1}'.format(
             force_text(response.content), comment)
     return response
Esempio n. 6
0
 def test_round_trip_loop_header(self):
     '''
     Checks a wide range of input tokens and keys
     '''
     for _ in range(1000):
         request = RequestFactory().get('/')
         csrf_token = get_random_string(32)
         request.META['CSRF_COOKIE'] = csrf_token
         token = csrf(request)['csrf_token']
         request = RequestFactory().post(
             '/',
             HTTP_X_CSRFTOKEN=force_text(token),
             HTTP_X_REQUESTED_WITH='XMLHttpRequest'
         )
         middleware = CSRFCryptMiddleware()
         middleware.process_request(request)
         self.assertEqual(
             force_text(request.META.get('HTTP_X_CSRFTOKEN')),
             force_text(csrf_token)
         )
Esempio n. 7
0
    def test_exemption(self):
        html = '''<html>
    <head><title>Test</title></head>
    <body><p>Test body.</p></body>
</html>'''
        response = HttpResponse(html)
        response._random_comment_exempt = True
        request = RequestFactory().get('/')
        middleware = RandomCommentMiddleware()
        response = middleware.process_response(request, response)
        self.assertEqual(force_text(response.content), html)
Esempio n. 8
0
 def process_response(self, request, response):
     str_types = string_types + (binary_type,)
     if (
         not getattr(response, "streaming", False)
         and response.get("Content-Type", "").startswith("text/html")
         and response.content
         and isinstance(response.content, str_types)
         and not getattr(response, "_random_comment_exempt", False)
     ):
         comment = "<!-- {0} -->".format(get_random_string(random.choice(range(12, 25))))
         response.content = "{0}{1}".format(force_text(response.content), comment)
     return response
Esempio n. 9
0
 def test_crypt_csrf_token(self):
     resp = self.client.get(reverse('test_form'))
     m = re.search(
         r'value=\'(.*\$.*)\'',
         force_text(resp.content),
         re.MULTILINE | re.DOTALL
     )
     self.assertEqual(len(m.groups()), 1)
     token = m.groups()[0].strip()
     post_resp = self.client.post(
         reverse('test_form'),
         {'csrfmiddlewaretoken': token, 'message': 'Some rubbish'}
     )
     self.assertRedirects(post_resp, reverse('home'))
Esempio n. 10
0
 def test_csrf(self):
     request = RequestFactory().get('/')
     request.META['CSRF_COOKIE'] = 'abc123'
     context = csrf(request)
     self.assertTrue(force_text(context['csrf_token']))
     self.assertNotEqual(force_text(context['csrf_token']), 'abc123')
Esempio n. 11
0
 def test_no_token_csrf(self):
     request = RequestFactory().get('/')
     context = csrf(request)
     self.assertTrue(force_text(context['csrf_token']))
     self.assertEqual(force_text(context['csrf_token']), 'NOTPROVIDED')