test_debug.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. # -*- coding: utf-8 -*-
  2. # This coding header is significant for tests, as the debug view is parsing
  3. # files to search for such a header to decode the source file content
  4. from __future__ import unicode_literals
  5. import importlib
  6. import inspect
  7. import os
  8. import re
  9. import shutil
  10. import sys
  11. from tempfile import NamedTemporaryFile, mkdtemp, mkstemp
  12. from unittest import skipIf
  13. from django.core import mail
  14. from django.core.files.uploadedfile import SimpleUploadedFile
  15. from django.core.urlresolvers import reverse
  16. from django.template.base import TemplateDoesNotExist
  17. from django.test import TestCase, RequestFactory, override_settings
  18. from django.utils.encoding import force_text, force_bytes
  19. from django.utils import six
  20. from django.views.debug import CallableSettingWrapper, ExceptionReporter
  21. from .. import BrokenException, except_args
  22. from ..views import (sensitive_view, non_sensitive_view, paranoid_view,
  23. custom_exception_reporter_filter_view, sensitive_method_view,
  24. sensitive_args_function_caller, sensitive_kwargs_function_caller,
  25. multivalue_dict_key_error)
  26. class CallableSettingWrapperTests(TestCase):
  27. """ Unittests for CallableSettingWrapper
  28. """
  29. def test_repr(self):
  30. class WrappedCallable(object):
  31. def __repr__(self):
  32. return "repr from the wrapped callable"
  33. def __call__(self):
  34. pass
  35. actual = repr(CallableSettingWrapper(WrappedCallable()))
  36. self.assertEqual(actual, "repr from the wrapped callable")
  37. @override_settings(DEBUG=True, TEMPLATE_DEBUG=True,
  38. ROOT_URLCONF="view_tests.urls")
  39. class DebugViewTests(TestCase):
  40. def test_files(self):
  41. response = self.client.get('/raises/')
  42. self.assertEqual(response.status_code, 500)
  43. data = {
  44. 'file_data.txt': SimpleUploadedFile('file_data.txt', b'haha'),
  45. }
  46. response = self.client.post('/raises/', data)
  47. self.assertContains(response, 'file_data.txt', status_code=500)
  48. self.assertNotContains(response, 'haha', status_code=500)
  49. def test_400(self):
  50. # Ensure that when DEBUG=True, technical_500_template() is called.
  51. response = self.client.get('/raises400/')
  52. self.assertContains(response, '<div class="context" id="', status_code=400)
  53. # Ensure no 403.html template exists to test the default case.
  54. @override_settings(TEMPLATES=[{
  55. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  56. }])
  57. def test_403(self):
  58. response = self.client.get('/raises403/')
  59. self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403)
  60. # Set up a test 403.html template.
  61. @override_settings(TEMPLATES=[{
  62. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  63. 'OPTIONS': {
  64. 'loaders': [
  65. ('django.template.loaders.locmem.Loader', {
  66. '403.html': 'This is a test template for a 403 error.',
  67. }),
  68. ],
  69. },
  70. }])
  71. def test_403_template(self):
  72. response = self.client.get('/raises403/')
  73. self.assertContains(response, 'test template', status_code=403)
  74. def test_404(self):
  75. response = self.client.get('/raises404/')
  76. self.assertEqual(response.status_code, 404)
  77. def test_raised_404(self):
  78. response = self.client.get('/views/raises404/')
  79. self.assertContains(response, "<code>not-in-urls</code>, didn't match", status_code=404)
  80. def test_404_not_in_urls(self):
  81. response = self.client.get('/not-in-urls')
  82. self.assertNotContains(response, "Raised by:", status_code=404)
  83. self.assertContains(response, "<code>not-in-urls</code>, didn't match", status_code=404)
  84. def test_technical_404(self):
  85. response = self.client.get('/views/technical404/')
  86. self.assertContains(response, "Raised by:", status_code=404)
  87. self.assertContains(response, "view_tests.views.technical404", status_code=404)
  88. def test_classbased_technical_404(self):
  89. response = self.client.get('/views/classbased404/')
  90. self.assertContains(response, "Raised by:", status_code=404)
  91. self.assertContains(response, "view_tests.views.Http404View", status_code=404)
  92. def test_view_exceptions(self):
  93. for n in range(len(except_args)):
  94. self.assertRaises(BrokenException, self.client.get,
  95. reverse('view_exception', args=(n,)))
  96. def test_non_l10ned_numeric_ids(self):
  97. """
  98. Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized.
  99. """
  100. with self.settings(DEBUG=True, USE_L10N=True):
  101. response = self.client.get('/raises500/')
  102. # We look for a HTML fragment of the form
  103. # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"'
  104. self.assertContains(response, '<div class="context" id="', status_code=500)
  105. match = re.search(b'<div class="context" id="(?P<id>[^"]+)">', response.content)
  106. self.assertIsNotNone(match)
  107. id_repr = match.group('id')
  108. self.assertFalse(re.search(b'[^c0-9]', id_repr),
  109. "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr)
  110. def test_template_exceptions(self):
  111. for n in range(len(except_args)):
  112. try:
  113. self.client.get(reverse('template_exception', args=(n,)))
  114. except Exception:
  115. raising_loc = inspect.trace()[-1][-2][0].strip()
  116. self.assertNotEqual(raising_loc.find('raise BrokenException'), -1,
  117. "Failed to find 'raise BrokenException' in last frame of traceback, instead found: %s" %
  118. raising_loc)
  119. def test_template_loader_postmortem(self):
  120. """Tests for not existing file"""
  121. template_name = "notfound.html"
  122. with NamedTemporaryFile(prefix=template_name) as tempfile:
  123. tempdir = os.path.dirname(tempfile.name)
  124. template_path = os.path.join(tempdir, template_name)
  125. with override_settings(TEMPLATE_DIRS=(tempdir,)):
  126. response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name}))
  127. self.assertContains(response, "%s (File does not exist)" % template_path, status_code=500, count=1)
  128. @skipIf(sys.platform == "win32", "Python on Windows doesn't have working os.chmod() and os.access().")
  129. def test_template_loader_postmortem_notreadable(self):
  130. """Tests for not readable file"""
  131. with NamedTemporaryFile() as tempfile:
  132. template_name = tempfile.name
  133. tempdir = os.path.dirname(tempfile.name)
  134. template_path = os.path.join(tempdir, template_name)
  135. os.chmod(template_path, 0o0222)
  136. with override_settings(TEMPLATE_DIRS=(tempdir,)):
  137. response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name}))
  138. self.assertContains(response, "%s (File is not readable)" % template_path, status_code=500, count=1)
  139. def test_template_loader_postmortem_notafile(self):
  140. """Tests for not being a file"""
  141. try:
  142. template_path = mkdtemp()
  143. template_name = os.path.basename(template_path)
  144. tempdir = os.path.dirname(template_path)
  145. with override_settings(TEMPLATE_DIRS=(tempdir,)):
  146. response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name}))
  147. self.assertContains(response, "%s (Not a file)" % template_path, status_code=500, count=1)
  148. finally:
  149. shutil.rmtree(template_path)
  150. def test_no_template_source_loaders(self):
  151. """
  152. Make sure if you don't specify a template, the debug view doesn't blow up.
  153. """
  154. self.assertRaises(TemplateDoesNotExist, self.client.get, '/render_no_template/')
  155. @override_settings(ROOT_URLCONF='view_tests.default_urls')
  156. def test_default_urlconf_template(self):
  157. """
  158. Make sure that the default urlconf template is shown shown instead
  159. of the technical 404 page, if the user has not altered their
  160. url conf yet.
  161. """
  162. response = self.client.get('/')
  163. self.assertContains(
  164. response,
  165. "<h2>Congratulations on your first Django-powered page.</h2>"
  166. )
  167. @override_settings(ROOT_URLCONF='view_tests.regression_21530_urls')
  168. def test_regression_21530(self):
  169. """
  170. Regression test for bug #21530.
  171. If the admin app include is replaced with exactly one url
  172. pattern, then the technical 404 template should be displayed.
  173. The bug here was that an AttributeError caused a 500 response.
  174. """
  175. response = self.client.get('/')
  176. self.assertContains(
  177. response,
  178. "Page not found <span>(404)</span>",
  179. status_code=404
  180. )
  181. class ExceptionReporterTests(TestCase):
  182. rf = RequestFactory()
  183. def test_request_and_exception(self):
  184. "A simple exception report can be generated"
  185. try:
  186. request = self.rf.get('/test_view/')
  187. raise ValueError("Can't find my keys")
  188. except ValueError:
  189. exc_type, exc_value, tb = sys.exc_info()
  190. reporter = ExceptionReporter(request, exc_type, exc_value, tb)
  191. html = reporter.get_traceback_html()
  192. self.assertIn('<h1>ValueError at /test_view/</h1>', html)
  193. self.assertIn('<pre class="exception_value">Can&#39;t find my keys</pre>', html)
  194. self.assertIn('<th>Request Method:</th>', html)
  195. self.assertIn('<th>Request URL:</th>', html)
  196. self.assertIn('<th>Exception Type:</th>', html)
  197. self.assertIn('<th>Exception Value:</th>', html)
  198. self.assertIn('<h2>Traceback ', html)
  199. self.assertIn('<h2>Request information</h2>', html)
  200. self.assertNotIn('<p>Request data not supplied</p>', html)
  201. def test_no_request(self):
  202. "An exception report can be generated without request"
  203. try:
  204. raise ValueError("Can't find my keys")
  205. except ValueError:
  206. exc_type, exc_value, tb = sys.exc_info()
  207. reporter = ExceptionReporter(None, exc_type, exc_value, tb)
  208. html = reporter.get_traceback_html()
  209. self.assertIn('<h1>ValueError</h1>', html)
  210. self.assertIn('<pre class="exception_value">Can&#39;t find my keys</pre>', html)
  211. self.assertNotIn('<th>Request Method:</th>', html)
  212. self.assertNotIn('<th>Request URL:</th>', html)
  213. self.assertIn('<th>Exception Type:</th>', html)
  214. self.assertIn('<th>Exception Value:</th>', html)
  215. self.assertIn('<h2>Traceback ', html)
  216. self.assertIn('<h2>Request information</h2>', html)
  217. self.assertIn('<p>Request data not supplied</p>', html)
  218. def test_eol_support(self):
  219. """Test that the ExceptionReporter supports Unix, Windows and Macintosh EOL markers"""
  220. LINES = list('print %d' % i for i in range(1, 6))
  221. reporter = ExceptionReporter(None, None, None, None)
  222. for newline in ['\n', '\r\n', '\r']:
  223. fd, filename = mkstemp(text=False)
  224. os.write(fd, force_bytes(newline.join(LINES) + newline))
  225. os.close(fd)
  226. try:
  227. self.assertEqual(
  228. reporter._get_lines_from_file(filename, 3, 2),
  229. (1, LINES[1:3], LINES[3], LINES[4:])
  230. )
  231. finally:
  232. os.unlink(filename)
  233. def test_no_exception(self):
  234. "An exception report can be generated for just a request"
  235. request = self.rf.get('/test_view/')
  236. reporter = ExceptionReporter(request, None, None, None)
  237. html = reporter.get_traceback_html()
  238. self.assertIn('<h1>Report at /test_view/</h1>', html)
  239. self.assertIn('<pre class="exception_value">No exception message supplied</pre>', html)
  240. self.assertIn('<th>Request Method:</th>', html)
  241. self.assertIn('<th>Request URL:</th>', html)
  242. self.assertNotIn('<th>Exception Type:</th>', html)
  243. self.assertNotIn('<th>Exception Value:</th>', html)
  244. self.assertNotIn('<h2>Traceback ', html)
  245. self.assertIn('<h2>Request information</h2>', html)
  246. self.assertNotIn('<p>Request data not supplied</p>', html)
  247. def test_request_and_message(self):
  248. "A message can be provided in addition to a request"
  249. request = self.rf.get('/test_view/')
  250. reporter = ExceptionReporter(request, None, "I'm a little teapot", None)
  251. html = reporter.get_traceback_html()
  252. self.assertIn('<h1>Report at /test_view/</h1>', html)
  253. self.assertIn('<pre class="exception_value">I&#39;m a little teapot</pre>', html)
  254. self.assertIn('<th>Request Method:</th>', html)
  255. self.assertIn('<th>Request URL:</th>', html)
  256. self.assertNotIn('<th>Exception Type:</th>', html)
  257. self.assertNotIn('<th>Exception Value:</th>', html)
  258. self.assertNotIn('<h2>Traceback ', html)
  259. self.assertIn('<h2>Request information</h2>', html)
  260. self.assertNotIn('<p>Request data not supplied</p>', html)
  261. def test_message_only(self):
  262. reporter = ExceptionReporter(None, None, "I'm a little teapot", None)
  263. html = reporter.get_traceback_html()
  264. self.assertIn('<h1>Report</h1>', html)
  265. self.assertIn('<pre class="exception_value">I&#39;m a little teapot</pre>', html)
  266. self.assertNotIn('<th>Request Method:</th>', html)
  267. self.assertNotIn('<th>Request URL:</th>', html)
  268. self.assertNotIn('<th>Exception Type:</th>', html)
  269. self.assertNotIn('<th>Exception Value:</th>', html)
  270. self.assertNotIn('<h2>Traceback ', html)
  271. self.assertIn('<h2>Request information</h2>', html)
  272. self.assertIn('<p>Request data not supplied</p>', html)
  273. def test_non_utf8_values_handling(self):
  274. "Non-UTF-8 exceptions/values should not make the output generation choke."
  275. try:
  276. class NonUtf8Output(Exception):
  277. def __repr__(self):
  278. return b'EXC\xe9EXC'
  279. somevar = b'VAL\xe9VAL' # NOQA
  280. raise NonUtf8Output()
  281. except Exception:
  282. exc_type, exc_value, tb = sys.exc_info()
  283. reporter = ExceptionReporter(None, exc_type, exc_value, tb)
  284. html = reporter.get_traceback_html()
  285. self.assertIn('VAL\\xe9VAL', html)
  286. self.assertIn('EXC\\xe9EXC', html)
  287. def test_unprintable_values_handling(self):
  288. "Unprintable values should not make the output generation choke."
  289. try:
  290. class OomOutput(object):
  291. def __repr__(self):
  292. raise MemoryError('OOM')
  293. oomvalue = OomOutput() # NOQA
  294. raise ValueError()
  295. except Exception:
  296. exc_type, exc_value, tb = sys.exc_info()
  297. reporter = ExceptionReporter(None, exc_type, exc_value, tb)
  298. html = reporter.get_traceback_html()
  299. self.assertIn('<td class="code"><pre>Error in formatting', html)
  300. def test_too_large_values_handling(self):
  301. "Large values should not create a large HTML."
  302. large = 256 * 1024
  303. repr_of_str_adds = len(repr(''))
  304. try:
  305. class LargeOutput(object):
  306. def __repr__(self):
  307. return repr('A' * large)
  308. largevalue = LargeOutput() # NOQA
  309. raise ValueError()
  310. except Exception:
  311. exc_type, exc_value, tb = sys.exc_info()
  312. reporter = ExceptionReporter(None, exc_type, exc_value, tb)
  313. html = reporter.get_traceback_html()
  314. self.assertEqual(len(html) // 1024 // 128, 0) # still fit in 128Kb
  315. self.assertIn('&lt;trimmed %d bytes string&gt;' % (large + repr_of_str_adds,), html)
  316. @skipIf(six.PY2, 'Bug manifests on PY3 only')
  317. def test_unfrozen_importlib(self):
  318. """
  319. importlib is not a frozen app, but its loader thinks it's frozen which
  320. results in an ImportError on Python 3. Refs #21443.
  321. """
  322. try:
  323. request = self.rf.get('/test_view/')
  324. importlib.import_module('abc.def.invalid.name')
  325. except Exception:
  326. exc_type, exc_value, tb = sys.exc_info()
  327. reporter = ExceptionReporter(request, exc_type, exc_value, tb)
  328. html = reporter.get_traceback_html()
  329. self.assertIn('<h1>ImportError at /test_view/</h1>', html)
  330. class PlainTextReportTests(TestCase):
  331. rf = RequestFactory()
  332. def test_request_and_exception(self):
  333. "A simple exception report can be generated"
  334. try:
  335. request = self.rf.get('/test_view/')
  336. raise ValueError("Can't find my keys")
  337. except ValueError:
  338. exc_type, exc_value, tb = sys.exc_info()
  339. reporter = ExceptionReporter(request, exc_type, exc_value, tb)
  340. text = reporter.get_traceback_text()
  341. self.assertIn('ValueError at /test_view/', text)
  342. self.assertIn("Can't find my keys", text)
  343. self.assertIn('Request Method:', text)
  344. self.assertIn('Request URL:', text)
  345. self.assertIn('Exception Type:', text)
  346. self.assertIn('Exception Value:', text)
  347. self.assertIn('Traceback:', text)
  348. self.assertIn('Request information:', text)
  349. self.assertNotIn('Request data not supplied', text)
  350. def test_no_request(self):
  351. "An exception report can be generated without request"
  352. try:
  353. raise ValueError("Can't find my keys")
  354. except ValueError:
  355. exc_type, exc_value, tb = sys.exc_info()
  356. reporter = ExceptionReporter(None, exc_type, exc_value, tb)
  357. text = reporter.get_traceback_text()
  358. self.assertIn('ValueError', text)
  359. self.assertIn("Can't find my keys", text)
  360. self.assertNotIn('Request Method:', text)
  361. self.assertNotIn('Request URL:', text)
  362. self.assertIn('Exception Type:', text)
  363. self.assertIn('Exception Value:', text)
  364. self.assertIn('Traceback:', text)
  365. self.assertIn('Request data not supplied', text)
  366. def test_no_exception(self):
  367. "An exception report can be generated for just a request"
  368. request = self.rf.get('/test_view/')
  369. reporter = ExceptionReporter(request, None, None, None)
  370. reporter.get_traceback_text()
  371. def test_request_and_message(self):
  372. "A message can be provided in addition to a request"
  373. request = self.rf.get('/test_view/')
  374. reporter = ExceptionReporter(request, None, "I'm a little teapot", None)
  375. reporter.get_traceback_text()
  376. def test_message_only(self):
  377. reporter = ExceptionReporter(None, None, "I'm a little teapot", None)
  378. reporter.get_traceback_text()
  379. class ExceptionReportTestMixin(object):
  380. # Mixin used in the ExceptionReporterFilterTests and
  381. # AjaxResponseExceptionReporterFilter tests below
  382. breakfast_data = {'sausage-key': 'sausage-value',
  383. 'baked-beans-key': 'baked-beans-value',
  384. 'hash-brown-key': 'hash-brown-value',
  385. 'bacon-key': 'bacon-value'}
  386. def verify_unsafe_response(self, view, check_for_vars=True,
  387. check_for_POST_params=True):
  388. """
  389. Asserts that potentially sensitive info are displayed in the response.
  390. """
  391. request = self.rf.post('/some_url/', self.breakfast_data)
  392. response = view(request)
  393. if check_for_vars:
  394. # All variables are shown.
  395. self.assertContains(response, 'cooked_eggs', status_code=500)
  396. self.assertContains(response, 'scrambled', status_code=500)
  397. self.assertContains(response, 'sauce', status_code=500)
  398. self.assertContains(response, 'worcestershire', status_code=500)
  399. if check_for_POST_params:
  400. for k, v in self.breakfast_data.items():
  401. # All POST parameters are shown.
  402. self.assertContains(response, k, status_code=500)
  403. self.assertContains(response, v, status_code=500)
  404. def verify_safe_response(self, view, check_for_vars=True,
  405. check_for_POST_params=True):
  406. """
  407. Asserts that certain sensitive info are not displayed in the response.
  408. """
  409. request = self.rf.post('/some_url/', self.breakfast_data)
  410. response = view(request)
  411. if check_for_vars:
  412. # Non-sensitive variable's name and value are shown.
  413. self.assertContains(response, 'cooked_eggs', status_code=500)
  414. self.assertContains(response, 'scrambled', status_code=500)
  415. # Sensitive variable's name is shown but not its value.
  416. self.assertContains(response, 'sauce', status_code=500)
  417. self.assertNotContains(response, 'worcestershire', status_code=500)
  418. if check_for_POST_params:
  419. for k, v in self.breakfast_data.items():
  420. # All POST parameters' names are shown.
  421. self.assertContains(response, k, status_code=500)
  422. # Non-sensitive POST parameters' values are shown.
  423. self.assertContains(response, 'baked-beans-value', status_code=500)
  424. self.assertContains(response, 'hash-brown-value', status_code=500)
  425. # Sensitive POST parameters' values are not shown.
  426. self.assertNotContains(response, 'sausage-value', status_code=500)
  427. self.assertNotContains(response, 'bacon-value', status_code=500)
  428. def verify_paranoid_response(self, view, check_for_vars=True,
  429. check_for_POST_params=True):
  430. """
  431. Asserts that no variables or POST parameters are displayed in the response.
  432. """
  433. request = self.rf.post('/some_url/', self.breakfast_data)
  434. response = view(request)
  435. if check_for_vars:
  436. # Show variable names but not their values.
  437. self.assertContains(response, 'cooked_eggs', status_code=500)
  438. self.assertNotContains(response, 'scrambled', status_code=500)
  439. self.assertContains(response, 'sauce', status_code=500)
  440. self.assertNotContains(response, 'worcestershire', status_code=500)
  441. if check_for_POST_params:
  442. for k, v in self.breakfast_data.items():
  443. # All POST parameters' names are shown.
  444. self.assertContains(response, k, status_code=500)
  445. # No POST parameters' values are shown.
  446. self.assertNotContains(response, v, status_code=500)
  447. def verify_unsafe_email(self, view, check_for_POST_params=True):
  448. """
  449. Asserts that potentially sensitive info are displayed in the email report.
  450. """
  451. with self.settings(ADMINS=(('Admin', 'admin@fattie-breakie.com'),)):
  452. mail.outbox = [] # Empty outbox
  453. request = self.rf.post('/some_url/', self.breakfast_data)
  454. view(request)
  455. self.assertEqual(len(mail.outbox), 1)
  456. email = mail.outbox[0]
  457. # Frames vars are never shown in plain text email reports.
  458. body_plain = force_text(email.body)
  459. self.assertNotIn('cooked_eggs', body_plain)
  460. self.assertNotIn('scrambled', body_plain)
  461. self.assertNotIn('sauce', body_plain)
  462. self.assertNotIn('worcestershire', body_plain)
  463. # Frames vars are shown in html email reports.
  464. body_html = force_text(email.alternatives[0][0])
  465. self.assertIn('cooked_eggs', body_html)
  466. self.assertIn('scrambled', body_html)
  467. self.assertIn('sauce', body_html)
  468. self.assertIn('worcestershire', body_html)
  469. if check_for_POST_params:
  470. for k, v in self.breakfast_data.items():
  471. # All POST parameters are shown.
  472. self.assertIn(k, body_plain)
  473. self.assertIn(v, body_plain)
  474. self.assertIn(k, body_html)
  475. self.assertIn(v, body_html)
  476. def verify_safe_email(self, view, check_for_POST_params=True):
  477. """
  478. Asserts that certain sensitive info are not displayed in the email report.
  479. """
  480. with self.settings(ADMINS=(('Admin', 'admin@fattie-breakie.com'),)):
  481. mail.outbox = [] # Empty outbox
  482. request = self.rf.post('/some_url/', self.breakfast_data)
  483. view(request)
  484. self.assertEqual(len(mail.outbox), 1)
  485. email = mail.outbox[0]
  486. # Frames vars are never shown in plain text email reports.
  487. body_plain = force_text(email.body)
  488. self.assertNotIn('cooked_eggs', body_plain)
  489. self.assertNotIn('scrambled', body_plain)
  490. self.assertNotIn('sauce', body_plain)
  491. self.assertNotIn('worcestershire', body_plain)
  492. # Frames vars are shown in html email reports.
  493. body_html = force_text(email.alternatives[0][0])
  494. self.assertIn('cooked_eggs', body_html)
  495. self.assertIn('scrambled', body_html)
  496. self.assertIn('sauce', body_html)
  497. self.assertNotIn('worcestershire', body_html)
  498. if check_for_POST_params:
  499. for k, v in self.breakfast_data.items():
  500. # All POST parameters' names are shown.
  501. self.assertIn(k, body_plain)
  502. # Non-sensitive POST parameters' values are shown.
  503. self.assertIn('baked-beans-value', body_plain)
  504. self.assertIn('hash-brown-value', body_plain)
  505. self.assertIn('baked-beans-value', body_html)
  506. self.assertIn('hash-brown-value', body_html)
  507. # Sensitive POST parameters' values are not shown.
  508. self.assertNotIn('sausage-value', body_plain)
  509. self.assertNotIn('bacon-value', body_plain)
  510. self.assertNotIn('sausage-value', body_html)
  511. self.assertNotIn('bacon-value', body_html)
  512. def verify_paranoid_email(self, view):
  513. """
  514. Asserts that no variables or POST parameters are displayed in the email report.
  515. """
  516. with self.settings(ADMINS=(('Admin', 'admin@fattie-breakie.com'),)):
  517. mail.outbox = [] # Empty outbox
  518. request = self.rf.post('/some_url/', self.breakfast_data)
  519. view(request)
  520. self.assertEqual(len(mail.outbox), 1)
  521. email = mail.outbox[0]
  522. # Frames vars are never shown in plain text email reports.
  523. body = force_text(email.body)
  524. self.assertNotIn('cooked_eggs', body)
  525. self.assertNotIn('scrambled', body)
  526. self.assertNotIn('sauce', body)
  527. self.assertNotIn('worcestershire', body)
  528. for k, v in self.breakfast_data.items():
  529. # All POST parameters' names are shown.
  530. self.assertIn(k, body)
  531. # No POST parameters' values are shown.
  532. self.assertNotIn(v, body)
  533. @override_settings(ROOT_URLCONF='view_tests.urls')
  534. class ExceptionReporterFilterTests(TestCase, ExceptionReportTestMixin):
  535. """
  536. Ensure that sensitive information can be filtered out of error reports.
  537. Refs #14614.
  538. """
  539. rf = RequestFactory()
  540. def test_non_sensitive_request(self):
  541. """
  542. Ensure that everything (request info and frame variables) can bee seen
  543. in the default error reports for non-sensitive requests.
  544. """
  545. with self.settings(DEBUG=True):
  546. self.verify_unsafe_response(non_sensitive_view)
  547. self.verify_unsafe_email(non_sensitive_view)
  548. with self.settings(DEBUG=False):
  549. self.verify_unsafe_response(non_sensitive_view)
  550. self.verify_unsafe_email(non_sensitive_view)
  551. def test_sensitive_request(self):
  552. """
  553. Ensure that sensitive POST parameters and frame variables cannot be
  554. seen in the default error reports for sensitive requests.
  555. """
  556. with self.settings(DEBUG=True):
  557. self.verify_unsafe_response(sensitive_view)
  558. self.verify_unsafe_email(sensitive_view)
  559. with self.settings(DEBUG=False):
  560. self.verify_safe_response(sensitive_view)
  561. self.verify_safe_email(sensitive_view)
  562. def test_paranoid_request(self):
  563. """
  564. Ensure that no POST parameters and frame variables can be seen in the
  565. default error reports for "paranoid" requests.
  566. """
  567. with self.settings(DEBUG=True):
  568. self.verify_unsafe_response(paranoid_view)
  569. self.verify_unsafe_email(paranoid_view)
  570. with self.settings(DEBUG=False):
  571. self.verify_paranoid_response(paranoid_view)
  572. self.verify_paranoid_email(paranoid_view)
  573. def test_multivalue_dict_key_error(self):
  574. """
  575. #21098 -- Ensure that sensitive POST parameters cannot be seen in the
  576. error reports for if request.POST['nonexistent_key'] throws an error.
  577. """
  578. with self.settings(DEBUG=True):
  579. self.verify_unsafe_response(multivalue_dict_key_error)
  580. self.verify_unsafe_email(multivalue_dict_key_error)
  581. with self.settings(DEBUG=False):
  582. self.verify_safe_response(multivalue_dict_key_error)
  583. self.verify_safe_email(multivalue_dict_key_error)
  584. def test_custom_exception_reporter_filter(self):
  585. """
  586. Ensure that it's possible to assign an exception reporter filter to
  587. the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER.
  588. """
  589. with self.settings(DEBUG=True):
  590. self.verify_unsafe_response(custom_exception_reporter_filter_view)
  591. self.verify_unsafe_email(custom_exception_reporter_filter_view)
  592. with self.settings(DEBUG=False):
  593. self.verify_unsafe_response(custom_exception_reporter_filter_view)
  594. self.verify_unsafe_email(custom_exception_reporter_filter_view)
  595. def test_sensitive_method(self):
  596. """
  597. Ensure that the sensitive_variables decorator works with object
  598. methods.
  599. Refs #18379.
  600. """
  601. with self.settings(DEBUG=True):
  602. self.verify_unsafe_response(sensitive_method_view,
  603. check_for_POST_params=False)
  604. self.verify_unsafe_email(sensitive_method_view,
  605. check_for_POST_params=False)
  606. with self.settings(DEBUG=False):
  607. self.verify_safe_response(sensitive_method_view,
  608. check_for_POST_params=False)
  609. self.verify_safe_email(sensitive_method_view,
  610. check_for_POST_params=False)
  611. def test_sensitive_function_arguments(self):
  612. """
  613. Ensure that sensitive variables don't leak in the sensitive_variables
  614. decorator's frame, when those variables are passed as arguments to the
  615. decorated function.
  616. Refs #19453.
  617. """
  618. with self.settings(DEBUG=True):
  619. self.verify_unsafe_response(sensitive_args_function_caller)
  620. self.verify_unsafe_email(sensitive_args_function_caller)
  621. with self.settings(DEBUG=False):
  622. self.verify_safe_response(sensitive_args_function_caller, check_for_POST_params=False)
  623. self.verify_safe_email(sensitive_args_function_caller, check_for_POST_params=False)
  624. def test_sensitive_function_keyword_arguments(self):
  625. """
  626. Ensure that sensitive variables don't leak in the sensitive_variables
  627. decorator's frame, when those variables are passed as keyword arguments
  628. to the decorated function.
  629. Refs #19453.
  630. """
  631. with self.settings(DEBUG=True):
  632. self.verify_unsafe_response(sensitive_kwargs_function_caller)
  633. self.verify_unsafe_email(sensitive_kwargs_function_caller)
  634. with self.settings(DEBUG=False):
  635. self.verify_safe_response(sensitive_kwargs_function_caller, check_for_POST_params=False)
  636. self.verify_safe_email(sensitive_kwargs_function_caller, check_for_POST_params=False)
  637. def test_callable_settings(self):
  638. """
  639. Callable settings should not be evaluated in the debug page (#21345).
  640. """
  641. def callable_setting():
  642. return "This should not be displayed"
  643. with self.settings(DEBUG=True, FOOBAR=callable_setting):
  644. response = self.client.get('/raises500/')
  645. self.assertNotContains(response, "This should not be displayed", status_code=500)
  646. def test_callable_settings_forbidding_to_set_attributes(self):
  647. """
  648. Callable settings which forbid to set attributes should not break
  649. the debug page (#23070).
  650. """
  651. class CallableSettingWithSlots(object):
  652. __slots__ = []
  653. def __call__(self):
  654. return "This should not be displayed"
  655. with self.settings(DEBUG=True, WITH_SLOTS=CallableSettingWithSlots()):
  656. response = self.client.get('/raises500/')
  657. self.assertNotContains(response, "This should not be displayed", status_code=500)
  658. def test_dict_setting_with_non_str_key(self):
  659. """
  660. A dict setting containing a non-string key should not break the
  661. debug page (#12744).
  662. """
  663. with self.settings(DEBUG=True, FOOBAR={42: None}):
  664. response = self.client.get('/raises500/')
  665. self.assertContains(response, 'FOOBAR', status_code=500)
  666. def test_sensitive_settings(self):
  667. """
  668. The debug page should not show some sensitive settings
  669. (password, secret key, ...).
  670. """
  671. sensitive_settings = [
  672. 'SECRET_KEY',
  673. 'PASSWORD',
  674. 'API_KEY',
  675. 'AUTH_TOKEN',
  676. ]
  677. for setting in sensitive_settings:
  678. with self.settings(DEBUG=True, **{setting: "should not be displayed"}):
  679. response = self.client.get('/raises500/')
  680. self.assertNotContains(response, 'should not be displayed', status_code=500)
  681. def test_settings_with_sensitive_keys(self):
  682. """
  683. The debug page should filter out some sensitive information found in
  684. dict settings.
  685. """
  686. sensitive_settings = [
  687. 'SECRET_KEY',
  688. 'PASSWORD',
  689. 'API_KEY',
  690. 'AUTH_TOKEN',
  691. ]
  692. for setting in sensitive_settings:
  693. FOOBAR = {
  694. setting: "should not be displayed",
  695. 'recursive': {setting: "should not be displayed"},
  696. }
  697. with self.settings(DEBUG=True, FOOBAR=FOOBAR):
  698. response = self.client.get('/raises500/')
  699. self.assertNotContains(response, 'should not be displayed', status_code=500)
  700. class AjaxResponseExceptionReporterFilter(TestCase, ExceptionReportTestMixin):
  701. """
  702. Ensure that sensitive information can be filtered out of error reports.
  703. Here we specifically test the plain text 500 debug-only error page served
  704. when it has been detected the request was sent by JS code. We don't check
  705. for (non)existence of frames vars in the traceback information section of
  706. the response content because we don't include them in these error pages.
  707. Refs #14614.
  708. """
  709. rf = RequestFactory(HTTP_X_REQUESTED_WITH='XMLHttpRequest')
  710. def test_non_sensitive_request(self):
  711. """
  712. Ensure that request info can bee seen in the default error reports for
  713. non-sensitive requests.
  714. """
  715. with self.settings(DEBUG=True):
  716. self.verify_unsafe_response(non_sensitive_view, check_for_vars=False)
  717. with self.settings(DEBUG=False):
  718. self.verify_unsafe_response(non_sensitive_view, check_for_vars=False)
  719. def test_sensitive_request(self):
  720. """
  721. Ensure that sensitive POST parameters cannot be seen in the default
  722. error reports for sensitive requests.
  723. """
  724. with self.settings(DEBUG=True):
  725. self.verify_unsafe_response(sensitive_view, check_for_vars=False)
  726. with self.settings(DEBUG=False):
  727. self.verify_safe_response(sensitive_view, check_for_vars=False)
  728. def test_paranoid_request(self):
  729. """
  730. Ensure that no POST parameters can be seen in the default error reports
  731. for "paranoid" requests.
  732. """
  733. with self.settings(DEBUG=True):
  734. self.verify_unsafe_response(paranoid_view, check_for_vars=False)
  735. with self.settings(DEBUG=False):
  736. self.verify_paranoid_response(paranoid_view, check_for_vars=False)
  737. def test_custom_exception_reporter_filter(self):
  738. """
  739. Ensure that it's possible to assign an exception reporter filter to
  740. the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER.
  741. """
  742. with self.settings(DEBUG=True):
  743. self.verify_unsafe_response(custom_exception_reporter_filter_view,
  744. check_for_vars=False)
  745. with self.settings(DEBUG=False):
  746. self.verify_unsafe_response(custom_exception_reporter_filter_view,
  747. check_for_vars=False)