From 2e70bf37854e39d46557317fb4098da5261618d5 Mon Sep 17 00:00:00 2001 From: sujayskumar Date: Wed, 24 Jun 2015 15:41:43 +0530 Subject: [PATCH] Fixed #25017 -- Allowed customizing the DISALLOWED_USER_AGENTS response --- django/middleware/common.py | 9 ++------- docs/releases/1.9.txt | 6 ++++++ tests/middleware/tests.py | 6 +++--- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/django/middleware/common.py b/django/middleware/common.py index 68fcb8a780..3d7f365af4 100644 --- a/django/middleware/common.py +++ b/django/middleware/common.py @@ -5,6 +5,7 @@ import re from django import http from django.conf import settings from django.core import urlresolvers +from django.core.exceptions import PermissionDenied from django.core.mail import mail_managers from django.utils.encoding import force_text @@ -47,13 +48,7 @@ class CommonMiddleware(object): if 'HTTP_USER_AGENT' in request.META: for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(request.META['HTTP_USER_AGENT']): - logger.warning('Forbidden (User agent): %s', request.path, - extra={ - 'status_code': 403, - 'request': request - } - ) - return http.HttpResponseForbidden('

Forbidden

') + raise PermissionDenied('Forbidden user agent') # Check for a redirect based on settings.APPEND_SLASH # and settings.PREPEND_WWW diff --git a/docs/releases/1.9.txt b/docs/releases/1.9.txt index 3a105fd3b6..9b0fbb2a02 100644 --- a/docs/releases/1.9.txt +++ b/docs/releases/1.9.txt @@ -452,6 +452,12 @@ Requests and Responses ` to ``None`` to revert any changes made by previous middleware and return to using the :setting:`ROOT_URLCONF`. +* The :setting:`DISALLOWED_USER_AGENTS` check in + :class:`~django.middleware.common.CommonMiddleware` now raises a + :class:`~django.core.exceptions.PermissionDenied` exception as opposed to + returning an :class:`~django.http.HttpResponseForbidden` so that + :data:`~django.conf.urls.handler403` is invoked. + Tests ^^^^^ diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py index db9de1e9b4..eaa1308e64 100644 --- a/tests/middleware/tests.py +++ b/tests/middleware/tests.py @@ -9,6 +9,7 @@ from unittest import skipIf from django.conf import settings from django.core import mail +from django.core.exceptions import PermissionDenied from django.http import ( FileResponse, HttpRequest, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect, StreamingHttpResponse, @@ -256,9 +257,8 @@ class CommonMiddlewareTest(SimpleTestCase): with patch_logger('django.request', 'warning') as log_messages: request = self.rf.get('/slash') request.META['HTTP_USER_AGENT'] = 'foo' - r = CommonMiddleware().process_request(request) - self.assertEqual(r.status_code, 403) - self.assertEqual(log_messages, ['Forbidden (User agent): /slash']) + with self.assertRaisesMessage(PermissionDenied, 'Forbidden user agent'): + CommonMiddleware().process_request(request) def test_non_ascii_query_string_does_not_crash(self): """Regression test for #15152"""