tests.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import logging
  4. import re
  5. import warnings
  6. from django.conf import settings
  7. from django.core.exceptions import ImproperlyConfigured
  8. from django.http import HttpRequest, HttpResponse
  9. from django.middleware.csrf import (
  10. CSRF_SESSION_KEY, CSRF_TOKEN_LENGTH, REASON_BAD_TOKEN,
  11. REASON_NO_CSRF_COOKIE, CsrfViewMiddleware,
  12. _compare_salted_tokens as equivalent_tokens, get_token,
  13. )
  14. from django.template import RequestContext, Template
  15. from django.template.context_processors import csrf
  16. from django.test import SimpleTestCase, override_settings
  17. from django.test.utils import patch_logger
  18. from django.utils.encoding import force_bytes
  19. from django.utils.six import text_type
  20. from django.views.decorators.csrf import (
  21. csrf_exempt, ensure_csrf_cookie, requires_csrf_token,
  22. )
  23. # Response/views used for CsrfResponseMiddleware and CsrfViewMiddleware tests
  24. def post_form_response():
  25. resp = HttpResponse(content="""
  26. <html><body><h1>\u00a1Unicode!<form method="post"><input type="text" /></form></body></html>
  27. """, mimetype="text/html")
  28. return resp
  29. def post_form_view(request):
  30. """A view that returns a POST form (without a token)"""
  31. return post_form_response()
  32. # Response/views used for template tag tests
  33. def token_view(request):
  34. """A view that uses {% csrf_token %}"""
  35. context = RequestContext(request, processors=[csrf])
  36. template = Template("{% csrf_token %}")
  37. return HttpResponse(template.render(context))
  38. def non_token_view_using_request_processor(request):
  39. """
  40. A view that doesn't use the token, but does use the csrf view processor.
  41. """
  42. context = RequestContext(request, processors=[csrf])
  43. template = Template("")
  44. return HttpResponse(template.render(context))
  45. class TestingHttpRequest(HttpRequest):
  46. """
  47. A version of HttpRequest that allows us to change some things
  48. more easily
  49. """
  50. def __init__(self):
  51. super(TestingHttpRequest, self).__init__()
  52. # A real session backend isn't needed.
  53. self.session = {}
  54. def is_secure(self):
  55. return getattr(self, '_is_secure_override', False)
  56. class CsrfViewMiddlewareTestMixin(object):
  57. """
  58. Shared methods and tests for session-based and cookie-based tokens.
  59. """
  60. _csrf_id = _csrf_id_cookie = '1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD'
  61. def _get_GET_no_csrf_cookie_request(self):
  62. return TestingHttpRequest()
  63. def _get_GET_csrf_cookie_request(self):
  64. raise NotImplementedError('This method must be implemented by a subclass.')
  65. def _get_POST_csrf_cookie_request(self):
  66. req = self._get_GET_csrf_cookie_request()
  67. req.method = "POST"
  68. return req
  69. def _get_POST_no_csrf_cookie_request(self):
  70. req = self._get_GET_no_csrf_cookie_request()
  71. req.method = "POST"
  72. return req
  73. def _get_POST_request_with_token(self):
  74. req = self._get_POST_csrf_cookie_request()
  75. req.POST['csrfmiddlewaretoken'] = self._csrf_id
  76. return req
  77. def _check_token_present(self, response, csrf_id=None):
  78. text = text_type(response.content, response.charset)
  79. match = re.search("name='csrfmiddlewaretoken' value='(.*?)'", text)
  80. csrf_token = csrf_id or self._csrf_id
  81. self.assertTrue(
  82. match and equivalent_tokens(csrf_token, match.group(1)),
  83. "Could not find csrfmiddlewaretoken to match %s" % csrf_token
  84. )
  85. def test_process_response_get_token_not_used(self):
  86. """
  87. If get_token() is not called, the view middleware does not
  88. add a cookie.
  89. """
  90. # This is important to make pages cacheable. Pages which do call
  91. # get_token(), assuming they use the token, are not cacheable because
  92. # the token is specific to the user
  93. req = self._get_GET_no_csrf_cookie_request()
  94. # non_token_view_using_request_processor does not call get_token(), but
  95. # does use the csrf request processor. By using this, we are testing
  96. # that the view processor is properly lazy and doesn't call get_token()
  97. # until needed.
  98. CsrfViewMiddleware().process_view(req, non_token_view_using_request_processor, (), {})
  99. resp = non_token_view_using_request_processor(req)
  100. resp2 = CsrfViewMiddleware().process_response(req, resp)
  101. csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)
  102. self.assertIs(csrf_cookie, False)
  103. # Check the request processing
  104. def test_process_request_no_csrf_cookie(self):
  105. """
  106. If no CSRF cookies is present, the middleware rejects the incoming
  107. request. This will stop login CSRF.
  108. """
  109. with patch_logger('django.security.csrf', 'warning') as logger_calls:
  110. req = self._get_POST_no_csrf_cookie_request()
  111. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  112. self.assertEqual(403, req2.status_code)
  113. self.assertEqual(logger_calls[0], 'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)
  114. def test_process_request_csrf_cookie_no_token(self):
  115. """
  116. If a CSRF cookie is present but no token, the middleware rejects
  117. the incoming request.
  118. """
  119. with patch_logger('django.security.csrf', 'warning') as logger_calls:
  120. req = self._get_POST_csrf_cookie_request()
  121. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  122. self.assertEqual(403, req2.status_code)
  123. self.assertEqual(logger_calls[0], 'Forbidden (%s): ' % REASON_BAD_TOKEN)
  124. def test_process_request_csrf_cookie_and_token(self):
  125. """
  126. If both a cookie and a token is present, the middleware lets it through.
  127. """
  128. req = self._get_POST_request_with_token()
  129. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  130. self.assertIsNone(req2)
  131. def test_process_request_csrf_cookie_no_token_exempt_view(self):
  132. """
  133. If a CSRF cookie is present and no token, but the csrf_exempt decorator
  134. has been applied to the view, the middleware lets it through
  135. """
  136. req = self._get_POST_csrf_cookie_request()
  137. req2 = CsrfViewMiddleware().process_view(req, csrf_exempt(post_form_view), (), {})
  138. self.assertIsNone(req2)
  139. def test_csrf_token_in_header(self):
  140. """
  141. The token may be passed in a header instead of in the form.
  142. """
  143. req = self._get_POST_csrf_cookie_request()
  144. req.META['HTTP_X_CSRFTOKEN'] = self._csrf_id
  145. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  146. self.assertIsNone(req2)
  147. @override_settings(CSRF_HEADER_NAME='HTTP_X_CSRFTOKEN_CUSTOMIZED')
  148. def test_csrf_token_in_header_with_customized_name(self):
  149. """
  150. settings.CSRF_HEADER_NAME can be used to customize the CSRF header name
  151. """
  152. req = self._get_POST_csrf_cookie_request()
  153. req.META['HTTP_X_CSRFTOKEN_CUSTOMIZED'] = self._csrf_id
  154. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  155. self.assertIsNone(req2)
  156. def test_put_and_delete_rejected(self):
  157. """
  158. HTTP PUT and DELETE methods have protection
  159. """
  160. req = TestingHttpRequest()
  161. req.method = 'PUT'
  162. with patch_logger('django.security.csrf', 'warning') as logger_calls:
  163. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  164. self.assertEqual(403, req2.status_code)
  165. self.assertEqual(logger_calls[0], 'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)
  166. req = TestingHttpRequest()
  167. req.method = 'DELETE'
  168. with patch_logger('django.security.csrf', 'warning') as logger_calls:
  169. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  170. self.assertEqual(403, req2.status_code)
  171. self.assertEqual(logger_calls[0], 'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)
  172. def test_put_and_delete_allowed(self):
  173. """
  174. HTTP PUT and DELETE can get through with X-CSRFToken and a cookie.
  175. """
  176. req = self._get_GET_csrf_cookie_request()
  177. req.method = 'PUT'
  178. req.META['HTTP_X_CSRFTOKEN'] = self._csrf_id
  179. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  180. self.assertIsNone(req2)
  181. req = self._get_GET_csrf_cookie_request()
  182. req.method = 'DELETE'
  183. req.META['HTTP_X_CSRFTOKEN'] = self._csrf_id
  184. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  185. self.assertIsNone(req2)
  186. # Tests for the template tag method
  187. def test_token_node_no_csrf_cookie(self):
  188. """
  189. CsrfTokenNode works when no CSRF cookie is set.
  190. """
  191. req = self._get_GET_no_csrf_cookie_request()
  192. resp = token_view(req)
  193. token = get_token(req)
  194. self.assertIsNotNone(token)
  195. self._check_token_present(resp, token)
  196. def test_token_node_empty_csrf_cookie(self):
  197. """
  198. A new token is sent if the csrf_cookie is the empty string.
  199. """
  200. req = self._get_GET_no_csrf_cookie_request()
  201. req.COOKIES[settings.CSRF_COOKIE_NAME] = b""
  202. CsrfViewMiddleware().process_view(req, token_view, (), {})
  203. resp = token_view(req)
  204. token = get_token(req)
  205. self.assertIsNotNone(token)
  206. self._check_token_present(resp, token)
  207. def test_token_node_with_csrf_cookie(self):
  208. """
  209. CsrfTokenNode works when a CSRF cookie is set.
  210. """
  211. req = self._get_GET_csrf_cookie_request()
  212. CsrfViewMiddleware().process_view(req, token_view, (), {})
  213. resp = token_view(req)
  214. self._check_token_present(resp)
  215. def test_get_token_for_exempt_view(self):
  216. """
  217. get_token still works for a view decorated with 'csrf_exempt'.
  218. """
  219. req = self._get_GET_csrf_cookie_request()
  220. CsrfViewMiddleware().process_view(req, csrf_exempt(token_view), (), {})
  221. resp = token_view(req)
  222. self._check_token_present(resp)
  223. def test_get_token_for_requires_csrf_token_view(self):
  224. """
  225. get_token() works for a view decorated solely with requires_csrf_token.
  226. """
  227. req = self._get_GET_csrf_cookie_request()
  228. resp = requires_csrf_token(token_view)(req)
  229. self._check_token_present(resp)
  230. def test_token_node_with_new_csrf_cookie(self):
  231. """
  232. CsrfTokenNode works when a CSRF cookie is created by
  233. the middleware (when one was not already present)
  234. """
  235. req = self._get_GET_no_csrf_cookie_request()
  236. CsrfViewMiddleware().process_view(req, token_view, (), {})
  237. resp = token_view(req)
  238. resp2 = CsrfViewMiddleware().process_response(req, resp)
  239. csrf_cookie = resp2.cookies[settings.CSRF_COOKIE_NAME]
  240. self._check_token_present(resp, csrf_id=csrf_cookie.value)
  241. def test_cookie_not_reset_on_accepted_request(self):
  242. """
  243. The csrf token used in posts is changed on every request (although
  244. stays equivalent). The csrf cookie should not change on accepted
  245. requests. If it appears in the response, it should keep its value.
  246. """
  247. req = self._get_POST_request_with_token()
  248. CsrfViewMiddleware().process_view(req, token_view, (), {})
  249. resp = token_view(req)
  250. resp = CsrfViewMiddleware().process_response(req, resp)
  251. csrf_cookie = resp.cookies.get(settings.CSRF_COOKIE_NAME, None)
  252. if csrf_cookie:
  253. self.assertEqual(
  254. csrf_cookie.value, self._csrf_id_cookie,
  255. "CSRF cookie was changed on an accepted request"
  256. )
  257. @override_settings(DEBUG=True, ALLOWED_HOSTS=['www.example.com'])
  258. def test_https_bad_referer(self):
  259. """
  260. A POST HTTPS request with a bad referer is rejected
  261. """
  262. req = self._get_POST_request_with_token()
  263. req._is_secure_override = True
  264. req.META['HTTP_HOST'] = 'www.example.com'
  265. req.META['HTTP_REFERER'] = 'https://www.evil.org/somepage'
  266. req.META['SERVER_PORT'] = '443'
  267. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  268. self.assertContains(
  269. response,
  270. 'Referer checking failed - https://www.evil.org/somepage does not '
  271. 'match any trusted origins.',
  272. status_code=403,
  273. )
  274. @override_settings(DEBUG=True)
  275. def test_https_malformed_referer(self):
  276. """
  277. A POST HTTPS request with a bad referer is rejected.
  278. """
  279. malformed_referer_msg = 'Referer checking failed - Referer is malformed.'
  280. req = self._get_POST_request_with_token()
  281. req._is_secure_override = True
  282. req.META['HTTP_REFERER'] = 'http://http://www.example.com/'
  283. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  284. self.assertContains(
  285. response,
  286. 'Referer checking failed - Referer is insecure while host is secure.',
  287. status_code=403,
  288. )
  289. # Empty
  290. req.META['HTTP_REFERER'] = ''
  291. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  292. self.assertContains(response, malformed_referer_msg, status_code=403)
  293. # Non-ASCII
  294. req.META['HTTP_REFERER'] = b'\xd8B\xf6I\xdf'
  295. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  296. self.assertContains(response, malformed_referer_msg, status_code=403)
  297. # missing scheme
  298. # >>> urlparse('//example.com/')
  299. # ParseResult(scheme='', netloc='example.com', path='/', params='', query='', fragment='')
  300. req.META['HTTP_REFERER'] = '//example.com/'
  301. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  302. self.assertContains(response, malformed_referer_msg, status_code=403)
  303. # missing netloc
  304. # >>> urlparse('https://')
  305. # ParseResult(scheme='https', netloc='', path='', params='', query='', fragment='')
  306. req.META['HTTP_REFERER'] = 'https://'
  307. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  308. self.assertContains(response, malformed_referer_msg, status_code=403)
  309. @override_settings(ALLOWED_HOSTS=['www.example.com'])
  310. def test_https_good_referer(self):
  311. """
  312. A POST HTTPS request with a good referer is accepted.
  313. """
  314. req = self._get_POST_request_with_token()
  315. req._is_secure_override = True
  316. req.META['HTTP_HOST'] = 'www.example.com'
  317. req.META['HTTP_REFERER'] = 'https://www.example.com/somepage'
  318. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  319. self.assertIsNone(req2)
  320. @override_settings(ALLOWED_HOSTS=['www.example.com'])
  321. def test_https_good_referer_2(self):
  322. """
  323. A POST HTTPS request with a good referer is accepted where the referer
  324. contains no trailing slash.
  325. """
  326. # See ticket #15617
  327. req = self._get_POST_request_with_token()
  328. req._is_secure_override = True
  329. req.META['HTTP_HOST'] = 'www.example.com'
  330. req.META['HTTP_REFERER'] = 'https://www.example.com'
  331. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  332. self.assertIsNone(req2)
  333. def _test_https_good_referer_behind_proxy(self):
  334. req = self._get_POST_request_with_token()
  335. req._is_secure_override = True
  336. req.META.update({
  337. 'HTTP_HOST': '10.0.0.2',
  338. 'HTTP_REFERER': 'https://www.example.com/somepage',
  339. 'SERVER_PORT': '8080',
  340. 'HTTP_X_FORWARDED_HOST': 'www.example.com',
  341. 'HTTP_X_FORWARDED_PORT': '443',
  342. })
  343. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  344. self.assertIsNone(req2)
  345. @override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_TRUSTED_ORIGINS=['dashboard.example.com'])
  346. def test_https_csrf_trusted_origin_allowed(self):
  347. """
  348. A POST HTTPS request with a referer added to the CSRF_TRUSTED_ORIGINS
  349. setting is accepted.
  350. """
  351. req = self._get_POST_request_with_token()
  352. req._is_secure_override = True
  353. req.META['HTTP_HOST'] = 'www.example.com'
  354. req.META['HTTP_REFERER'] = 'https://dashboard.example.com'
  355. req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  356. self.assertIsNone(req2)
  357. @override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_TRUSTED_ORIGINS=['.example.com'])
  358. def test_https_csrf_wildcard_trusted_origin_allowed(self):
  359. """
  360. A POST HTTPS request with a referer that matches a CSRF_TRUSTED_ORIGINS
  361. wildcard is accepted.
  362. """
  363. req = self._get_POST_request_with_token()
  364. req._is_secure_override = True
  365. req.META['HTTP_HOST'] = 'www.example.com'
  366. req.META['HTTP_REFERER'] = 'https://dashboard.example.com'
  367. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  368. self.assertIsNone(response)
  369. def _test_https_good_referer_matches_cookie_domain(self):
  370. req = self._get_POST_request_with_token()
  371. req._is_secure_override = True
  372. req.META['HTTP_REFERER'] = 'https://foo.example.com/'
  373. req.META['SERVER_PORT'] = '443'
  374. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  375. self.assertIsNone(response)
  376. def _test_https_good_referer_matches_cookie_domain_with_different_port(self):
  377. req = self._get_POST_request_with_token()
  378. req._is_secure_override = True
  379. req.META['HTTP_HOST'] = 'www.example.com'
  380. req.META['HTTP_REFERER'] = 'https://foo.example.com:4443/'
  381. req.META['SERVER_PORT'] = '4443'
  382. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  383. self.assertIsNone(response)
  384. def test_ensures_csrf_cookie_no_logging(self):
  385. """
  386. ensure_csrf_cookie() doesn't log warnings (#19436).
  387. """
  388. @ensure_csrf_cookie
  389. def view(request):
  390. # Doesn't insert a token or anything
  391. return HttpResponse(content="")
  392. class TestHandler(logging.Handler):
  393. def emit(self, record):
  394. raise Exception("This shouldn't have happened!")
  395. logger = logging.getLogger('django.request')
  396. test_handler = TestHandler()
  397. old_log_level = logger.level
  398. try:
  399. logger.addHandler(test_handler)
  400. logger.setLevel(logging.WARNING)
  401. req = self._get_GET_no_csrf_cookie_request()
  402. view(req)
  403. finally:
  404. logger.removeHandler(test_handler)
  405. logger.setLevel(old_log_level)
  406. def test_post_data_read_failure(self):
  407. """
  408. #20128 -- IOErrors during POST data reading should be caught and
  409. treated as if the POST data wasn't there.
  410. """
  411. class CsrfPostRequest(HttpRequest):
  412. """
  413. HttpRequest that can raise an IOError when accessing POST data
  414. """
  415. def __init__(self, token, raise_error):
  416. super(CsrfPostRequest, self).__init__()
  417. self.method = 'POST'
  418. self.raise_error = False
  419. self.COOKIES[settings.CSRF_COOKIE_NAME] = token
  420. # Handle both cases here to prevent duplicate code in the
  421. # session tests.
  422. self.session = {}
  423. self.session[CSRF_SESSION_KEY] = token
  424. self.POST['csrfmiddlewaretoken'] = token
  425. self.raise_error = raise_error
  426. def _load_post_and_files(self):
  427. raise IOError('error reading input data')
  428. def _get_post(self):
  429. if self.raise_error:
  430. self._load_post_and_files()
  431. return self._post
  432. def _set_post(self, post):
  433. self._post = post
  434. POST = property(_get_post, _set_post)
  435. token = ('ABC' + self._csrf_id)[:CSRF_TOKEN_LENGTH]
  436. req = CsrfPostRequest(token, raise_error=False)
  437. resp = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  438. self.assertIsNone(resp)
  439. req = CsrfPostRequest(token, raise_error=True)
  440. with patch_logger('django.security.csrf', 'warning') as logger_calls:
  441. resp = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  442. self.assertEqual(resp.status_code, 403)
  443. self.assertEqual(logger_calls[0], 'Forbidden (%s): ' % REASON_BAD_TOKEN)
  444. class CsrfViewMiddlewareTests(CsrfViewMiddlewareTestMixin, SimpleTestCase):
  445. def _get_GET_csrf_cookie_request(self):
  446. req = TestingHttpRequest()
  447. req.COOKIES[settings.CSRF_COOKIE_NAME] = self._csrf_id_cookie
  448. return req
  449. def _get_POST_bare_secret_csrf_cookie_request(self):
  450. req = self._get_POST_no_csrf_cookie_request()
  451. req.COOKIES[settings.CSRF_COOKIE_NAME] = self._csrf_id_cookie[:32]
  452. return req
  453. def _get_POST_bare_secret_csrf_cookie_request_with_token(self):
  454. req = self._get_POST_bare_secret_csrf_cookie_request()
  455. req.POST['csrfmiddlewaretoken'] = self._csrf_id_cookie[:32]
  456. return req
  457. def test_ensures_csrf_cookie_no_middleware(self):
  458. """
  459. The ensure_csrf_cookie() decorator works without middleware.
  460. """
  461. @ensure_csrf_cookie
  462. def view(request):
  463. # Doesn't insert a token or anything
  464. return HttpResponse(content="")
  465. req = self._get_GET_no_csrf_cookie_request()
  466. resp = view(req)
  467. self.assertTrue(resp.cookies.get(settings.CSRF_COOKIE_NAME, False))
  468. self.assertIn('Cookie', resp.get('Vary', ''))
  469. def test_ensures_csrf_cookie_with_middleware(self):
  470. """
  471. The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware
  472. enabled.
  473. """
  474. @ensure_csrf_cookie
  475. def view(request):
  476. # Doesn't insert a token or anything
  477. return HttpResponse(content="")
  478. req = self._get_GET_no_csrf_cookie_request()
  479. CsrfViewMiddleware().process_view(req, view, (), {})
  480. resp = view(req)
  481. resp2 = CsrfViewMiddleware().process_response(req, resp)
  482. self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False))
  483. self.assertIn('Cookie', resp2.get('Vary', ''))
  484. def test_csrf_cookie_age(self):
  485. """
  486. CSRF cookie age can be set using settings.CSRF_COOKIE_AGE.
  487. """
  488. req = self._get_GET_no_csrf_cookie_request()
  489. MAX_AGE = 123
  490. with self.settings(CSRF_COOKIE_NAME='csrfcookie',
  491. CSRF_COOKIE_DOMAIN='.example.com',
  492. CSRF_COOKIE_AGE=MAX_AGE,
  493. CSRF_COOKIE_PATH='/test/',
  494. CSRF_COOKIE_SECURE=True,
  495. CSRF_COOKIE_HTTPONLY=True):
  496. # token_view calls get_token() indirectly
  497. CsrfViewMiddleware().process_view(req, token_view, (), {})
  498. resp = token_view(req)
  499. resp2 = CsrfViewMiddleware().process_response(req, resp)
  500. max_age = resp2.cookies.get('csrfcookie').get('max-age')
  501. self.assertEqual(max_age, MAX_AGE)
  502. def test_csrf_cookie_age_none(self):
  503. """
  504. CSRF cookie age does not have max age set and therefore uses
  505. session-based cookies.
  506. """
  507. req = self._get_GET_no_csrf_cookie_request()
  508. MAX_AGE = None
  509. with self.settings(CSRF_COOKIE_NAME='csrfcookie',
  510. CSRF_COOKIE_DOMAIN='.example.com',
  511. CSRF_COOKIE_AGE=MAX_AGE,
  512. CSRF_COOKIE_PATH='/test/',
  513. CSRF_COOKIE_SECURE=True,
  514. CSRF_COOKIE_HTTPONLY=True):
  515. # token_view calls get_token() indirectly
  516. CsrfViewMiddleware().process_view(req, token_view, (), {})
  517. resp = token_view(req)
  518. resp2 = CsrfViewMiddleware().process_response(req, resp)
  519. max_age = resp2.cookies.get('csrfcookie').get('max-age')
  520. self.assertEqual(max_age, '')
  521. def test_process_view_token_too_long(self):
  522. """
  523. If the token is longer than expected, it is ignored and a new token is
  524. created.
  525. """
  526. req = self._get_GET_no_csrf_cookie_request()
  527. req.COOKIES[settings.CSRF_COOKIE_NAME] = 'x' * 100000
  528. CsrfViewMiddleware().process_view(req, token_view, (), {})
  529. resp = token_view(req)
  530. resp2 = CsrfViewMiddleware().process_response(req, resp)
  531. csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)
  532. self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH)
  533. def test_process_view_token_invalid_bytes(self):
  534. """
  535. If the token contains improperly encoded unicode, it is ignored and a
  536. new token is created.
  537. """
  538. token = (b"<1>\xc2\xa1" + force_bytes(self._csrf_id, 'ascii'))[:CSRF_TOKEN_LENGTH]
  539. req = self._get_GET_no_csrf_cookie_request()
  540. req.COOKIES[settings.CSRF_COOKIE_NAME] = token
  541. # We expect a UnicodeWarning here, because we used broken utf-8 on purpose
  542. with warnings.catch_warnings():
  543. warnings.filterwarnings("ignore", category=UnicodeWarning)
  544. CsrfViewMiddleware().process_view(req, token_view, (), {})
  545. resp = token_view(req)
  546. resp2 = CsrfViewMiddleware().process_response(req, resp)
  547. csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)
  548. self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH)
  549. self.assertNotEqual(csrf_cookie.value, token)
  550. def test_process_view_token_invalid_chars(self):
  551. """
  552. If the token contains non-alphanumeric characters, it is ignored and a
  553. new token is created.
  554. """
  555. token = ('!@#' + self._csrf_id)[:CSRF_TOKEN_LENGTH]
  556. req = self._get_GET_no_csrf_cookie_request()
  557. req.COOKIES[settings.CSRF_COOKIE_NAME] = token
  558. CsrfViewMiddleware().process_view(req, token_view, (), {})
  559. resp = token_view(req)
  560. resp2 = CsrfViewMiddleware().process_response(req, resp)
  561. csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)
  562. self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH)
  563. self.assertNotEqual(csrf_cookie.value, token)
  564. def test_bare_secret_accepted_and_replaced(self):
  565. """
  566. The csrf token is reset from a bare secret.
  567. """
  568. req = self._get_POST_bare_secret_csrf_cookie_request_with_token()
  569. req2 = CsrfViewMiddleware().process_view(req, token_view, (), {})
  570. self.assertIsNone(req2)
  571. resp = token_view(req)
  572. resp = CsrfViewMiddleware().process_response(req, resp)
  573. self.assertIn(settings.CSRF_COOKIE_NAME, resp.cookies, "Cookie was not reset from bare secret")
  574. csrf_cookie = resp.cookies[settings.CSRF_COOKIE_NAME]
  575. self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH)
  576. self._check_token_present(resp, csrf_id=csrf_cookie.value)
  577. @override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_COOKIE_DOMAIN='.example.com', USE_X_FORWARDED_PORT=True)
  578. def test_https_good_referer_behind_proxy(self):
  579. """
  580. A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True.
  581. """
  582. self._test_https_good_referer_behind_proxy()
  583. @override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_COOKIE_DOMAIN='.example.com')
  584. def test_https_good_referer_matches_cookie_domain(self):
  585. """
  586. A POST HTTPS request with a good referer should be accepted from a
  587. subdomain that's allowed by CSRF_COOKIE_DOMAIN.
  588. """
  589. self._test_https_good_referer_matches_cookie_domain()
  590. @override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_COOKIE_DOMAIN='.example.com')
  591. def test_https_good_referer_matches_cookie_domain_with_different_port(self):
  592. """
  593. A POST HTTPS request with a good referer should be accepted from a
  594. subdomain that's allowed by CSRF_COOKIE_DOMAIN and a non-443 port.
  595. """
  596. self._test_https_good_referer_matches_cookie_domain_with_different_port()
  597. @override_settings(CSRF_COOKIE_DOMAIN='.example.com', DEBUG=True)
  598. def test_https_reject_insecure_referer(self):
  599. """
  600. A POST HTTPS request from an insecure referer should be rejected.
  601. """
  602. req = self._get_POST_request_with_token()
  603. req._is_secure_override = True
  604. req.META['HTTP_REFERER'] = 'http://example.com/'
  605. req.META['SERVER_PORT'] = '443'
  606. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  607. self.assertContains(
  608. response,
  609. 'Referer checking failed - Referer is insecure while host is secure.',
  610. status_code=403,
  611. )
  612. @override_settings(CSRF_USE_SESSIONS=True, CSRF_COOKIE_DOMAIN=None)
  613. class CsrfViewMiddlewareUseSessionsTests(CsrfViewMiddlewareTestMixin, SimpleTestCase):
  614. """
  615. CSRF tests with CSRF_USE_SESSIONS=True.
  616. """
  617. def _get_POST_bare_secret_csrf_cookie_request(self):
  618. req = self._get_POST_no_csrf_cookie_request()
  619. req.session[CSRF_SESSION_KEY] = self._csrf_id_cookie[:32]
  620. return req
  621. def _get_GET_csrf_cookie_request(self):
  622. req = TestingHttpRequest()
  623. req.session[CSRF_SESSION_KEY] = self._csrf_id_cookie
  624. return req
  625. def test_no_session_on_request(self):
  626. msg = (
  627. 'CSRF_USE_SESSIONS is enabled, but request.session is not set. '
  628. 'SessionMiddleware must appear before CsrfViewMiddleware in MIDDLEWARE.'
  629. )
  630. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  631. CsrfViewMiddleware().process_view(HttpRequest(), None, (), {})
  632. def test_process_response_get_token_used(self):
  633. """The ensure_csrf_cookie() decorator works without middleware."""
  634. @ensure_csrf_cookie
  635. def view(request):
  636. # Doesn't insert a token or anything
  637. return HttpResponse(content="")
  638. req = self._get_GET_no_csrf_cookie_request()
  639. view(req)
  640. self.assertTrue(req.session.get(CSRF_SESSION_KEY, False))
  641. def test_ensures_csrf_cookie_with_middleware(self):
  642. """
  643. The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware
  644. enabled.
  645. """
  646. @ensure_csrf_cookie
  647. def view(request):
  648. # Doesn't insert a token or anything
  649. return HttpResponse(content="")
  650. req = self._get_GET_no_csrf_cookie_request()
  651. CsrfViewMiddleware().process_view(req, view, (), {})
  652. resp = view(req)
  653. CsrfViewMiddleware().process_response(req, resp)
  654. self.assertTrue(req.session.get(CSRF_SESSION_KEY, False))
  655. def test_token_node_with_new_csrf_cookie(self):
  656. """
  657. CsrfTokenNode works when a CSRF cookie is created by the middleware
  658. (when one was not already present).
  659. """
  660. req = self._get_GET_no_csrf_cookie_request()
  661. CsrfViewMiddleware().process_view(req, token_view, (), {})
  662. resp = token_view(req)
  663. CsrfViewMiddleware().process_response(req, resp)
  664. csrf_cookie = req.session[CSRF_SESSION_KEY]
  665. self._check_token_present(resp, csrf_id=csrf_cookie)
  666. @override_settings(
  667. ALLOWED_HOSTS=['www.example.com'],
  668. SESSION_COOKIE_DOMAIN='.example.com',
  669. USE_X_FORWARDED_PORT=True,
  670. DEBUG=True,
  671. )
  672. def test_https_good_referer_behind_proxy(self):
  673. """
  674. A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True.
  675. """
  676. self._test_https_good_referer_behind_proxy()
  677. @override_settings(ALLOWED_HOSTS=['www.example.com'], SESSION_COOKIE_DOMAIN='.example.com')
  678. def test_https_good_referer_matches_cookie_domain(self):
  679. """
  680. A POST HTTPS request with a good referer should be accepted from a
  681. subdomain that's allowed by SESSION_COOKIE_DOMAIN.
  682. """
  683. self._test_https_good_referer_matches_cookie_domain()
  684. @override_settings(ALLOWED_HOSTS=['www.example.com'], SESSION_COOKIE_DOMAIN='.example.com')
  685. def test_https_good_referer_matches_cookie_domain_with_different_port(self):
  686. """
  687. A POST HTTPS request with a good referer should be accepted from a
  688. subdomain that's allowed by SESSION_COOKIE_DOMAIN and a non-443 port.
  689. """
  690. self._test_https_good_referer_matches_cookie_domain_with_different_port()
  691. @override_settings(SESSION_COOKIE_DOMAIN='.example.com', DEBUG=True)
  692. def test_https_reject_insecure_referer(self):
  693. """
  694. A POST HTTPS request from an insecure referer should be rejected.
  695. """
  696. req = self._get_POST_request_with_token()
  697. req._is_secure_override = True
  698. req.META['HTTP_REFERER'] = 'http://example.com/'
  699. req.META['SERVER_PORT'] = '443'
  700. response = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
  701. self.assertContains(
  702. response,
  703. 'Referer checking failed - Referer is insecure while host is secure.',
  704. status_code=403,
  705. )