Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/middleware/security.py: 68%
36 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1import re
3from django.conf import settings
4from django.http import HttpResponsePermanentRedirect
5from django.utils.deprecation import MiddlewareMixin
8class SecurityMiddleware(MiddlewareMixin):
9 def __init__(self, get_response):
10 super().__init__(get_response)
11 self.sts_seconds = settings.SECURE_HSTS_SECONDS
12 self.sts_include_subdomains = settings.SECURE_HSTS_INCLUDE_SUBDOMAINS
13 self.sts_preload = settings.SECURE_HSTS_PRELOAD
14 self.content_type_nosniff = settings.SECURE_CONTENT_TYPE_NOSNIFF
15 self.redirect = settings.SECURE_SSL_REDIRECT
16 self.redirect_host = settings.SECURE_SSL_HOST
17 self.redirect_exempt = [re.compile(r) for r in settings.SECURE_REDIRECT_EXEMPT]
18 self.referrer_policy = settings.SECURE_REFERRER_POLICY
19 self.cross_origin_opener_policy = settings.SECURE_CROSS_ORIGIN_OPENER_POLICY
21 def process_request(self, request):
22 path = request.path.lstrip("/")
23 if ( 23 ↛ exit, 23 ↛ 282 missed branches: 1) line 23 didn't jump to the function exit, 2) line 23 didn't jump to line 28
24 self.redirect
25 and not request.is_secure()
26 and not any(pattern.search(path) for pattern in self.redirect_exempt)
27 ):
28 host = self.redirect_host or request.get_host()
29 return HttpResponsePermanentRedirect(
30 "https://%s%s" % (host, request.get_full_path())
31 )
33 def process_response(self, request, response):
34 if ( 34 ↛ 39line 34 didn't jump to line 39
35 self.sts_seconds
36 and request.is_secure()
37 and "Strict-Transport-Security" not in response
38 ):
39 sts_header = "max-age=%s" % self.sts_seconds
40 if self.sts_include_subdomains:
41 sts_header = sts_header + "; includeSubDomains"
42 if self.sts_preload:
43 sts_header = sts_header + "; preload"
44 response.headers["Strict-Transport-Security"] = sts_header
46 if self.content_type_nosniff: 46 ↛ 49line 46 didn't jump to line 49, because the condition on line 46 was never false
47 response.headers.setdefault("X-Content-Type-Options", "nosniff")
49 if self.referrer_policy: 49 ↛ 61line 49 didn't jump to line 61, because the condition on line 49 was never false
50 # Support a comma-separated string or iterable of values to allow
51 # fallback.
52 response.headers.setdefault(
53 "Referrer-Policy",
54 ",".join(
55 [v.strip() for v in self.referrer_policy.split(",")]
56 if isinstance(self.referrer_policy, str)
57 else self.referrer_policy
58 ),
59 )
61 if self.cross_origin_opener_policy: 61 ↛ 66line 61 didn't jump to line 66, because the condition on line 61 was never false
62 response.setdefault(
63 "Cross-Origin-Opener-Policy",
64 self.cross_origin_opener_policy,
65 )
66 return response