1. import datetime
    
  2. import decimal
    
  3. import logging
    
  4. import sys
    
  5. from pathlib import Path
    
  6. 
    
  7. from django.core.exceptions import BadRequest, PermissionDenied, SuspiciousOperation
    
  8. from django.http import Http404, HttpResponse, JsonResponse
    
  9. from django.shortcuts import render
    
  10. from django.template import Context, Template, TemplateDoesNotExist
    
  11. from django.urls import get_resolver
    
  12. from django.views import View
    
  13. from django.views.debug import (
    
  14.     ExceptionReporter,
    
  15.     SafeExceptionReporterFilter,
    
  16.     technical_500_response,
    
  17. )
    
  18. from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables
    
  19. 
    
  20. TEMPLATES_PATH = Path(__file__).resolve().parent / "templates"
    
  21. 
    
  22. 
    
  23. def index_page(request):
    
  24.     """Dummy index page"""
    
  25.     return HttpResponse("<html><body>Dummy page</body></html>")
    
  26. 
    
  27. 
    
  28. def with_parameter(request, parameter):
    
  29.     return HttpResponse("ok")
    
  30. 
    
  31. 
    
  32. def raises(request):
    
  33.     # Make sure that a callable that raises an exception in the stack frame's
    
  34.     # local vars won't hijack the technical 500 response (#15025).
    
  35.     def callable():
    
  36.         raise Exception
    
  37. 
    
  38.     try:
    
  39.         raise Exception
    
  40.     except Exception:
    
  41.         return technical_500_response(request, *sys.exc_info())
    
  42. 
    
  43. 
    
  44. def raises500(request):
    
  45.     # We need to inspect the HTML generated by the fancy 500 debug view but
    
  46.     # the test client ignores it, so we send it explicitly.
    
  47.     try:
    
  48.         raise Exception
    
  49.     except Exception:
    
  50.         return technical_500_response(request, *sys.exc_info())
    
  51. 
    
  52. 
    
  53. class Raises500View(View):
    
  54.     def get(self, request):
    
  55.         try:
    
  56.             raise Exception
    
  57.         except Exception:
    
  58.             return technical_500_response(request, *sys.exc_info())
    
  59. 
    
  60. 
    
  61. def raises400(request):
    
  62.     raise SuspiciousOperation
    
  63. 
    
  64. 
    
  65. def raises400_bad_request(request):
    
  66.     raise BadRequest("Malformed request syntax")
    
  67. 
    
  68. 
    
  69. def raises403(request):
    
  70.     raise PermissionDenied("Insufficient Permissions")
    
  71. 
    
  72. 
    
  73. def raises404(request):
    
  74.     resolver = get_resolver(None)
    
  75.     resolver.resolve("/not-in-urls")
    
  76. 
    
  77. 
    
  78. def technical404(request):
    
  79.     raise Http404("Testing technical 404.")
    
  80. 
    
  81. 
    
  82. class Http404View(View):
    
  83.     def get(self, request):
    
  84.         raise Http404("Testing class-based technical 404.")
    
  85. 
    
  86. 
    
  87. def template_exception(request):
    
  88.     return render(request, "debug/template_exception.html")
    
  89. 
    
  90. 
    
  91. def safestring_in_template_exception(request):
    
  92.     """
    
  93.     Trigger an exception in the template machinery which causes a SafeString
    
  94.     to be inserted as args[0] of the Exception.
    
  95.     """
    
  96.     template = Template('{% extends "<script>alert(1);</script>" %}')
    
  97.     try:
    
  98.         template.render(Context())
    
  99.     except Exception:
    
  100.         return technical_500_response(request, *sys.exc_info())
    
  101. 
    
  102. 
    
  103. def jsi18n(request):
    
  104.     return render(request, "jsi18n.html")
    
  105. 
    
  106. 
    
  107. def jsi18n_multi_catalogs(request):
    
  108.     return render(request, "jsi18n-multi-catalogs.html")
    
  109. 
    
  110. 
    
  111. def raises_template_does_not_exist(request, path="i_dont_exist.html"):
    
  112.     # We need to inspect the HTML generated by the fancy 500 debug view but
    
  113.     # the test client ignores it, so we send it explicitly.
    
  114.     try:
    
  115.         return render(request, path)
    
  116.     except TemplateDoesNotExist:
    
  117.         return technical_500_response(request, *sys.exc_info())
    
  118. 
    
  119. 
    
  120. def render_no_template(request):
    
  121.     # If we do not specify a template, we need to make sure the debug
    
  122.     # view doesn't blow up.
    
  123.     return render(request, [], {})
    
  124. 
    
  125. 
    
  126. def send_log(request, exc_info):
    
  127.     logger = logging.getLogger("django")
    
  128.     # The default logging config has a logging filter to ensure admin emails are
    
  129.     # only sent with DEBUG=False, but since someone might choose to remove that
    
  130.     # filter, we still want to be able to test the behavior of error emails
    
  131.     # with DEBUG=True. So we need to remove the filter temporarily.
    
  132.     admin_email_handler = [
    
  133.         h for h in logger.handlers if h.__class__.__name__ == "AdminEmailHandler"
    
  134.     ][0]
    
  135.     orig_filters = admin_email_handler.filters
    
  136.     admin_email_handler.filters = []
    
  137.     admin_email_handler.include_html = True
    
  138.     logger.error(
    
  139.         "Internal Server Error: %s",
    
  140.         request.path,
    
  141.         exc_info=exc_info,
    
  142.         extra={"status_code": 500, "request": request},
    
  143.     )
    
  144.     admin_email_handler.filters = orig_filters
    
  145. 
    
  146. 
    
  147. def non_sensitive_view(request):
    
  148.     # Do not just use plain strings for the variables' values in the code
    
  149.     # so that the tests don't return false positives when the function's source
    
  150.     # is displayed in the exception report.
    
  151.     cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"])  # NOQA
    
  152.     sauce = "".join(  # NOQA
    
  153.         ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
    
  154.     )
    
  155.     try:
    
  156.         raise Exception
    
  157.     except Exception:
    
  158.         exc_info = sys.exc_info()
    
  159.         send_log(request, exc_info)
    
  160.         return technical_500_response(request, *exc_info)
    
  161. 
    
  162. 
    
  163. @sensitive_variables("sauce")
    
  164. @sensitive_post_parameters("bacon-key", "sausage-key")
    
  165. def sensitive_view(request):
    
  166.     # Do not just use plain strings for the variables' values in the code
    
  167.     # so that the tests don't return false positives when the function's source
    
  168.     # is displayed in the exception report.
    
  169.     cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"])  # NOQA
    
  170.     sauce = "".join(  # NOQA
    
  171.         ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
    
  172.     )
    
  173.     try:
    
  174.         raise Exception
    
  175.     except Exception:
    
  176.         exc_info = sys.exc_info()
    
  177.         send_log(request, exc_info)
    
  178.         return technical_500_response(request, *exc_info)
    
  179. 
    
  180. 
    
  181. @sensitive_variables()
    
  182. @sensitive_post_parameters()
    
  183. def paranoid_view(request):
    
  184.     # Do not just use plain strings for the variables' values in the code
    
  185.     # so that the tests don't return false positives when the function's source
    
  186.     # is displayed in the exception report.
    
  187.     cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"])  # NOQA
    
  188.     sauce = "".join(  # NOQA
    
  189.         ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
    
  190.     )
    
  191.     try:
    
  192.         raise Exception
    
  193.     except Exception:
    
  194.         exc_info = sys.exc_info()
    
  195.         send_log(request, exc_info)
    
  196.         return technical_500_response(request, *exc_info)
    
  197. 
    
  198. 
    
  199. def sensitive_args_function_caller(request):
    
  200.     try:
    
  201.         sensitive_args_function(
    
  202.             "".join(
    
  203.                 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
    
  204.             )
    
  205.         )
    
  206.     except Exception:
    
  207.         exc_info = sys.exc_info()
    
  208.         send_log(request, exc_info)
    
  209.         return technical_500_response(request, *exc_info)
    
  210. 
    
  211. 
    
  212. @sensitive_variables("sauce")
    
  213. def sensitive_args_function(sauce):
    
  214.     # Do not just use plain strings for the variables' values in the code
    
  215.     # so that the tests don't return false positives when the function's source
    
  216.     # is displayed in the exception report.
    
  217.     cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"])  # NOQA
    
  218.     raise Exception
    
  219. 
    
  220. 
    
  221. def sensitive_kwargs_function_caller(request):
    
  222.     try:
    
  223.         sensitive_kwargs_function(
    
  224.             "".join(
    
  225.                 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
    
  226.             )
    
  227.         )
    
  228.     except Exception:
    
  229.         exc_info = sys.exc_info()
    
  230.         send_log(request, exc_info)
    
  231.         return technical_500_response(request, *exc_info)
    
  232. 
    
  233. 
    
  234. @sensitive_variables("sauce")
    
  235. def sensitive_kwargs_function(sauce=None):
    
  236.     # Do not just use plain strings for the variables' values in the code
    
  237.     # so that the tests don't return false positives when the function's source
    
  238.     # is displayed in the exception report.
    
  239.     cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"])  # NOQA
    
  240.     raise Exception
    
  241. 
    
  242. 
    
  243. class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter):
    
  244.     """
    
  245.     Ignores all the filtering done by its parent class.
    
  246.     """
    
  247. 
    
  248.     def get_post_parameters(self, request):
    
  249.         return request.POST
    
  250. 
    
  251.     def get_traceback_frame_variables(self, request, tb_frame):
    
  252.         return tb_frame.f_locals.items()
    
  253. 
    
  254. 
    
  255. @sensitive_variables()
    
  256. @sensitive_post_parameters()
    
  257. def custom_exception_reporter_filter_view(request):
    
  258.     # Do not just use plain strings for the variables' values in the code
    
  259.     # so that the tests don't return false positives when the function's source
    
  260.     # is displayed in the exception report.
    
  261.     cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"])  # NOQA
    
  262.     sauce = "".join(  # NOQA
    
  263.         ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
    
  264.     )
    
  265.     request.exception_reporter_filter = UnsafeExceptionReporterFilter()
    
  266.     try:
    
  267.         raise Exception
    
  268.     except Exception:
    
  269.         exc_info = sys.exc_info()
    
  270.         send_log(request, exc_info)
    
  271.         return technical_500_response(request, *exc_info)
    
  272. 
    
  273. 
    
  274. class CustomExceptionReporter(ExceptionReporter):
    
  275.     custom_traceback_text = "custom traceback text"
    
  276. 
    
  277.     def get_traceback_html(self):
    
  278.         return self.custom_traceback_text
    
  279. 
    
  280. 
    
  281. class TemplateOverrideExceptionReporter(ExceptionReporter):
    
  282.     html_template_path = TEMPLATES_PATH / "my_technical_500.html"
    
  283.     text_template_path = TEMPLATES_PATH / "my_technical_500.txt"
    
  284. 
    
  285. 
    
  286. def custom_reporter_class_view(request):
    
  287.     request.exception_reporter_class = CustomExceptionReporter
    
  288.     try:
    
  289.         raise Exception
    
  290.     except Exception:
    
  291.         exc_info = sys.exc_info()
    
  292.         return technical_500_response(request, *exc_info)
    
  293. 
    
  294. 
    
  295. class Klass:
    
  296.     @sensitive_variables("sauce")
    
  297.     def method(self, request):
    
  298.         # Do not just use plain strings for the variables' values in the code
    
  299.         # so that the tests don't return false positives when the function's
    
  300.         # source is displayed in the exception report.
    
  301.         cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"])  # NOQA
    
  302.         sauce = "".join(  # NOQA
    
  303.             ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
    
  304.         )
    
  305.         try:
    
  306.             raise Exception
    
  307.         except Exception:
    
  308.             exc_info = sys.exc_info()
    
  309.             send_log(request, exc_info)
    
  310.             return technical_500_response(request, *exc_info)
    
  311. 
    
  312. 
    
  313. def sensitive_method_view(request):
    
  314.     return Klass().method(request)
    
  315. 
    
  316. 
    
  317. @sensitive_variables("sauce")
    
  318. @sensitive_post_parameters("bacon-key", "sausage-key")
    
  319. def multivalue_dict_key_error(request):
    
  320.     cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"])  # NOQA
    
  321.     sauce = "".join(  # NOQA
    
  322.         ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
    
  323.     )
    
  324.     try:
    
  325.         request.POST["bar"]
    
  326.     except Exception:
    
  327.         exc_info = sys.exc_info()
    
  328.         send_log(request, exc_info)
    
  329.         return technical_500_response(request, *exc_info)
    
  330. 
    
  331. 
    
  332. def json_response_view(request):
    
  333.     return JsonResponse(
    
  334.         {
    
  335.             "a": [1, 2, 3],
    
  336.             "foo": {"bar": "baz"},
    
  337.             # Make sure datetime and Decimal objects would be serialized properly
    
  338.             "timestamp": datetime.datetime(2013, 5, 19, 20),
    
  339.             "value": decimal.Decimal("3.14"),
    
  340.         }
    
  341.     )