Debian Codegraph @

tests/view_tests/views.py

raw
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("sauce")
182 @sensitive_post_parameters("bacon-key", "sausage-key")
183 async def async_sensitive_view(request):
184 # Do not just use plain strings for the variables' values in the code so
185 # that the tests don't return false positives when the function's source is
186 # 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 @sensitive_variables("sauce")
200 @sensitive_post_parameters("bacon-key", "sausage-key")
201 async def async_sensitive_function(request):
202 # Do not just use plain strings for the variables' values in the code so
203 # that the tests don't return false positives when the function's source is
204 # displayed in the exception report.
205 cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
206 sauce = "".join( # NOQA
207 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
208 )
209 raise Exception
210
211
212 async def async_sensitive_view_nested(request):
213 try:
214 await async_sensitive_function(request)
215 except Exception:
216 exc_info = sys.exc_info()
217 send_log(request, exc_info)
218 return technical_500_response(request, *exc_info)
219
220
221 @sensitive_variables()
222 @sensitive_post_parameters()
223 def paranoid_view(request):
224 # Do not just use plain strings for the variables' values in the code
225 # so that the tests don't return false positives when the function's source
226 # is displayed in the exception report.
227 cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
228 sauce = "".join( # NOQA
229 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
230 )
231 try:
232 raise Exception
233 except Exception:
234 exc_info = sys.exc_info()
235 send_log(request, exc_info)
236 return technical_500_response(request, *exc_info)
237
238
239 def sensitive_args_function_caller(request):
240 try:
241 sensitive_args_function(
242 "".join(
243 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
244 )
245 )
246 except Exception:
247 exc_info = sys.exc_info()
248 send_log(request, exc_info)
249 return technical_500_response(request, *exc_info)
250
251
252 @sensitive_variables("sauce")
253 def sensitive_args_function(sauce):
254 # Do not just use plain strings for the variables' values in the code
255 # so that the tests don't return false positives when the function's source
256 # is displayed in the exception report.
257 cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
258 raise Exception
259
260
261 def sensitive_kwargs_function_caller(request):
262 try:
263 sensitive_kwargs_function(
264 "".join(
265 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
266 )
267 )
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 @sensitive_variables("sauce")
275 def sensitive_kwargs_function(sauce=None):
276 # Do not just use plain strings for the variables' values in the code
277 # so that the tests don't return false positives when the function's source
278 # is displayed in the exception report.
279 cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
280 raise Exception
281
282
283 class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter):
284 """
285 Ignores all the filtering done by its parent class.
286 """
287
288 def get_post_parameters(self, request):
289 return request.POST
290
291 def get_traceback_frame_variables(self, request, tb_frame):
292 return tb_frame.f_locals.items()
293
294
295 @sensitive_variables()
296 @sensitive_post_parameters()
297 def custom_exception_reporter_filter_view(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 source
300 # 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 request.exception_reporter_filter = UnsafeExceptionReporterFilter()
306 try:
307 raise Exception
308 except Exception:
309 exc_info = sys.exc_info()
310 send_log(request, exc_info)
311 return technical_500_response(request, *exc_info)
312
313
314 class CustomExceptionReporter(ExceptionReporter):
315 custom_traceback_text = "custom traceback text"
316
317 def get_traceback_html(self):
318 return self.custom_traceback_text
319
320
321 class TemplateOverrideExceptionReporter(ExceptionReporter):
322 html_template_path = TEMPLATES_PATH / "my_technical_500.html"
323 text_template_path = TEMPLATES_PATH / "my_technical_500.txt"
324
325
326 def custom_reporter_class_view(request):
327 request.exception_reporter_class = CustomExceptionReporter
328 try:
329 raise Exception
330 except Exception:
331 exc_info = sys.exc_info()
332 return technical_500_response(request, *exc_info)
333
334
335 class Klass:
336 @sensitive_variables("sauce")
337 def method(self, request):
338 # Do not just use plain strings for the variables' values in the code
339 # so that the tests don't return false positives when the function's
340 # source is displayed in the exception report.
341 cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
342 sauce = "".join( # NOQA
343 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
344 )
345 try:
346 raise Exception
347 except Exception:
348 exc_info = sys.exc_info()
349 send_log(request, exc_info)
350 return technical_500_response(request, *exc_info)
351
352 @sensitive_variables("sauce")
353 async def async_method(self, request):
354 # Do not just use plain strings for the variables' values in the code
355 # so that the tests don't return false positives when the function's
356 # source is displayed in the exception report.
357 cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
358 sauce = "".join( # NOQA
359 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
360 )
361 try:
362 raise Exception
363 except Exception:
364 exc_info = sys.exc_info()
365 send_log(request, exc_info)
366 return technical_500_response(request, *exc_info)
367
368 @sensitive_variables("sauce")
369 async def _async_method_inner(self, request):
370 # Do not just use plain strings for the variables' values in the code
371 # so that the tests don't return false positives when the function's
372 # source is displayed in the exception report.
373 cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
374 sauce = "".join( # NOQA
375 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
376 )
377 raise Exception
378
379 async def async_method_nested(self, request):
380 try:
381 await self._async_method_inner(request)
382 except Exception:
383 exc_info = sys.exc_info()
384 send_log(request, exc_info)
385 return technical_500_response(request, *exc_info)
386
387
388 def sensitive_method_view(request):
389 return Klass().method(request)
390
391
392 async def async_sensitive_method_view(request):
393 return await Klass().async_method(request)
394
395
396 async def async_sensitive_method_view_nested(request):
397 return await Klass().async_method_nested(request)
398
399
400 @sensitive_variables("sauce")
401 @sensitive_post_parameters("bacon-key", "sausage-key")
402 def multivalue_dict_key_error(request):
403 cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
404 sauce = "".join( # NOQA
405 ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
406 )
407 try:
408 request.POST["bar"]
409 except Exception:
410 exc_info = sys.exc_info()
411 send_log(request, exc_info)
412 return technical_500_response(request, *exc_info)
413
414
415 def json_response_view(request):
416 return JsonResponse(
417 {
418 "a": [1, 2, 3],
419 "foo": {"bar": "baz"},
420 # Make sure datetime and Decimal objects would be serialized properly
421 "timestamp": datetime.datetime(2013, 5, 19, 20),
422 "value": decimal.Decimal("3.14"),
423 }
424 )