views.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. from __future__ import unicode_literals
  2. import datetime
  3. import decimal
  4. import logging
  5. import sys
  6. from django.core.exceptions import PermissionDenied, SuspiciousOperation
  7. from django.http import Http404, HttpResponse, JsonResponse
  8. from django.shortcuts import render
  9. from django.template import TemplateDoesNotExist
  10. from django.urls import get_resolver
  11. from django.views import View
  12. from django.views.debug import (
  13. SafeExceptionReporterFilter, technical_500_response,
  14. )
  15. from django.views.decorators.debug import (
  16. sensitive_post_parameters, sensitive_variables,
  17. )
  18. from . import BrokenException, except_args
  19. def index_page(request):
  20. """Dummy index page"""
  21. return HttpResponse('<html><body>Dummy page</body></html>')
  22. def with_parameter(request, parameter):
  23. return HttpResponse('ok')
  24. def raises(request):
  25. # Make sure that a callable that raises an exception in the stack frame's
  26. # local vars won't hijack the technical 500 response (#15025).
  27. def callable():
  28. raise Exception
  29. try:
  30. raise Exception
  31. except Exception:
  32. return technical_500_response(request, *sys.exc_info())
  33. def raises500(request):
  34. # We need to inspect the HTML generated by the fancy 500 debug view but
  35. # the test client ignores it, so we send it explicitly.
  36. try:
  37. raise Exception
  38. except Exception:
  39. return technical_500_response(request, *sys.exc_info())
  40. def raises400(request):
  41. raise SuspiciousOperation
  42. def raises403(request):
  43. raise PermissionDenied("Insufficient Permissions")
  44. def raises404(request):
  45. resolver = get_resolver(None)
  46. resolver.resolve('/not-in-urls')
  47. def technical404(request):
  48. raise Http404("Testing technical 404.")
  49. class Http404View(View):
  50. def get(self, request):
  51. raise Http404("Testing class-based technical 404.")
  52. def view_exception(request, n):
  53. raise BrokenException(except_args[int(n)])
  54. def template_exception(request, n):
  55. return render(request, 'debug/template_exception.html', {'arg': except_args[int(n)]})
  56. def jsi18n(request):
  57. return render(request, 'jsi18n.html')
  58. def old_jsi18n(request):
  59. return render(request, 'old_jsi18n.html')
  60. def jsi18n_multi_catalogs(request):
  61. return render(request, 'jsi18n-multi-catalogs.html')
  62. def old_jsi18n_multi_catalogs(request):
  63. return render(request, 'old_jsi18n-multi-catalogs.html')
  64. def raises_template_does_not_exist(request, path='i_dont_exist.html'):
  65. # We need to inspect the HTML generated by the fancy 500 debug view but
  66. # the test client ignores it, so we send it explicitly.
  67. try:
  68. return render(request, path)
  69. except TemplateDoesNotExist:
  70. return technical_500_response(request, *sys.exc_info())
  71. def render_no_template(request):
  72. # If we do not specify a template, we need to make sure the debug
  73. # view doesn't blow up.
  74. return render(request, [], {})
  75. def send_log(request, exc_info):
  76. logger = logging.getLogger('django')
  77. # The default logging config has a logging filter to ensure admin emails are
  78. # only sent with DEBUG=False, but since someone might choose to remove that
  79. # filter, we still want to be able to test the behavior of error emails
  80. # with DEBUG=True. So we need to remove the filter temporarily.
  81. admin_email_handler = [
  82. h for h in logger.handlers
  83. if h.__class__.__name__ == "AdminEmailHandler"
  84. ][0]
  85. orig_filters = admin_email_handler.filters
  86. admin_email_handler.filters = []
  87. admin_email_handler.include_html = True
  88. logger.error(
  89. 'Internal Server Error: %s', request.path,
  90. exc_info=exc_info,
  91. extra={'status_code': 500, 'request': request},
  92. )
  93. admin_email_handler.filters = orig_filters
  94. def non_sensitive_view(request):
  95. # Do not just use plain strings for the variables' values in the code
  96. # so that the tests don't return false positives when the function's source
  97. # is displayed in the exception report.
  98. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  99. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  100. try:
  101. raise Exception
  102. except Exception:
  103. exc_info = sys.exc_info()
  104. send_log(request, exc_info)
  105. return technical_500_response(request, *exc_info)
  106. @sensitive_variables('sauce')
  107. @sensitive_post_parameters('bacon-key', 'sausage-key')
  108. def sensitive_view(request):
  109. # Do not just use plain strings for the variables' values in the code
  110. # so that the tests don't return false positives when the function's source
  111. # is displayed in the exception report.
  112. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  113. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  114. try:
  115. raise Exception
  116. except Exception:
  117. exc_info = sys.exc_info()
  118. send_log(request, exc_info)
  119. return technical_500_response(request, *exc_info)
  120. @sensitive_variables()
  121. @sensitive_post_parameters()
  122. def paranoid_view(request):
  123. # Do not just use plain strings for the variables' values in the code
  124. # so that the tests don't return false positives when the function's source
  125. # is displayed in the exception report.
  126. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  127. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  128. try:
  129. raise Exception
  130. except Exception:
  131. exc_info = sys.exc_info()
  132. send_log(request, exc_info)
  133. return technical_500_response(request, *exc_info)
  134. def sensitive_args_function_caller(request):
  135. try:
  136. sensitive_args_function(''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']))
  137. except Exception:
  138. exc_info = sys.exc_info()
  139. send_log(request, exc_info)
  140. return technical_500_response(request, *exc_info)
  141. @sensitive_variables('sauce')
  142. def sensitive_args_function(sauce):
  143. # Do not just use plain strings for the variables' values in the code
  144. # so that the tests don't return false positives when the function's source
  145. # is displayed in the exception report.
  146. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  147. raise Exception
  148. def sensitive_kwargs_function_caller(request):
  149. try:
  150. sensitive_kwargs_function(''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']))
  151. except Exception:
  152. exc_info = sys.exc_info()
  153. send_log(request, exc_info)
  154. return technical_500_response(request, *exc_info)
  155. @sensitive_variables('sauce')
  156. def sensitive_kwargs_function(sauce=None):
  157. # Do not just use plain strings for the variables' values in the code
  158. # so that the tests don't return false positives when the function's source
  159. # is displayed in the exception report.
  160. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  161. raise Exception
  162. class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter):
  163. """
  164. Ignores all the filtering done by its parent class.
  165. """
  166. def get_post_parameters(self, request):
  167. return request.POST
  168. def get_traceback_frame_variables(self, request, tb_frame):
  169. return tb_frame.f_locals.items()
  170. @sensitive_variables()
  171. @sensitive_post_parameters()
  172. def custom_exception_reporter_filter_view(request):
  173. # Do not just use plain strings for the variables' values in the code
  174. # so that the tests don't return false positives when the function's source
  175. # is displayed in the exception report.
  176. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  177. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  178. request.exception_reporter_filter = UnsafeExceptionReporterFilter()
  179. try:
  180. raise Exception
  181. except Exception:
  182. exc_info = sys.exc_info()
  183. send_log(request, exc_info)
  184. return technical_500_response(request, *exc_info)
  185. class Klass(object):
  186. @sensitive_variables('sauce')
  187. def method(self, request):
  188. # Do not just use plain strings for the variables' values in the code
  189. # so that the tests don't return false positives when the function's
  190. # source is displayed in the exception report.
  191. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  192. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  193. try:
  194. raise Exception
  195. except Exception:
  196. exc_info = sys.exc_info()
  197. send_log(request, exc_info)
  198. return technical_500_response(request, *exc_info)
  199. def sensitive_method_view(request):
  200. return Klass().method(request)
  201. @sensitive_variables('sauce')
  202. @sensitive_post_parameters('bacon-key', 'sausage-key')
  203. def multivalue_dict_key_error(request):
  204. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  205. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  206. try:
  207. request.POST['bar']
  208. except Exception:
  209. exc_info = sys.exc_info()
  210. send_log(request, exc_info)
  211. return technical_500_response(request, *exc_info)
  212. def json_response_view(request):
  213. return JsonResponse({
  214. 'a': [1, 2, 3],
  215. 'foo': {'bar': 'baz'},
  216. # Make sure datetime and Decimal objects would be serialized properly
  217. 'timestamp': datetime.datetime(2013, 5, 19, 20),
  218. 'value': decimal.Decimal('3.14'),
  219. })