views.py 9.5 KB

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