Skip to content

Commit

Permalink
Merge pull request #4228 from broadinstitute/django-csrf-4
Browse files Browse the repository at this point in the history
add custom middleware to log csrf request info
  • Loading branch information
jklugherz authored Jul 11, 2024
2 parents 0bd60f2 + cbd4b49 commit c3166a7
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 4 deletions.
29 changes: 28 additions & 1 deletion seqr/utils/middleware.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from urllib.parse import urlparse

from anymail.exceptions import AnymailError
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.core.handlers.exception import get_exception_response
Expand All @@ -15,7 +17,7 @@
from seqr.utils.logging_utils import SeqrLogger
from seqr.views.utils.json_utils import create_json_response
from seqr.views.utils.terra_api_utils import TerraAPIException
from settings import DEBUG, LOGIN_URL
from settings import DEBUG, LOGIN_URL, CSRF_TRUSTED_ORIGINS

logger = SeqrLogger()

Expand Down Expand Up @@ -170,3 +172,28 @@ def process_response(request, response):
add_never_cache_headers(response)
response['Pragma'] = 'no-cache'
return response


class DebugCSRFMiddleware:
def __init__(self, get_response):
self.get_response = get_response

@staticmethod
def good_origin(request):
return "%s://%s" % (
"https" if request.is_secure() else "http",
request.get_host(),
)

def __call__(self, request):
logger.info(f'request META: {request.META}', request.user)
request_origin = request.META.get('HTTP_ORIGIN')
good_origin = self.good_origin(request)
logger.info(f'request get_host: {request.get_host()}', request.user)
logger.info(f'request is_secure: {request.is_secure()}', request.user)
logger.info(f'request_origin: {request_origin}', request.user)
logger.info(f'good_origin: {good_origin}', request.user)
logger.info(f'settings CSRF_TRUSTED_ORIGINS: {CSRF_TRUSTED_ORIGINS}', request.user)
parsed_origin = urlparse(request_origin)
logger.info(f'parsed request origin: {parsed_origin}', request.user)
return self.get_response(request)
3 changes: 3 additions & 0 deletions seqr/views/utils/terra_api_utils_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ def test_is_anvil_authenticated(self, mock_social_auth_key, mock_terra_url):
class TerraApiUtilsCallsCase(AuthenticationTestCase):
fixtures = ['users', 'social_auth']

def assert_json_logs(self, user, expected_logs, log_start_idx=0):
super().assert_json_logs(user, expected_logs, log_start_idx)

def _check_exceptions(self, path, func, args, kwargs=None, responses_body=None):
url = f'{TEST_TERRA_API_ROOT_URL}{path}'
kwargs = kwargs or {}
Expand Down
4 changes: 2 additions & 2 deletions seqr/views/utils/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,8 +250,8 @@ def reset_logs(self):
self._log_stream.truncate(0)
self._log_stream.seek(0)

def assert_json_logs(self, user, expected):
logs = self._log_stream.getvalue().split('\n')
def assert_json_logs(self, user, expected, log_start_idx=7):
logs = self._log_stream.getvalue().split('\n')[log_start_idx:]
for i, (message, extra) in enumerate(expected):
extra = extra or {}
validate = extra.pop('validate', None)
Expand Down
4 changes: 3 additions & 1 deletion settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,11 @@
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'seqr.utils.middleware.DebugCSRFMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.common.CommonMiddleware',
'csp.middleware.CSPMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'seqr.utils.middleware.CacheControlMiddleware',
Expand Down Expand Up @@ -260,6 +261,7 @@
DEBUG = False
else:
DEBUG = True
CSRF_TRUSTED_ORIGINS = []
# Enable CORS and hijak for local development
INSTALLED_APPS += ['corsheaders', 'hijack']
MIDDLEWARE.insert(0, 'corsheaders.middleware.CorsMiddleware')
Expand Down

0 comments on commit c3166a7

Please sign in to comment.