Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/core/checks/security/csrf.py: 63%

30 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1import inspect 

2 

3from django.conf import settings 

4 

5from .. import Error, Tags, Warning, register 

6 

7W003 = Warning( 

8 "You don't appear to be using Django's built-in " 

9 "cross-site request forgery protection via the middleware " 

10 "('django.middleware.csrf.CsrfViewMiddleware' is not in your " 

11 "MIDDLEWARE). Enabling the middleware is the safest approach " 

12 "to ensure you don't leave any holes.", 

13 id="security.W003", 

14) 

15 

16W016 = Warning( 

17 "You have 'django.middleware.csrf.CsrfViewMiddleware' in your " 

18 "MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. " 

19 "Using a secure-only CSRF cookie makes it more difficult for network " 

20 "traffic sniffers to steal the CSRF token.", 

21 id="security.W016", 

22) 

23 

24 

25def _csrf_middleware(): 

26 return "django.middleware.csrf.CsrfViewMiddleware" in settings.MIDDLEWARE 

27 

28 

29@register(Tags.security, deploy=True) 

30def check_csrf_middleware(app_configs, **kwargs): 

31 passed_check = _csrf_middleware() 

32 return [] if passed_check else [W003] 

33 

34 

35@register(Tags.security, deploy=True) 

36def check_csrf_cookie_secure(app_configs, **kwargs): 

37 passed_check = ( 

38 settings.CSRF_USE_SESSIONS 

39 or not _csrf_middleware() 

40 or settings.CSRF_COOKIE_SECURE 

41 ) 

42 return [] if passed_check else [W016] 

43 

44 

45@register(Tags.security) 

46def check_csrf_failure_view(app_configs, **kwargs): 

47 from django.middleware.csrf import _get_failure_view 

48 

49 errors = [] 

50 try: 

51 view = _get_failure_view() 

52 except ImportError: 

53 msg = ( 

54 "The CSRF failure view '%s' could not be imported." 

55 % settings.CSRF_FAILURE_VIEW 

56 ) 

57 errors.append(Error(msg, id="security.E102")) 

58 else: 

59 try: 

60 inspect.signature(view).bind(None, reason=None) 

61 except TypeError: 

62 msg = ( 

63 "The CSRF failure view '%s' does not take the correct number of " 

64 "arguments." % settings.CSRF_FAILURE_VIEW 

65 ) 

66 errors.append(Error(msg, id="security.E101")) 

67 return errors