| 1 |
import logging |
| 2 |
import re |
| 3 |
|
| 4 |
from django.conf import settings |
| 5 |
from django.contrib.sessions.backends.cache import SessionStore |
| 6 |
from django.core.exceptions import ImproperlyConfigured |
| 7 |
from django.http import HttpRequest, HttpResponse, UnreadablePostError |
| 8 |
from django.middleware.csrf import ( |
| 9 |
CSRF_ALLOWED_CHARS, |
| 10 |
CSRF_SECRET_LENGTH, |
| 11 |
CSRF_SESSION_KEY, |
| 12 |
CSRF_TOKEN_LENGTH, |
| 13 |
REASON_BAD_ORIGIN, |
| 14 |
REASON_CSRF_TOKEN_MISSING, |
| 15 |
REASON_NO_CSRF_COOKIE, |
| 16 |
CsrfViewMiddleware, |
| 17 |
InvalidTokenFormat, |
| 18 |
RejectRequest, |
| 19 |
_check_token_format, |
| 20 |
_does_token_match, |
| 21 |
_mask_cipher_secret, |
| 22 |
_unmask_cipher_token, |
| 23 |
get_token, |
| 24 |
rotate_token, |
| 25 |
) |
| 26 |
from django.test import SimpleTestCase, override_settings |
| 27 |
from django.views.decorators.csrf import csrf_exempt, requires_csrf_token |
| 28 |
|
| 29 |
from .views import ( |
| 30 |
ensure_csrf_cookie_view, |
| 31 |
ensured_and_protected_view, |
| 32 |
non_token_view_using_request_processor, |
| 33 |
post_form_view, |
| 34 |
protected_view, |
| 35 |
sandwiched_rotate_token_view, |
| 36 |
token_view, |
| 37 |
) |
| 38 |
|
| 39 |
# This is a test (unmasked) CSRF cookie / secret. |
| 40 |
TEST_SECRET = "lcccccccX2kcccccccY2jcccccccssIC" |
| 41 |
# Two masked versions of TEST_SECRET for testing purposes. |
| 42 |
MASKED_TEST_SECRET1 = "1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD" |
| 43 |
MASKED_TEST_SECRET2 = "2JgchWvM1tpxT2lfz9aydoXW9yT1DN3NdLiejYxOOlzzV4nhBbYqmqZYbAV3V5Bf" |
| 44 |
|
| 45 |
|
| 46 |
class CsrfFunctionTestMixin: |
| 47 |
# This method depends on _unmask_cipher_token() being correct. |
| 48 |
def assertMaskedSecretCorrect(self, masked_secret, secret): |
| 49 |
"""Test that a string is a valid masked version of a secret.""" |
| 50 |
self.assertEqual(len(masked_secret), CSRF_TOKEN_LENGTH) |
| 51 |
self.assertEqual(len(secret), CSRF_SECRET_LENGTH) |
| 52 |
self.assertTrue( |
| 53 |
set(masked_secret).issubset(set(CSRF_ALLOWED_CHARS)), |
| 54 |
msg=f"invalid characters in {masked_secret!r}", |
| 55 |
) |
| 56 |
actual = _unmask_cipher_token(masked_secret) |
| 57 |
self.assertEqual(actual, secret) |
| 58 |
|
| 59 |
def assertForbiddenReason( |
| 60 |
self, response, logger_cm, reason, levelno=logging.WARNING |
| 61 |
): |
| 62 |
self.assertEqual( |
| 63 |
records_len := len(logger_cm.records), |
| 64 |
1, |
| 65 |
f"Unexpected number of records for {logger_cm=} in {levelno=} (expected 1, " |
| 66 |
f"got {records_len}).", |
| 67 |
) |
| 68 |
record = logger_cm.records[0] |
| 69 |
self.assertEqual(record.getMessage(), "Forbidden (%s): " % reason) |
| 70 |
self.assertEqual(record.levelno, levelno) |
| 71 |
self.assertEqual(record.status_code, 403) |
| 72 |
self.assertEqual(response.status_code, 403) |
| 73 |
|
| 74 |
|
| 75 |
class CsrfFunctionTests(CsrfFunctionTestMixin, SimpleTestCase): |
| 76 |
def test_unmask_cipher_token(self): |
| 77 |
cases = [ |
| 78 |
(TEST_SECRET, MASKED_TEST_SECRET1), |
| 79 |
(TEST_SECRET, MASKED_TEST_SECRET2), |
| 80 |
( |
| 81 |
32 * "a", |
| 82 |
"vFioG3XOLyGyGsPRFyB9iYUs341ufzIEvFioG3XOLyGyGsPRFyB9iYUs341ufzIE", |
| 83 |
), |
| 84 |
(32 * "a", 64 * "a"), |
| 85 |
(32 * "a", 64 * "b"), |
| 86 |
(32 * "b", 32 * "a" + 32 * "b"), |
| 87 |
(32 * "b", 32 * "b" + 32 * "c"), |
| 88 |
(32 * "c", 32 * "a" + 32 * "c"), |
| 89 |
] |
| 90 |
for secret, masked_secret in cases: |
| 91 |
with self.subTest(masked_secret=masked_secret): |
| 92 |
actual = _unmask_cipher_token(masked_secret) |
| 93 |
self.assertEqual(actual, secret) |
| 94 |
|
| 95 |
def test_mask_cipher_secret(self): |
| 96 |
cases = [ |
| 97 |
32 * "a", |
| 98 |
TEST_SECRET, |
| 99 |
"da4SrUiHJYoJ0HYQ0vcgisoIuFOxx4ER", |
| 100 |
] |
| 101 |
for secret in cases: |
| 102 |
with self.subTest(secret=secret): |
| 103 |
masked = _mask_cipher_secret(secret) |
| 104 |
self.assertMaskedSecretCorrect(masked, secret) |
| 105 |
|
| 106 |
def test_get_token_csrf_cookie_set(self): |
| 107 |
request = HttpRequest() |
| 108 |
request.META["CSRF_COOKIE"] = TEST_SECRET |
| 109 |
self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) |
| 110 |
token = get_token(request) |
| 111 |
self.assertMaskedSecretCorrect(token, TEST_SECRET) |
| 112 |
# The existing cookie is preserved. |
| 113 |
self.assertEqual(request.META["CSRF_COOKIE"], TEST_SECRET) |
| 114 |
self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) |
| 115 |
|
| 116 |
def test_get_token_csrf_cookie_not_set(self): |
| 117 |
request = HttpRequest() |
| 118 |
self.assertNotIn("CSRF_COOKIE", request.META) |
| 119 |
self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) |
| 120 |
token = get_token(request) |
| 121 |
cookie = request.META["CSRF_COOKIE"] |
| 122 |
self.assertMaskedSecretCorrect(token, cookie) |
| 123 |
self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) |
| 124 |
|
| 125 |
def test_rotate_token(self): |
| 126 |
request = HttpRequest() |
| 127 |
request.META["CSRF_COOKIE"] = TEST_SECRET |
| 128 |
self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) |
| 129 |
rotate_token(request) |
| 130 |
# The underlying secret was changed. |
| 131 |
cookie = request.META["CSRF_COOKIE"] |
| 132 |
self.assertEqual(len(cookie), CSRF_SECRET_LENGTH) |
| 133 |
self.assertNotEqual(cookie, TEST_SECRET) |
| 134 |
self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) |
| 135 |
|
| 136 |
def test_check_token_format_valid(self): |
| 137 |
cases = [ |
| 138 |
# A token of length CSRF_SECRET_LENGTH. |
| 139 |
TEST_SECRET, |
| 140 |
# A token of length CSRF_TOKEN_LENGTH. |
| 141 |
MASKED_TEST_SECRET1, |
| 142 |
64 * "a", |
| 143 |
] |
| 144 |
for token in cases: |
| 145 |
with self.subTest(token=token): |
| 146 |
actual = _check_token_format(token) |
| 147 |
self.assertIsNone(actual) |
| 148 |
|
| 149 |
def test_check_token_format_invalid(self): |
| 150 |
cases = [ |
| 151 |
(64 * "*", "has invalid characters"), |
| 152 |
(16 * "a", "has incorrect length"), |
| 153 |
] |
| 154 |
for token, expected_message in cases: |
| 155 |
with self.subTest(token=token): |
| 156 |
with self.assertRaisesMessage(InvalidTokenFormat, expected_message): |
| 157 |
_check_token_format(token) |
| 158 |
|
| 159 |
def test_does_token_match(self): |
| 160 |
cases = [ |
| 161 |
# Masked tokens match. |
| 162 |
((MASKED_TEST_SECRET1, TEST_SECRET), True), |
| 163 |
((MASKED_TEST_SECRET2, TEST_SECRET), True), |
| 164 |
((64 * "a", _unmask_cipher_token(64 * "a")), True), |
| 165 |
# Unmasked tokens match. |
| 166 |
((TEST_SECRET, TEST_SECRET), True), |
| 167 |
((32 * "a", 32 * "a"), True), |
| 168 |
# Incorrect tokens don't match. |
| 169 |
((32 * "a", TEST_SECRET), False), |
| 170 |
((64 * "a", TEST_SECRET), False), |
| 171 |
] |
| 172 |
for (token, secret), expected in cases: |
| 173 |
with self.subTest(token=token, secret=secret): |
| 174 |
actual = _does_token_match(token, secret) |
| 175 |
self.assertIs(actual, expected) |
| 176 |
|
| 177 |
def test_does_token_match_wrong_token_length(self): |
| 178 |
with self.assertRaises(AssertionError): |
| 179 |
_does_token_match(16 * "a", TEST_SECRET) |
| 180 |
|
| 181 |
|
| 182 |
class TestingSessionStore(SessionStore): |
| 183 |
""" |
| 184 |
A version of SessionStore that stores what cookie values are passed to |
| 185 |
set_cookie() when CSRF_USE_SESSIONS=True. |
| 186 |
""" |
| 187 |
|
| 188 |
def __init__(self, *args, **kwargs): |
| 189 |
super().__init__(*args, **kwargs) |
| 190 |
# This is a list of the cookie values passed to set_cookie() over |
| 191 |
# the course of the request-response. |
| 192 |
self._cookies_set = [] |
| 193 |
|
| 194 |
def __setitem__(self, key, value): |
| 195 |
super().__setitem__(key, value) |
| 196 |
self._cookies_set.append(value) |
| 197 |
|
| 198 |
|
| 199 |
class TestingHttpRequest(HttpRequest): |
| 200 |
""" |
| 201 |
A version of HttpRequest that lets one track and change some things more |
| 202 |
easily. |
| 203 |
""" |
| 204 |
|
| 205 |
def __init__(self): |
| 206 |
super().__init__() |
| 207 |
self.session = TestingSessionStore() |
| 208 |
|
| 209 |
def is_secure(self): |
| 210 |
return getattr(self, "_is_secure_override", False) |
| 211 |
|
| 212 |
|
| 213 |
class PostErrorRequest(TestingHttpRequest): |
| 214 |
""" |
| 215 |
TestingHttpRequest that can raise errors when accessing POST data. |
| 216 |
""" |
| 217 |
|
| 218 |
post_error = None |
| 219 |
|
| 220 |
def _get_post(self): |
| 221 |
if self.post_error is not None: |
| 222 |
raise self.post_error |
| 223 |
return self._post |
| 224 |
|
| 225 |
def _set_post(self, post): |
| 226 |
self._post = post |
| 227 |
|
| 228 |
POST = property(_get_post, _set_post) |
| 229 |
|
| 230 |
|
| 231 |
class CsrfViewMiddlewareTestMixin(CsrfFunctionTestMixin): |
| 232 |
""" |
| 233 |
Shared methods and tests for session-based and cookie-based tokens. |
| 234 |
""" |
| 235 |
|
| 236 |
_csrf_id_cookie = MASKED_TEST_SECRET1 |
| 237 |
_csrf_id_token = MASKED_TEST_SECRET2 |
| 238 |
|
| 239 |
def _set_csrf_cookie(self, req, cookie): |
| 240 |
raise NotImplementedError("This method must be implemented by a subclass.") |
| 241 |
|
| 242 |
def _read_csrf_cookie(self, req, resp): |
| 243 |
""" |
| 244 |
Return the CSRF cookie as a string, or False if no cookie is present. |
| 245 |
""" |
| 246 |
raise NotImplementedError("This method must be implemented by a subclass.") |
| 247 |
|
| 248 |
def _get_cookies_set(self, req, resp): |
| 249 |
""" |
| 250 |
Return a list of the cookie values passed to set_cookie() over the |
| 251 |
course of the request-response. |
| 252 |
""" |
| 253 |
raise NotImplementedError("This method must be implemented by a subclass.") |
| 254 |
|
| 255 |
def _get_request(self, method=None, cookie=None, request_class=None): |
| 256 |
if method is None: |
| 257 |
method = "GET" |
| 258 |
if request_class is None: |
| 259 |
request_class = TestingHttpRequest |
| 260 |
req = request_class() |
| 261 |
req.method = method |
| 262 |
if cookie is not None: |
| 263 |
self._set_csrf_cookie(req, cookie) |
| 264 |
return req |
| 265 |
|
| 266 |
def _get_csrf_cookie_request( |
| 267 |
self, |
| 268 |
method=None, |
| 269 |
cookie=None, |
| 270 |
post_token=None, |
| 271 |
meta_token=None, |
| 272 |
token_header=None, |
| 273 |
request_class=None, |
| 274 |
): |
| 275 |
""" |
| 276 |
The method argument defaults to "GET". The cookie argument defaults to |
| 277 |
this class's default test cookie. The post_token and meta_token |
| 278 |
arguments are included in the request's req.POST and req.META headers, |
| 279 |
respectively, when that argument is provided and non-None. The |
| 280 |
token_header argument is the header key to use for req.META, defaults |
| 281 |
to "HTTP_X_CSRFTOKEN". |
| 282 |
""" |
| 283 |
if cookie is None: |
| 284 |
cookie = self._csrf_id_cookie |
| 285 |
if token_header is None: |
| 286 |
token_header = "HTTP_X_CSRFTOKEN" |
| 287 |
req = self._get_request( |
| 288 |
method=method, |
| 289 |
cookie=cookie, |
| 290 |
request_class=request_class, |
| 291 |
) |
| 292 |
if post_token is not None: |
| 293 |
req.POST["csrfmiddlewaretoken"] = post_token |
| 294 |
if meta_token is not None: |
| 295 |
req.META[token_header] = meta_token |
| 296 |
return req |
| 297 |
|
| 298 |
def _get_POST_csrf_cookie_request( |
| 299 |
self, |
| 300 |
cookie=None, |
| 301 |
post_token=None, |
| 302 |
meta_token=None, |
| 303 |
token_header=None, |
| 304 |
request_class=None, |
| 305 |
): |
| 306 |
return self._get_csrf_cookie_request( |
| 307 |
method="POST", |
| 308 |
cookie=cookie, |
| 309 |
post_token=post_token, |
| 310 |
meta_token=meta_token, |
| 311 |
token_header=token_header, |
| 312 |
request_class=request_class, |
| 313 |
) |
| 314 |
|
| 315 |
def _get_POST_request_with_token(self, cookie=None, request_class=None): |
| 316 |
"""The cookie argument defaults to this class's default test cookie.""" |
| 317 |
return self._get_POST_csrf_cookie_request( |
| 318 |
cookie=cookie, |
| 319 |
post_token=self._csrf_id_token, |
| 320 |
request_class=request_class, |
| 321 |
) |
| 322 |
|
| 323 |
# This method depends on _unmask_cipher_token() being correct. |
| 324 |
def _check_token_present(self, response, csrf_secret=None): |
| 325 |
if csrf_secret is None: |
| 326 |
csrf_secret = TEST_SECRET |
| 327 |
text = str(response.content, response.charset) |
| 328 |
match = re.search('name="csrfmiddlewaretoken" value="(.*?)"', text) |
| 329 |
self.assertTrue( |
| 330 |
match, |
| 331 |
f"Could not find a csrfmiddlewaretoken value in: {text}", |
| 332 |
) |
| 333 |
csrf_token = match[1] |
| 334 |
self.assertMaskedSecretCorrect(csrf_token, csrf_secret) |
| 335 |
|
| 336 |
def test_process_response_get_token_not_used(self): |
| 337 |
""" |
| 338 |
If get_token() is not called, the view middleware does not |
| 339 |
add a cookie. |
| 340 |
""" |
| 341 |
# This is important to make pages cacheable. Pages which do call |
| 342 |
# get_token(), assuming they use the token, are not cacheable because |
| 343 |
# the token is specific to the user |
| 344 |
req = self._get_request() |
| 345 |
# non_token_view_using_request_processor does not call get_token(), but |
| 346 |
# does use the csrf request processor. By using this, we are testing |
| 347 |
# that the view processor is properly lazy and doesn't call get_token() |
| 348 |
# until needed. |
| 349 |
mw = CsrfViewMiddleware(non_token_view_using_request_processor) |
| 350 |
mw.process_request(req) |
| 351 |
mw.process_view(req, non_token_view_using_request_processor, (), {}) |
| 352 |
resp = mw(req) |
| 353 |
|
| 354 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 355 |
self.assertIs(csrf_cookie, False) |
| 356 |
|
| 357 |
def _check_bad_or_missing_cookie(self, cookie, expected): |
| 358 |
"""Passing None for cookie includes no cookie.""" |
| 359 |
req = self._get_request(method="POST", cookie=cookie) |
| 360 |
mw = CsrfViewMiddleware(post_form_view) |
| 361 |
mw.process_request(req) |
| 362 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 363 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 364 |
self.assertForbiddenReason(resp, cm, expected) |
| 365 |
|
| 366 |
def test_no_csrf_cookie(self): |
| 367 |
""" |
| 368 |
If no CSRF cookies is present, the middleware rejects the incoming |
| 369 |
request. This will stop login CSRF. |
| 370 |
""" |
| 371 |
self._check_bad_or_missing_cookie(None, REASON_NO_CSRF_COOKIE) |
| 372 |
|
| 373 |
def _check_bad_or_missing_token( |
| 374 |
self, |
| 375 |
expected, |
| 376 |
post_token=None, |
| 377 |
meta_token=None, |
| 378 |
token_header=None, |
| 379 |
): |
| 380 |
req = self._get_POST_csrf_cookie_request( |
| 381 |
post_token=post_token, |
| 382 |
meta_token=meta_token, |
| 383 |
token_header=token_header, |
| 384 |
) |
| 385 |
mw = CsrfViewMiddleware(post_form_view) |
| 386 |
mw.process_request(req) |
| 387 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 388 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 389 |
self.assertEqual(resp["Content-Type"], "text/html; charset=utf-8") |
| 390 |
self.assertForbiddenReason(resp, cm, expected) |
| 391 |
|
| 392 |
def test_csrf_cookie_bad_or_missing_token(self): |
| 393 |
""" |
| 394 |
If a CSRF cookie is present but the token is missing or invalid, the |
| 395 |
middleware rejects the incoming request. |
| 396 |
""" |
| 397 |
cases = [ |
| 398 |
(None, None, REASON_CSRF_TOKEN_MISSING), |
| 399 |
(16 * "a", None, "CSRF token from POST has incorrect length."), |
| 400 |
(64 * "*", None, "CSRF token from POST has invalid characters."), |
| 401 |
(64 * "a", None, "CSRF token from POST incorrect."), |
| 402 |
( |
| 403 |
None, |
| 404 |
16 * "a", |
| 405 |
"CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.", |
| 406 |
), |
| 407 |
( |
| 408 |
None, |
| 409 |
64 * "*", |
| 410 |
"CSRF token from the 'X-Csrftoken' HTTP header has invalid characters.", |
| 411 |
), |
| 412 |
( |
| 413 |
None, |
| 414 |
64 * "a", |
| 415 |
"CSRF token from the 'X-Csrftoken' HTTP header incorrect.", |
| 416 |
), |
| 417 |
] |
| 418 |
for post_token, meta_token, expected in cases: |
| 419 |
with self.subTest(post_token=post_token, meta_token=meta_token): |
| 420 |
self._check_bad_or_missing_token( |
| 421 |
expected, |
| 422 |
post_token=post_token, |
| 423 |
meta_token=meta_token, |
| 424 |
) |
| 425 |
|
| 426 |
@override_settings(CSRF_HEADER_NAME="HTTP_X_CSRFTOKEN_CUSTOMIZED") |
| 427 |
def test_csrf_cookie_bad_token_custom_header(self): |
| 428 |
""" |
| 429 |
If a CSRF cookie is present and an invalid token is passed via a |
| 430 |
custom CSRF_HEADER_NAME, the middleware rejects the incoming request. |
| 431 |
""" |
| 432 |
expected = ( |
| 433 |
"CSRF token from the 'X-Csrftoken-Customized' HTTP header has " |
| 434 |
"incorrect length." |
| 435 |
) |
| 436 |
self._check_bad_or_missing_token( |
| 437 |
expected, |
| 438 |
meta_token=16 * "a", |
| 439 |
token_header="HTTP_X_CSRFTOKEN_CUSTOMIZED", |
| 440 |
) |
| 441 |
|
| 442 |
def test_process_request_csrf_cookie_and_token(self): |
| 443 |
""" |
| 444 |
If both a cookie and a token is present, the middleware lets it through. |
| 445 |
""" |
| 446 |
req = self._get_POST_request_with_token() |
| 447 |
mw = CsrfViewMiddleware(post_form_view) |
| 448 |
mw.process_request(req) |
| 449 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 450 |
self.assertIsNone(resp) |
| 451 |
|
| 452 |
def test_process_request_csrf_cookie_no_token_exempt_view(self): |
| 453 |
""" |
| 454 |
If a CSRF cookie is present and no token, but the csrf_exempt decorator |
| 455 |
has been applied to the view, the middleware lets it through |
| 456 |
""" |
| 457 |
req = self._get_POST_csrf_cookie_request() |
| 458 |
mw = CsrfViewMiddleware(post_form_view) |
| 459 |
mw.process_request(req) |
| 460 |
resp = mw.process_view(req, csrf_exempt(post_form_view), (), {}) |
| 461 |
self.assertIsNone(resp) |
| 462 |
|
| 463 |
def test_csrf_token_in_header(self): |
| 464 |
""" |
| 465 |
The token may be passed in a header instead of in the form. |
| 466 |
""" |
| 467 |
req = self._get_POST_csrf_cookie_request(meta_token=self._csrf_id_token) |
| 468 |
mw = CsrfViewMiddleware(post_form_view) |
| 469 |
mw.process_request(req) |
| 470 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 471 |
self.assertIsNone(resp) |
| 472 |
|
| 473 |
@override_settings(CSRF_HEADER_NAME="HTTP_X_CSRFTOKEN_CUSTOMIZED") |
| 474 |
def test_csrf_token_in_header_with_customized_name(self): |
| 475 |
""" |
| 476 |
settings.CSRF_HEADER_NAME can be used to customize the CSRF header name |
| 477 |
""" |
| 478 |
req = self._get_POST_csrf_cookie_request( |
| 479 |
meta_token=self._csrf_id_token, |
| 480 |
token_header="HTTP_X_CSRFTOKEN_CUSTOMIZED", |
| 481 |
) |
| 482 |
mw = CsrfViewMiddleware(post_form_view) |
| 483 |
mw.process_request(req) |
| 484 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 485 |
self.assertIsNone(resp) |
| 486 |
|
| 487 |
def test_put_and_delete_rejected(self): |
| 488 |
""" |
| 489 |
HTTP PUT and DELETE methods have protection |
| 490 |
""" |
| 491 |
req = self._get_request(method="PUT") |
| 492 |
mw = CsrfViewMiddleware(post_form_view) |
| 493 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 494 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 495 |
self.assertForbiddenReason(resp, cm, REASON_NO_CSRF_COOKIE) |
| 496 |
|
| 497 |
req = self._get_request(method="DELETE") |
| 498 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 499 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 500 |
self.assertForbiddenReason(resp, cm, REASON_NO_CSRF_COOKIE) |
| 501 |
|
| 502 |
def test_put_and_delete_allowed(self): |
| 503 |
""" |
| 504 |
HTTP PUT and DELETE can get through with X-CSRFToken and a cookie. |
| 505 |
""" |
| 506 |
req = self._get_csrf_cookie_request( |
| 507 |
method="PUT", meta_token=self._csrf_id_token |
| 508 |
) |
| 509 |
mw = CsrfViewMiddleware(post_form_view) |
| 510 |
mw.process_request(req) |
| 511 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 512 |
self.assertIsNone(resp) |
| 513 |
|
| 514 |
req = self._get_csrf_cookie_request( |
| 515 |
method="DELETE", meta_token=self._csrf_id_token |
| 516 |
) |
| 517 |
mw.process_request(req) |
| 518 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 519 |
self.assertIsNone(resp) |
| 520 |
|
| 521 |
def test_rotate_token_triggers_second_reset(self): |
| 522 |
""" |
| 523 |
If rotate_token() is called after the token is reset in |
| 524 |
CsrfViewMiddleware's process_response() and before another call to |
| 525 |
the same process_response(), the cookie is reset a second time. |
| 526 |
""" |
| 527 |
req = self._get_POST_request_with_token() |
| 528 |
resp = sandwiched_rotate_token_view(req) |
| 529 |
self.assertContains(resp, "OK") |
| 530 |
actual_secret = self._read_csrf_cookie(req, resp) |
| 531 |
# set_cookie() was called a second time with a different secret. |
| 532 |
cookies_set = self._get_cookies_set(req, resp) |
| 533 |
# Only compare the last two to exclude a spurious entry that's present |
| 534 |
# when CsrfViewMiddlewareUseSessionsTests is running. |
| 535 |
self.assertEqual(cookies_set[-2:], [TEST_SECRET, actual_secret]) |
| 536 |
self.assertNotEqual(actual_secret, TEST_SECRET) |
| 537 |
|
| 538 |
# Tests for the template tag method |
| 539 |
def test_token_node_no_csrf_cookie(self): |
| 540 |
""" |
| 541 |
CsrfTokenNode works when no CSRF cookie is set. |
| 542 |
""" |
| 543 |
req = self._get_request() |
| 544 |
resp = token_view(req) |
| 545 |
|
| 546 |
token = get_token(req) |
| 547 |
self.assertIsNotNone(token) |
| 548 |
csrf_secret = _unmask_cipher_token(token) |
| 549 |
self._check_token_present(resp, csrf_secret) |
| 550 |
|
| 551 |
def test_token_node_empty_csrf_cookie(self): |
| 552 |
""" |
| 553 |
A new token is sent if the csrf_cookie is the empty string. |
| 554 |
""" |
| 555 |
req = self._get_request(cookie="") |
| 556 |
mw = CsrfViewMiddleware(token_view) |
| 557 |
mw.process_view(req, token_view, (), {}) |
| 558 |
resp = token_view(req) |
| 559 |
|
| 560 |
token = get_token(req) |
| 561 |
self.assertIsNotNone(token) |
| 562 |
csrf_secret = _unmask_cipher_token(token) |
| 563 |
self._check_token_present(resp, csrf_secret) |
| 564 |
|
| 565 |
def test_token_node_with_csrf_cookie(self): |
| 566 |
""" |
| 567 |
CsrfTokenNode works when a CSRF cookie is set. |
| 568 |
""" |
| 569 |
req = self._get_csrf_cookie_request() |
| 570 |
mw = CsrfViewMiddleware(token_view) |
| 571 |
mw.process_request(req) |
| 572 |
mw.process_view(req, token_view, (), {}) |
| 573 |
resp = token_view(req) |
| 574 |
self._check_token_present(resp) |
| 575 |
|
| 576 |
def test_get_token_for_exempt_view(self): |
| 577 |
""" |
| 578 |
get_token still works for a view decorated with 'csrf_exempt'. |
| 579 |
""" |
| 580 |
req = self._get_csrf_cookie_request() |
| 581 |
mw = CsrfViewMiddleware(token_view) |
| 582 |
mw.process_request(req) |
| 583 |
mw.process_view(req, csrf_exempt(token_view), (), {}) |
| 584 |
resp = token_view(req) |
| 585 |
self._check_token_present(resp) |
| 586 |
|
| 587 |
def test_get_token_for_requires_csrf_token_view(self): |
| 588 |
""" |
| 589 |
get_token() works for a view decorated solely with requires_csrf_token. |
| 590 |
""" |
| 591 |
req = self._get_csrf_cookie_request() |
| 592 |
resp = requires_csrf_token(token_view)(req) |
| 593 |
self._check_token_present(resp) |
| 594 |
|
| 595 |
def test_token_node_with_new_csrf_cookie(self): |
| 596 |
""" |
| 597 |
CsrfTokenNode works when a CSRF cookie is created by |
| 598 |
the middleware (when one was not already present) |
| 599 |
""" |
| 600 |
req = self._get_request() |
| 601 |
mw = CsrfViewMiddleware(token_view) |
| 602 |
mw.process_view(req, token_view, (), {}) |
| 603 |
resp = mw(req) |
| 604 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 605 |
self._check_token_present(resp, csrf_cookie) |
| 606 |
|
| 607 |
def test_cookie_not_reset_on_accepted_request(self): |
| 608 |
""" |
| 609 |
The csrf token used in posts is changed on every request (although |
| 610 |
stays equivalent). The csrf cookie should not change on accepted |
| 611 |
requests. If it appears in the response, it should keep its value. |
| 612 |
""" |
| 613 |
req = self._get_POST_request_with_token() |
| 614 |
mw = CsrfViewMiddleware(token_view) |
| 615 |
mw.process_request(req) |
| 616 |
mw.process_view(req, token_view, (), {}) |
| 617 |
resp = mw(req) |
| 618 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 619 |
self.assertEqual( |
| 620 |
csrf_cookie, |
| 621 |
TEST_SECRET, |
| 622 |
"CSRF cookie was changed on an accepted request", |
| 623 |
) |
| 624 |
|
| 625 |
@override_settings(DEBUG=True, ALLOWED_HOSTS=["www.example.com"]) |
| 626 |
def test_https_bad_referer(self): |
| 627 |
""" |
| 628 |
A POST HTTPS request with a bad referer is rejected |
| 629 |
""" |
| 630 |
req = self._get_POST_request_with_token() |
| 631 |
req._is_secure_override = True |
| 632 |
req.META["HTTP_HOST"] = "www.example.com" |
| 633 |
req.META["HTTP_REFERER"] = "https://www.evil.org/somepage" |
| 634 |
req.META["SERVER_PORT"] = "443" |
| 635 |
mw = CsrfViewMiddleware(post_form_view) |
| 636 |
response = mw.process_view(req, post_form_view, (), {}) |
| 637 |
self.assertContains( |
| 638 |
response, |
| 639 |
"Referer checking failed - https://www.evil.org/somepage does not " |
| 640 |
"match any trusted origins.", |
| 641 |
status_code=403, |
| 642 |
) |
| 643 |
|
| 644 |
def _check_referer_rejects(self, mw, req): |
| 645 |
with self.assertRaises(RejectRequest): |
| 646 |
mw._check_referer(req) |
| 647 |
|
| 648 |
@override_settings(DEBUG=True) |
| 649 |
def test_https_no_referer(self): |
| 650 |
"""A POST HTTPS request with a missing referer is rejected.""" |
| 651 |
req = self._get_POST_request_with_token() |
| 652 |
req._is_secure_override = True |
| 653 |
mw = CsrfViewMiddleware(post_form_view) |
| 654 |
self._check_referer_rejects(mw, req) |
| 655 |
response = mw.process_view(req, post_form_view, (), {}) |
| 656 |
self.assertContains( |
| 657 |
response, |
| 658 |
"Referer checking failed - no Referer.", |
| 659 |
status_code=403, |
| 660 |
) |
| 661 |
|
| 662 |
def test_https_malformed_host(self): |
| 663 |
""" |
| 664 |
CsrfViewMiddleware generates a 403 response if it receives an HTTPS |
| 665 |
request with a bad host. |
| 666 |
""" |
| 667 |
req = self._get_request(method="POST") |
| 668 |
req._is_secure_override = True |
| 669 |
req.META["HTTP_HOST"] = "@malformed" |
| 670 |
req.META["HTTP_REFERER"] = "https://www.evil.org/somepage" |
| 671 |
req.META["SERVER_PORT"] = "443" |
| 672 |
mw = CsrfViewMiddleware(token_view) |
| 673 |
expected = ( |
| 674 |
"Referer checking failed - https://www.evil.org/somepage does not " |
| 675 |
"match any trusted origins." |
| 676 |
) |
| 677 |
with self.assertRaisesMessage(RejectRequest, expected): |
| 678 |
mw._check_referer(req) |
| 679 |
response = mw.process_view(req, token_view, (), {}) |
| 680 |
self.assertEqual(response.status_code, 403) |
| 681 |
|
| 682 |
def test_origin_malformed_host(self): |
| 683 |
req = self._get_request(method="POST") |
| 684 |
req._is_secure_override = True |
| 685 |
req.META["HTTP_HOST"] = "@malformed" |
| 686 |
req.META["HTTP_ORIGIN"] = "https://www.evil.org" |
| 687 |
mw = CsrfViewMiddleware(token_view) |
| 688 |
self._check_referer_rejects(mw, req) |
| 689 |
response = mw.process_view(req, token_view, (), {}) |
| 690 |
self.assertEqual(response.status_code, 403) |
| 691 |
|
| 692 |
@override_settings(DEBUG=True) |
| 693 |
def test_https_malformed_referer(self): |
| 694 |
""" |
| 695 |
A POST HTTPS request with a bad referer is rejected. |
| 696 |
""" |
| 697 |
malformed_referer_msg = "Referer checking failed - Referer is malformed." |
| 698 |
req = self._get_POST_request_with_token() |
| 699 |
req._is_secure_override = True |
| 700 |
req.META["HTTP_REFERER"] = "http://http://www.example.com/" |
| 701 |
mw = CsrfViewMiddleware(post_form_view) |
| 702 |
self._check_referer_rejects(mw, req) |
| 703 |
response = mw.process_view(req, post_form_view, (), {}) |
| 704 |
self.assertContains( |
| 705 |
response, |
| 706 |
"Referer checking failed - Referer is insecure while host is secure.", |
| 707 |
status_code=403, |
| 708 |
) |
| 709 |
# Empty |
| 710 |
req.META["HTTP_REFERER"] = "" |
| 711 |
self._check_referer_rejects(mw, req) |
| 712 |
response = mw.process_view(req, post_form_view, (), {}) |
| 713 |
self.assertContains(response, malformed_referer_msg, status_code=403) |
| 714 |
# Non-ASCII |
| 715 |
req.META["HTTP_REFERER"] = "ØBöIß" |
| 716 |
self._check_referer_rejects(mw, req) |
| 717 |
response = mw.process_view(req, post_form_view, (), {}) |
| 718 |
self.assertContains(response, malformed_referer_msg, status_code=403) |
| 719 |
# missing scheme |
| 720 |
# >>> urlsplit('//example.com/') |
| 721 |
# SplitResult(scheme='', netloc='example.com', path='/', query='', fragment='') |
| 722 |
req.META["HTTP_REFERER"] = "//example.com/" |
| 723 |
self._check_referer_rejects(mw, req) |
| 724 |
response = mw.process_view(req, post_form_view, (), {}) |
| 725 |
self.assertContains(response, malformed_referer_msg, status_code=403) |
| 726 |
# missing netloc |
| 727 |
# >>> urlsplit('https://') |
| 728 |
# SplitResult(scheme='https', netloc='', path='', query='', fragment='') |
| 729 |
req.META["HTTP_REFERER"] = "https://" |
| 730 |
self._check_referer_rejects(mw, req) |
| 731 |
response = mw.process_view(req, post_form_view, (), {}) |
| 732 |
self.assertContains(response, malformed_referer_msg, status_code=403) |
| 733 |
# Invalid URL |
| 734 |
# >>> urlsplit('https://[') |
| 735 |
# ValueError: Invalid IPv6 URL |
| 736 |
req.META["HTTP_REFERER"] = "https://[" |
| 737 |
self._check_referer_rejects(mw, req) |
| 738 |
response = mw.process_view(req, post_form_view, (), {}) |
| 739 |
self.assertContains(response, malformed_referer_msg, status_code=403) |
| 740 |
|
| 741 |
@override_settings(ALLOWED_HOSTS=["www.example.com"]) |
| 742 |
def test_https_good_referer(self): |
| 743 |
""" |
| 744 |
A POST HTTPS request with a good referer is accepted. |
| 745 |
""" |
| 746 |
req = self._get_POST_request_with_token() |
| 747 |
req._is_secure_override = True |
| 748 |
req.META["HTTP_HOST"] = "www.example.com" |
| 749 |
req.META["HTTP_REFERER"] = "https://www.example.com/somepage" |
| 750 |
mw = CsrfViewMiddleware(post_form_view) |
| 751 |
mw.process_request(req) |
| 752 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 753 |
self.assertIsNone(resp) |
| 754 |
|
| 755 |
@override_settings(ALLOWED_HOSTS=["www.example.com"]) |
| 756 |
def test_https_good_referer_2(self): |
| 757 |
""" |
| 758 |
A POST HTTPS request with a good referer is accepted where the referer |
| 759 |
contains no trailing slash. |
| 760 |
""" |
| 761 |
# See ticket #15617 |
| 762 |
req = self._get_POST_request_with_token() |
| 763 |
req._is_secure_override = True |
| 764 |
req.META["HTTP_HOST"] = "www.example.com" |
| 765 |
req.META["HTTP_REFERER"] = "https://www.example.com" |
| 766 |
mw = CsrfViewMiddleware(post_form_view) |
| 767 |
mw.process_request(req) |
| 768 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 769 |
self.assertIsNone(resp) |
| 770 |
|
| 771 |
def _test_https_good_referer_behind_proxy(self): |
| 772 |
req = self._get_POST_request_with_token() |
| 773 |
req._is_secure_override = True |
| 774 |
req.META.update( |
| 775 |
{ |
| 776 |
"HTTP_HOST": "10.0.0.2", |
| 777 |
"HTTP_REFERER": "https://www.example.com/somepage", |
| 778 |
"SERVER_PORT": "8080", |
| 779 |
"HTTP_X_FORWARDED_HOST": "www.example.com", |
| 780 |
"HTTP_X_FORWARDED_PORT": "443", |
| 781 |
} |
| 782 |
) |
| 783 |
mw = CsrfViewMiddleware(post_form_view) |
| 784 |
mw.process_request(req) |
| 785 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 786 |
self.assertIsNone(resp) |
| 787 |
|
| 788 |
@override_settings(CSRF_TRUSTED_ORIGINS=["https://dashboard.example.com"]) |
| 789 |
def test_https_good_referer_malformed_host(self): |
| 790 |
""" |
| 791 |
A POST HTTPS request is accepted if it receives a good referer with |
| 792 |
a bad host. |
| 793 |
""" |
| 794 |
req = self._get_POST_request_with_token() |
| 795 |
req._is_secure_override = True |
| 796 |
req.META["HTTP_HOST"] = "@malformed" |
| 797 |
req.META["HTTP_REFERER"] = "https://dashboard.example.com/somepage" |
| 798 |
mw = CsrfViewMiddleware(post_form_view) |
| 799 |
mw.process_request(req) |
| 800 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 801 |
self.assertIsNone(resp) |
| 802 |
|
| 803 |
@override_settings( |
| 804 |
ALLOWED_HOSTS=["www.example.com"], |
| 805 |
CSRF_TRUSTED_ORIGINS=["https://dashboard.example.com"], |
| 806 |
) |
| 807 |
def test_https_csrf_trusted_origin_allowed(self): |
| 808 |
""" |
| 809 |
A POST HTTPS request with a referer added to the CSRF_TRUSTED_ORIGINS |
| 810 |
setting is accepted. |
| 811 |
""" |
| 812 |
req = self._get_POST_request_with_token() |
| 813 |
req._is_secure_override = True |
| 814 |
req.META["HTTP_HOST"] = "www.example.com" |
| 815 |
req.META["HTTP_REFERER"] = "https://dashboard.example.com" |
| 816 |
mw = CsrfViewMiddleware(post_form_view) |
| 817 |
mw.process_request(req) |
| 818 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 819 |
self.assertIsNone(resp) |
| 820 |
|
| 821 |
@override_settings( |
| 822 |
ALLOWED_HOSTS=["www.example.com"], |
| 823 |
CSRF_TRUSTED_ORIGINS=["https://*.example.com"], |
| 824 |
) |
| 825 |
def test_https_csrf_wildcard_trusted_origin_allowed(self): |
| 826 |
""" |
| 827 |
A POST HTTPS request with a referer that matches a CSRF_TRUSTED_ORIGINS |
| 828 |
wildcard is accepted. |
| 829 |
""" |
| 830 |
req = self._get_POST_request_with_token() |
| 831 |
req._is_secure_override = True |
| 832 |
req.META["HTTP_HOST"] = "www.example.com" |
| 833 |
req.META["HTTP_REFERER"] = "https://dashboard.example.com" |
| 834 |
mw = CsrfViewMiddleware(post_form_view) |
| 835 |
mw.process_request(req) |
| 836 |
response = mw.process_view(req, post_form_view, (), {}) |
| 837 |
self.assertIsNone(response) |
| 838 |
|
| 839 |
def _test_https_good_referer_matches_cookie_domain(self): |
| 840 |
req = self._get_POST_request_with_token() |
| 841 |
req._is_secure_override = True |
| 842 |
req.META["HTTP_REFERER"] = "https://foo.example.com/" |
| 843 |
req.META["SERVER_PORT"] = "443" |
| 844 |
mw = CsrfViewMiddleware(post_form_view) |
| 845 |
mw.process_request(req) |
| 846 |
response = mw.process_view(req, post_form_view, (), {}) |
| 847 |
self.assertIsNone(response) |
| 848 |
|
| 849 |
def _test_https_good_referer_matches_cookie_domain_with_different_port(self): |
| 850 |
req = self._get_POST_request_with_token() |
| 851 |
req._is_secure_override = True |
| 852 |
req.META["HTTP_HOST"] = "www.example.com" |
| 853 |
req.META["HTTP_REFERER"] = "https://foo.example.com:4443/" |
| 854 |
req.META["SERVER_PORT"] = "4443" |
| 855 |
mw = CsrfViewMiddleware(post_form_view) |
| 856 |
mw.process_request(req) |
| 857 |
response = mw.process_view(req, post_form_view, (), {}) |
| 858 |
self.assertIsNone(response) |
| 859 |
|
| 860 |
def test_ensures_csrf_cookie_no_logging(self): |
| 861 |
""" |
| 862 |
ensure_csrf_cookie() doesn't log warnings (#19436). |
| 863 |
""" |
| 864 |
with self.assertNoLogs("django.security.csrf", "WARNING"): |
| 865 |
req = self._get_request() |
| 866 |
ensure_csrf_cookie_view(req) |
| 867 |
|
| 868 |
def test_reading_post_data_raises_unreadable_post_error(self): |
| 869 |
""" |
| 870 |
An UnreadablePostError raised while reading the POST data should be |
| 871 |
handled by the middleware. |
| 872 |
""" |
| 873 |
req = self._get_POST_request_with_token() |
| 874 |
mw = CsrfViewMiddleware(post_form_view) |
| 875 |
mw.process_request(req) |
| 876 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 877 |
self.assertIsNone(resp) |
| 878 |
|
| 879 |
req = self._get_POST_request_with_token(request_class=PostErrorRequest) |
| 880 |
req.post_error = UnreadablePostError("Error reading input data.") |
| 881 |
mw.process_request(req) |
| 882 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 883 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 884 |
self.assertForbiddenReason(resp, cm, REASON_CSRF_TOKEN_MISSING) |
| 885 |
|
| 886 |
def test_reading_post_data_raises_os_error(self): |
| 887 |
""" |
| 888 |
An OSError raised while reading the POST data should not be handled by |
| 889 |
the middleware. |
| 890 |
""" |
| 891 |
mw = CsrfViewMiddleware(post_form_view) |
| 892 |
req = self._get_POST_request_with_token(request_class=PostErrorRequest) |
| 893 |
req.post_error = OSError("Deleted directories/Missing permissions.") |
| 894 |
mw.process_request(req) |
| 895 |
with self.assertRaises(OSError): |
| 896 |
mw.process_view(req, post_form_view, (), {}) |
| 897 |
|
| 898 |
@override_settings(ALLOWED_HOSTS=["www.example.com"]) |
| 899 |
def test_bad_origin_bad_domain(self): |
| 900 |
"""A request with a bad origin is rejected.""" |
| 901 |
req = self._get_POST_request_with_token() |
| 902 |
req.META["HTTP_HOST"] = "www.example.com" |
| 903 |
req.META["HTTP_ORIGIN"] = "https://www.evil.org" |
| 904 |
mw = CsrfViewMiddleware(post_form_view) |
| 905 |
self._check_referer_rejects(mw, req) |
| 906 |
self.assertIs(mw._origin_verified(req), False) |
| 907 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 908 |
response = mw.process_view(req, post_form_view, (), {}) |
| 909 |
msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] |
| 910 |
self.assertForbiddenReason(response, cm, msg) |
| 911 |
|
| 912 |
@override_settings(ALLOWED_HOSTS=["www.example.com"]) |
| 913 |
def test_bad_origin_null_origin(self): |
| 914 |
"""A request with a null origin is rejected.""" |
| 915 |
req = self._get_POST_request_with_token() |
| 916 |
req.META["HTTP_HOST"] = "www.example.com" |
| 917 |
req.META["HTTP_ORIGIN"] = "null" |
| 918 |
mw = CsrfViewMiddleware(post_form_view) |
| 919 |
self._check_referer_rejects(mw, req) |
| 920 |
self.assertIs(mw._origin_verified(req), False) |
| 921 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 922 |
response = mw.process_view(req, post_form_view, (), {}) |
| 923 |
msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] |
| 924 |
self.assertForbiddenReason(response, cm, msg) |
| 925 |
|
| 926 |
@override_settings(ALLOWED_HOSTS=["www.example.com"]) |
| 927 |
def test_bad_origin_bad_protocol(self): |
| 928 |
"""A request with an origin with wrong protocol is rejected.""" |
| 929 |
req = self._get_POST_request_with_token() |
| 930 |
req._is_secure_override = True |
| 931 |
req.META["HTTP_HOST"] = "www.example.com" |
| 932 |
req.META["HTTP_ORIGIN"] = "http://example.com" |
| 933 |
mw = CsrfViewMiddleware(post_form_view) |
| 934 |
self._check_referer_rejects(mw, req) |
| 935 |
self.assertIs(mw._origin_verified(req), False) |
| 936 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 937 |
response = mw.process_view(req, post_form_view, (), {}) |
| 938 |
msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] |
| 939 |
self.assertForbiddenReason(response, cm, msg) |
| 940 |
|
| 941 |
@override_settings( |
| 942 |
ALLOWED_HOSTS=["www.example.com"], |
| 943 |
CSRF_TRUSTED_ORIGINS=[ |
| 944 |
"http://no-match.com", |
| 945 |
"https://*.example.com", |
| 946 |
"http://*.no-match.com", |
| 947 |
"http://*.no-match-2.com", |
| 948 |
], |
| 949 |
) |
| 950 |
def test_bad_origin_csrf_trusted_origin_bad_protocol(self): |
| 951 |
""" |
| 952 |
A request with an origin with the wrong protocol compared to |
| 953 |
CSRF_TRUSTED_ORIGINS is rejected. |
| 954 |
""" |
| 955 |
req = self._get_POST_request_with_token() |
| 956 |
req._is_secure_override = True |
| 957 |
req.META["HTTP_HOST"] = "www.example.com" |
| 958 |
req.META["HTTP_ORIGIN"] = "http://foo.example.com" |
| 959 |
mw = CsrfViewMiddleware(post_form_view) |
| 960 |
self._check_referer_rejects(mw, req) |
| 961 |
self.assertIs(mw._origin_verified(req), False) |
| 962 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 963 |
response = mw.process_view(req, post_form_view, (), {}) |
| 964 |
msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] |
| 965 |
self.assertForbiddenReason(response, cm, msg) |
| 966 |
self.assertEqual(mw.allowed_origins_exact, {"http://no-match.com"}) |
| 967 |
self.assertEqual( |
| 968 |
mw.allowed_origin_subdomains, |
| 969 |
{ |
| 970 |
"https": [".example.com"], |
| 971 |
"http": [".no-match.com", ".no-match-2.com"], |
| 972 |
}, |
| 973 |
) |
| 974 |
|
| 975 |
@override_settings(ALLOWED_HOSTS=["www.example.com"]) |
| 976 |
def test_bad_origin_cannot_be_parsed(self): |
| 977 |
""" |
| 978 |
A POST request with an origin that can't be parsed by urlsplit() is |
| 979 |
rejected. |
| 980 |
""" |
| 981 |
req = self._get_POST_request_with_token() |
| 982 |
req.META["HTTP_HOST"] = "www.example.com" |
| 983 |
req.META["HTTP_ORIGIN"] = "https://[" |
| 984 |
mw = CsrfViewMiddleware(post_form_view) |
| 985 |
self._check_referer_rejects(mw, req) |
| 986 |
self.assertIs(mw._origin_verified(req), False) |
| 987 |
with self.assertLogs("django.security.csrf", "WARNING") as cm: |
| 988 |
response = mw.process_view(req, post_form_view, (), {}) |
| 989 |
msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] |
| 990 |
self.assertForbiddenReason(response, cm, msg) |
| 991 |
|
| 992 |
@override_settings(ALLOWED_HOSTS=["www.example.com"]) |
| 993 |
def test_good_origin_insecure(self): |
| 994 |
"""A POST HTTP request with a good origin is accepted.""" |
| 995 |
req = self._get_POST_request_with_token() |
| 996 |
req.META["HTTP_HOST"] = "www.example.com" |
| 997 |
req.META["HTTP_ORIGIN"] = "http://www.example.com" |
| 998 |
mw = CsrfViewMiddleware(post_form_view) |
| 999 |
self.assertIs(mw._origin_verified(req), True) |
| 1000 |
response = mw.process_view(req, post_form_view, (), {}) |
| 1001 |
self.assertIsNone(response) |
| 1002 |
|
| 1003 |
@override_settings(ALLOWED_HOSTS=["www.example.com"]) |
| 1004 |
def test_good_origin_secure(self): |
| 1005 |
"""A POST HTTPS request with a good origin is accepted.""" |
| 1006 |
req = self._get_POST_request_with_token() |
| 1007 |
req._is_secure_override = True |
| 1008 |
req.META["HTTP_HOST"] = "www.example.com" |
| 1009 |
req.META["HTTP_ORIGIN"] = "https://www.example.com" |
| 1010 |
mw = CsrfViewMiddleware(post_form_view) |
| 1011 |
self.assertIs(mw._origin_verified(req), True) |
| 1012 |
response = mw.process_view(req, post_form_view, (), {}) |
| 1013 |
self.assertIsNone(response) |
| 1014 |
|
| 1015 |
@override_settings( |
| 1016 |
ALLOWED_HOSTS=["www.example.com"], |
| 1017 |
CSRF_TRUSTED_ORIGINS=["https://dashboard.example.com"], |
| 1018 |
) |
| 1019 |
def test_good_origin_csrf_trusted_origin_allowed(self): |
| 1020 |
""" |
| 1021 |
A POST request with an origin added to the CSRF_TRUSTED_ORIGINS |
| 1022 |
setting is accepted. |
| 1023 |
""" |
| 1024 |
req = self._get_POST_request_with_token() |
| 1025 |
req._is_secure_override = True |
| 1026 |
req.META["HTTP_HOST"] = "www.example.com" |
| 1027 |
req.META["HTTP_ORIGIN"] = "https://dashboard.example.com" |
| 1028 |
mw = CsrfViewMiddleware(post_form_view) |
| 1029 |
self.assertIs(mw._origin_verified(req), True) |
| 1030 |
resp = mw.process_view(req, post_form_view, (), {}) |
| 1031 |
self.assertIsNone(resp) |
| 1032 |
self.assertEqual(mw.allowed_origins_exact, {"https://dashboard.example.com"}) |
| 1033 |
self.assertEqual(mw.allowed_origin_subdomains, {}) |
| 1034 |
|
| 1035 |
@override_settings( |
| 1036 |
ALLOWED_HOSTS=["www.example.com"], |
| 1037 |
CSRF_TRUSTED_ORIGINS=["https://*.example.com"], |
| 1038 |
) |
| 1039 |
def test_good_origin_wildcard_csrf_trusted_origin_allowed(self): |
| 1040 |
""" |
| 1041 |
A POST request with an origin that matches a CSRF_TRUSTED_ORIGINS |
| 1042 |
wildcard is accepted. |
| 1043 |
""" |
| 1044 |
req = self._get_POST_request_with_token() |
| 1045 |
req._is_secure_override = True |
| 1046 |
req.META["HTTP_HOST"] = "www.example.com" |
| 1047 |
req.META["HTTP_ORIGIN"] = "https://foo.example.com" |
| 1048 |
mw = CsrfViewMiddleware(post_form_view) |
| 1049 |
self.assertIs(mw._origin_verified(req), True) |
| 1050 |
response = mw.process_view(req, post_form_view, (), {}) |
| 1051 |
self.assertIsNone(response) |
| 1052 |
self.assertEqual(mw.allowed_origins_exact, set()) |
| 1053 |
self.assertEqual(mw.allowed_origin_subdomains, {"https": [".example.com"]}) |
| 1054 |
|
| 1055 |
|
| 1056 |
class CsrfViewMiddlewareTests(CsrfViewMiddlewareTestMixin, SimpleTestCase): |
| 1057 |
def _set_csrf_cookie(self, req, cookie): |
| 1058 |
req.COOKIES[settings.CSRF_COOKIE_NAME] = cookie |
| 1059 |
|
| 1060 |
def _read_csrf_cookie(self, req, resp): |
| 1061 |
""" |
| 1062 |
Return the CSRF cookie as a string, or False if no cookie is present. |
| 1063 |
""" |
| 1064 |
if settings.CSRF_COOKIE_NAME not in resp.cookies: |
| 1065 |
return False |
| 1066 |
csrf_cookie = resp.cookies[settings.CSRF_COOKIE_NAME] |
| 1067 |
return csrf_cookie.value |
| 1068 |
|
| 1069 |
def _get_cookies_set(self, req, resp): |
| 1070 |
return resp._cookies_set |
| 1071 |
|
| 1072 |
def test_ensures_csrf_cookie_no_middleware(self): |
| 1073 |
""" |
| 1074 |
The ensure_csrf_cookie() decorator works without middleware. |
| 1075 |
""" |
| 1076 |
req = self._get_request() |
| 1077 |
resp = ensure_csrf_cookie_view(req) |
| 1078 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 1079 |
self.assertTrue(csrf_cookie) |
| 1080 |
self.assertIn("Cookie", resp.get("Vary", "")) |
| 1081 |
|
| 1082 |
def test_ensures_csrf_cookie_with_middleware(self): |
| 1083 |
""" |
| 1084 |
The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware |
| 1085 |
enabled. |
| 1086 |
""" |
| 1087 |
req = self._get_request() |
| 1088 |
mw = CsrfViewMiddleware(ensure_csrf_cookie_view) |
| 1089 |
mw.process_view(req, ensure_csrf_cookie_view, (), {}) |
| 1090 |
resp = mw(req) |
| 1091 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 1092 |
self.assertTrue(csrf_cookie) |
| 1093 |
self.assertIn("Cookie", resp.get("Vary", "")) |
| 1094 |
|
| 1095 |
def test_csrf_cookie_age(self): |
| 1096 |
""" |
| 1097 |
CSRF cookie age can be set using settings.CSRF_COOKIE_AGE. |
| 1098 |
""" |
| 1099 |
req = self._get_request() |
| 1100 |
|
| 1101 |
MAX_AGE = 123 |
| 1102 |
with self.settings( |
| 1103 |
CSRF_COOKIE_NAME="csrfcookie", |
| 1104 |
CSRF_COOKIE_DOMAIN=".example.com", |
| 1105 |
CSRF_COOKIE_AGE=MAX_AGE, |
| 1106 |
CSRF_COOKIE_PATH="/test/", |
| 1107 |
CSRF_COOKIE_SECURE=True, |
| 1108 |
CSRF_COOKIE_HTTPONLY=True, |
| 1109 |
): |
| 1110 |
# token_view calls get_token() indirectly |
| 1111 |
mw = CsrfViewMiddleware(token_view) |
| 1112 |
mw.process_view(req, token_view, (), {}) |
| 1113 |
resp = mw(req) |
| 1114 |
max_age = resp.cookies.get("csrfcookie").get("max-age") |
| 1115 |
self.assertEqual(max_age, MAX_AGE) |
| 1116 |
|
| 1117 |
def test_csrf_cookie_age_none(self): |
| 1118 |
""" |
| 1119 |
CSRF cookie age does not have max age set and therefore uses |
| 1120 |
session-based cookies. |
| 1121 |
""" |
| 1122 |
req = self._get_request() |
| 1123 |
|
| 1124 |
MAX_AGE = None |
| 1125 |
with self.settings( |
| 1126 |
CSRF_COOKIE_NAME="csrfcookie", |
| 1127 |
CSRF_COOKIE_DOMAIN=".example.com", |
| 1128 |
CSRF_COOKIE_AGE=MAX_AGE, |
| 1129 |
CSRF_COOKIE_PATH="/test/", |
| 1130 |
CSRF_COOKIE_SECURE=True, |
| 1131 |
CSRF_COOKIE_HTTPONLY=True, |
| 1132 |
): |
| 1133 |
# token_view calls get_token() indirectly |
| 1134 |
mw = CsrfViewMiddleware(token_view) |
| 1135 |
mw.process_view(req, token_view, (), {}) |
| 1136 |
resp = mw(req) |
| 1137 |
max_age = resp.cookies.get("csrfcookie").get("max-age") |
| 1138 |
self.assertEqual(max_age, "") |
| 1139 |
|
| 1140 |
def test_csrf_cookie_samesite(self): |
| 1141 |
req = self._get_request() |
| 1142 |
with self.settings( |
| 1143 |
CSRF_COOKIE_NAME="csrfcookie", CSRF_COOKIE_SAMESITE="Strict" |
| 1144 |
): |
| 1145 |
mw = CsrfViewMiddleware(token_view) |
| 1146 |
mw.process_view(req, token_view, (), {}) |
| 1147 |
resp = mw(req) |
| 1148 |
self.assertEqual(resp.cookies["csrfcookie"]["samesite"], "Strict") |
| 1149 |
|
| 1150 |
def test_bad_csrf_cookie_characters(self): |
| 1151 |
""" |
| 1152 |
If the CSRF cookie has invalid characters in a POST request, the |
| 1153 |
middleware rejects the incoming request. |
| 1154 |
""" |
| 1155 |
self._check_bad_or_missing_cookie( |
| 1156 |
64 * "*", "CSRF cookie has invalid characters." |
| 1157 |
) |
| 1158 |
|
| 1159 |
def test_bad_csrf_cookie_length(self): |
| 1160 |
""" |
| 1161 |
If the CSRF cookie has an incorrect length in a POST request, the |
| 1162 |
middleware rejects the incoming request. |
| 1163 |
""" |
| 1164 |
self._check_bad_or_missing_cookie(16 * "a", "CSRF cookie has incorrect length.") |
| 1165 |
|
| 1166 |
def test_process_view_token_too_long(self): |
| 1167 |
""" |
| 1168 |
If the token is longer than expected, it is ignored and a new token is |
| 1169 |
created. |
| 1170 |
""" |
| 1171 |
req = self._get_request(cookie="x" * 100000) |
| 1172 |
mw = CsrfViewMiddleware(token_view) |
| 1173 |
mw.process_view(req, token_view, (), {}) |
| 1174 |
resp = mw(req) |
| 1175 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 1176 |
self.assertEqual(len(csrf_cookie), CSRF_SECRET_LENGTH) |
| 1177 |
|
| 1178 |
def test_process_view_token_invalid_chars(self): |
| 1179 |
""" |
| 1180 |
If the token contains non-alphanumeric characters, it is ignored and a |
| 1181 |
new token is created. |
| 1182 |
""" |
| 1183 |
token = ("!@#" + self._csrf_id_token)[:CSRF_TOKEN_LENGTH] |
| 1184 |
req = self._get_request(cookie=token) |
| 1185 |
mw = CsrfViewMiddleware(token_view) |
| 1186 |
mw.process_view(req, token_view, (), {}) |
| 1187 |
resp = mw(req) |
| 1188 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 1189 |
self.assertEqual(len(csrf_cookie), CSRF_SECRET_LENGTH) |
| 1190 |
self.assertNotEqual(csrf_cookie, token) |
| 1191 |
|
| 1192 |
def test_masked_unmasked_combinations(self): |
| 1193 |
""" |
| 1194 |
All combinations are allowed of (1) masked and unmasked cookies, |
| 1195 |
(2) masked and unmasked tokens, and (3) tokens provided via POST and |
| 1196 |
the X-CSRFToken header. |
| 1197 |
""" |
| 1198 |
cases = [ |
| 1199 |
(TEST_SECRET, TEST_SECRET, None), |
| 1200 |
(TEST_SECRET, MASKED_TEST_SECRET2, None), |
| 1201 |
(TEST_SECRET, None, TEST_SECRET), |
| 1202 |
(TEST_SECRET, None, MASKED_TEST_SECRET2), |
| 1203 |
(MASKED_TEST_SECRET1, TEST_SECRET, None), |
| 1204 |
(MASKED_TEST_SECRET1, MASKED_TEST_SECRET2, None), |
| 1205 |
(MASKED_TEST_SECRET1, None, TEST_SECRET), |
| 1206 |
(MASKED_TEST_SECRET1, None, MASKED_TEST_SECRET2), |
| 1207 |
] |
| 1208 |
for args in cases: |
| 1209 |
with self.subTest(args=args): |
| 1210 |
cookie, post_token, meta_token = args |
| 1211 |
req = self._get_POST_csrf_cookie_request( |
| 1212 |
cookie=cookie, |
| 1213 |
post_token=post_token, |
| 1214 |
meta_token=meta_token, |
| 1215 |
) |
| 1216 |
mw = CsrfViewMiddleware(token_view) |
| 1217 |
mw.process_request(req) |
| 1218 |
resp = mw.process_view(req, token_view, (), {}) |
| 1219 |
self.assertIsNone(resp) |
| 1220 |
|
| 1221 |
def test_set_cookie_called_only_once(self): |
| 1222 |
""" |
| 1223 |
set_cookie() is called only once when the view is decorated with both |
| 1224 |
ensure_csrf_cookie and csrf_protect. |
| 1225 |
""" |
| 1226 |
req = self._get_POST_request_with_token() |
| 1227 |
resp = ensured_and_protected_view(req) |
| 1228 |
self.assertContains(resp, "OK") |
| 1229 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 1230 |
self.assertEqual(csrf_cookie, TEST_SECRET) |
| 1231 |
# set_cookie() was called only once and with the expected secret. |
| 1232 |
cookies_set = self._get_cookies_set(req, resp) |
| 1233 |
self.assertEqual(cookies_set, [TEST_SECRET]) |
| 1234 |
|
| 1235 |
def test_invalid_cookie_replaced_on_GET(self): |
| 1236 |
""" |
| 1237 |
A CSRF cookie with the wrong format is replaced during a GET request. |
| 1238 |
""" |
| 1239 |
req = self._get_request(cookie="badvalue") |
| 1240 |
resp = protected_view(req) |
| 1241 |
self.assertContains(resp, "OK") |
| 1242 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 1243 |
self.assertTrue(csrf_cookie, msg="No CSRF cookie was sent.") |
| 1244 |
self.assertEqual(len(csrf_cookie), CSRF_SECRET_LENGTH) |
| 1245 |
|
| 1246 |
def test_valid_secret_not_replaced_on_GET(self): |
| 1247 |
""" |
| 1248 |
Masked and unmasked CSRF cookies are not replaced during a GET request. |
| 1249 |
""" |
| 1250 |
cases = [ |
| 1251 |
TEST_SECRET, |
| 1252 |
MASKED_TEST_SECRET1, |
| 1253 |
] |
| 1254 |
for cookie in cases: |
| 1255 |
with self.subTest(cookie=cookie): |
| 1256 |
req = self._get_request(cookie=cookie) |
| 1257 |
resp = protected_view(req) |
| 1258 |
self.assertContains(resp, "OK") |
| 1259 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 1260 |
self.assertFalse(csrf_cookie, msg="A CSRF cookie was sent.") |
| 1261 |
|
| 1262 |
def test_masked_secret_accepted_and_replaced(self): |
| 1263 |
""" |
| 1264 |
For a view that uses the csrf_token, the csrf cookie is replaced with |
| 1265 |
the unmasked version if originally masked. |
| 1266 |
""" |
| 1267 |
req = self._get_POST_request_with_token(cookie=MASKED_TEST_SECRET1) |
| 1268 |
mw = CsrfViewMiddleware(token_view) |
| 1269 |
mw.process_request(req) |
| 1270 |
resp = mw.process_view(req, token_view, (), {}) |
| 1271 |
self.assertIsNone(resp) |
| 1272 |
resp = mw(req) |
| 1273 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 1274 |
self.assertEqual(csrf_cookie, TEST_SECRET) |
| 1275 |
self._check_token_present(resp, csrf_cookie) |
| 1276 |
|
| 1277 |
def test_bare_secret_accepted_and_not_replaced(self): |
| 1278 |
""" |
| 1279 |
The csrf cookie is left unchanged if originally not masked. |
| 1280 |
""" |
| 1281 |
req = self._get_POST_request_with_token(cookie=TEST_SECRET) |
| 1282 |
mw = CsrfViewMiddleware(token_view) |
| 1283 |
mw.process_request(req) |
| 1284 |
resp = mw.process_view(req, token_view, (), {}) |
| 1285 |
self.assertIsNone(resp) |
| 1286 |
resp = mw(req) |
| 1287 |
csrf_cookie = self._read_csrf_cookie(req, resp) |
| 1288 |
self.assertEqual(csrf_cookie, TEST_SECRET) |
| 1289 |
self._check_token_present(resp, csrf_cookie) |
| 1290 |
|
| 1291 |
@override_settings( |
| 1292 |
ALLOWED_HOSTS=["www.example.com"], |
| 1293 |
CSRF_COOKIE_DOMAIN=".example.com", |
| 1294 |
USE_X_FORWARDED_PORT=True, |
| 1295 |
) |
| 1296 |
def test_https_good_referer_behind_proxy(self): |
| 1297 |
""" |
| 1298 |
A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True. |
| 1299 |
""" |
| 1300 |
self._test_https_good_referer_behind_proxy() |
| 1301 |
|
| 1302 |
@override_settings( |
| 1303 |
ALLOWED_HOSTS=["www.example.com"], CSRF_COOKIE_DOMAIN=".example.com" |
| 1304 |
) |
| 1305 |
def test_https_good_referer_matches_cookie_domain(self): |
| 1306 |
""" |
| 1307 |
A POST HTTPS request with a good referer should be accepted from a |
| 1308 |
subdomain that's allowed by CSRF_COOKIE_DOMAIN. |
| 1309 |
""" |
| 1310 |
self._test_https_good_referer_matches_cookie_domain() |
| 1311 |
|
| 1312 |
@override_settings( |
| 1313 |
ALLOWED_HOSTS=["www.example.com"], CSRF_COOKIE_DOMAIN=".example.com" |
| 1314 |
) |
| 1315 |
def test_https_good_referer_matches_cookie_domain_with_different_port(self): |
| 1316 |
""" |
| 1317 |
A POST HTTPS request with a good referer should be accepted from a |
| 1318 |
subdomain that's allowed by CSRF_COOKIE_DOMAIN and a non-443 port. |
| 1319 |
""" |
| 1320 |
self._test_https_good_referer_matches_cookie_domain_with_different_port() |
| 1321 |
|
| 1322 |
@override_settings(CSRF_COOKIE_DOMAIN=".example.com", DEBUG=True) |
| 1323 |
def test_https_reject_insecure_referer(self): |
| 1324 |
""" |
| 1325 |
A POST HTTPS request from an insecure referer should be rejected. |
| 1326 |
""" |
| 1327 |
req = self._get_POST_request_with_token() |
| 1328 |
req._is_secure_override = True |
| 1329 |
req.META["HTTP_REFERER"] = "http://example.com/" |
| 1330 |
req.META["SERVER_PORT"] = "443" |
| 1331 |
mw = CsrfViewMiddleware(post_form_view) |
| 1332 |
self._check_referer_rejects(mw, req) |
| 1333 |
response = mw.process_view(req, post_form_view, (), {}) |
| 1334 |
self.assertContains( |
| 1335 |
response, |
| 1336 |
"Referer checking failed - Referer is insecure while host is secure.", |
| 1337 |
status_code=403, |
| 1338 |
) |
| 1339 |
|
| 1340 |
|
| 1341 |
@override_settings(CSRF_USE_SESSIONS=True, CSRF_COOKIE_DOMAIN=None) |
| 1342 |
class CsrfViewMiddlewareUseSessionsTests(CsrfViewMiddlewareTestMixin, SimpleTestCase): |
| 1343 |
""" |
| 1344 |
CSRF tests with CSRF_USE_SESSIONS=True. |
| 1345 |
""" |
| 1346 |
|
| 1347 |
def _set_csrf_cookie(self, req, cookie): |
| 1348 |
req.session[CSRF_SESSION_KEY] = cookie |
| 1349 |
|
| 1350 |
def _read_csrf_cookie(self, req, resp=None): |
| 1351 |
""" |
| 1352 |
Return the CSRF cookie as a string, or False if no cookie is present. |
| 1353 |
""" |
| 1354 |
if CSRF_SESSION_KEY not in req.session: |
| 1355 |
return False |
| 1356 |
return req.session[CSRF_SESSION_KEY] |
| 1357 |
|
| 1358 |
def _get_cookies_set(self, req, resp): |
| 1359 |
return req.session._cookies_set |
| 1360 |
|
| 1361 |
def test_no_session_on_request(self): |
| 1362 |
msg = ( |
| 1363 |
"CSRF_USE_SESSIONS is enabled, but request.session is not set. " |
| 1364 |
"SessionMiddleware must appear before CsrfViewMiddleware in MIDDLEWARE." |
| 1365 |
) |
| 1366 |
with self.assertRaisesMessage(ImproperlyConfigured, msg): |
| 1367 |
mw = CsrfViewMiddleware(lambda req: HttpResponse()) |
| 1368 |
mw.process_request(HttpRequest()) |
| 1369 |
|
| 1370 |
def test_masked_unmasked_combinations(self): |
| 1371 |
""" |
| 1372 |
Masked and unmasked tokens are allowed both as POST and as the |
| 1373 |
X-CSRFToken header. |
| 1374 |
""" |
| 1375 |
cases = [ |
| 1376 |
# Bare secrets are not allowed when CSRF_USE_SESSIONS=True. |
| 1377 |
(MASKED_TEST_SECRET1, TEST_SECRET, None), |
| 1378 |
(MASKED_TEST_SECRET1, MASKED_TEST_SECRET2, None), |
| 1379 |
(MASKED_TEST_SECRET1, None, TEST_SECRET), |
| 1380 |
(MASKED_TEST_SECRET1, None, MASKED_TEST_SECRET2), |
| 1381 |
] |
| 1382 |
for args in cases: |
| 1383 |
with self.subTest(args=args): |
| 1384 |
cookie, post_token, meta_token = args |
| 1385 |
req = self._get_POST_csrf_cookie_request( |
| 1386 |
cookie=cookie, |
| 1387 |
post_token=post_token, |
| 1388 |
meta_token=meta_token, |
| 1389 |
) |
| 1390 |
mw = CsrfViewMiddleware(token_view) |
| 1391 |
mw.process_request(req) |
| 1392 |
resp = mw.process_view(req, token_view, (), {}) |
| 1393 |
self.assertIsNone(resp) |
| 1394 |
|
| 1395 |
def test_process_response_get_token_used(self): |
| 1396 |
"""The ensure_csrf_cookie() decorator works without middleware.""" |
| 1397 |
req = self._get_request() |
| 1398 |
ensure_csrf_cookie_view(req) |
| 1399 |
csrf_cookie = self._read_csrf_cookie(req) |
| 1400 |
self.assertTrue(csrf_cookie) |
| 1401 |
|
| 1402 |
def test_session_modify(self): |
| 1403 |
"""The session isn't saved if the CSRF cookie is unchanged.""" |
| 1404 |
req = self._get_request() |
| 1405 |
mw = CsrfViewMiddleware(ensure_csrf_cookie_view) |
| 1406 |
mw.process_view(req, ensure_csrf_cookie_view, (), {}) |
| 1407 |
mw(req) |
| 1408 |
csrf_cookie = self._read_csrf_cookie(req) |
| 1409 |
self.assertTrue(csrf_cookie) |
| 1410 |
req.session.modified = False |
| 1411 |
mw.process_view(req, ensure_csrf_cookie_view, (), {}) |
| 1412 |
mw(req) |
| 1413 |
self.assertFalse(req.session.modified) |
| 1414 |
|
| 1415 |
def test_ensures_csrf_cookie_with_middleware(self): |
| 1416 |
""" |
| 1417 |
The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware |
| 1418 |
enabled. |
| 1419 |
""" |
| 1420 |
req = self._get_request() |
| 1421 |
mw = CsrfViewMiddleware(ensure_csrf_cookie_view) |
| 1422 |
mw.process_view(req, ensure_csrf_cookie_view, (), {}) |
| 1423 |
mw(req) |
| 1424 |
csrf_cookie = self._read_csrf_cookie(req) |
| 1425 |
self.assertTrue(csrf_cookie) |
| 1426 |
|
| 1427 |
@override_settings( |
| 1428 |
ALLOWED_HOSTS=["www.example.com"], |
| 1429 |
SESSION_COOKIE_DOMAIN=".example.com", |
| 1430 |
USE_X_FORWARDED_PORT=True, |
| 1431 |
DEBUG=True, |
| 1432 |
) |
| 1433 |
def test_https_good_referer_behind_proxy(self): |
| 1434 |
""" |
| 1435 |
A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True. |
| 1436 |
""" |
| 1437 |
self._test_https_good_referer_behind_proxy() |
| 1438 |
|
| 1439 |
@override_settings( |
| 1440 |
ALLOWED_HOSTS=["www.example.com"], SESSION_COOKIE_DOMAIN=".example.com" |
| 1441 |
) |
| 1442 |
def test_https_good_referer_matches_cookie_domain(self): |
| 1443 |
""" |
| 1444 |
A POST HTTPS request with a good referer should be accepted from a |
| 1445 |
subdomain that's allowed by SESSION_COOKIE_DOMAIN. |
| 1446 |
""" |
| 1447 |
self._test_https_good_referer_matches_cookie_domain() |
| 1448 |
|
| 1449 |
@override_settings( |
| 1450 |
ALLOWED_HOSTS=["www.example.com"], SESSION_COOKIE_DOMAIN=".example.com" |
| 1451 |
) |
| 1452 |
def test_https_good_referer_matches_cookie_domain_with_different_port(self): |
| 1453 |
""" |
| 1454 |
A POST HTTPS request with a good referer should be accepted from a |
| 1455 |
subdomain that's allowed by SESSION_COOKIE_DOMAIN and a non-443 port. |
| 1456 |
""" |
| 1457 |
self._test_https_good_referer_matches_cookie_domain_with_different_port() |
| 1458 |
|
| 1459 |
@override_settings(SESSION_COOKIE_DOMAIN=".example.com", DEBUG=True) |
| 1460 |
def test_https_reject_insecure_referer(self): |
| 1461 |
""" |
| 1462 |
A POST HTTPS request from an insecure referer should be rejected. |
| 1463 |
""" |
| 1464 |
req = self._get_POST_request_with_token() |
| 1465 |
req._is_secure_override = True |
| 1466 |
req.META["HTTP_REFERER"] = "http://example.com/" |
| 1467 |
req.META["SERVER_PORT"] = "443" |
| 1468 |
mw = CsrfViewMiddleware(post_form_view) |
| 1469 |
response = mw.process_view(req, post_form_view, (), {}) |
| 1470 |
self.assertContains( |
| 1471 |
response, |
| 1472 |
"Referer checking failed - Referer is insecure while host is secure.", |
| 1473 |
status_code=403, |
| 1474 |
) |
| 1475 |
|
| 1476 |
|
| 1477 |
@override_settings(ROOT_URLCONF="csrf_tests.csrf_token_error_handler_urls", DEBUG=False) |
| 1478 |
class CsrfInErrorHandlingViewsTests(CsrfFunctionTestMixin, SimpleTestCase): |
| 1479 |
def test_csrf_token_on_404_stays_constant(self): |
| 1480 |
response = self.client.get("/does not exist/") |
| 1481 |
# The error handler returns status code 599. |
| 1482 |
self.assertEqual(response.status_code, 599) |
| 1483 |
response.charset = "ascii" |
| 1484 |
token1 = response.text |
| 1485 |
response = self.client.get("/does not exist/") |
| 1486 |
self.assertEqual(response.status_code, 599) |
| 1487 |
response.charset = "ascii" |
| 1488 |
token2 = response.text |
| 1489 |
secret2 = _unmask_cipher_token(token2) |
| 1490 |
self.assertMaskedSecretCorrect(token1, secret2) |