| 1 |
""" |
| 2 |
test_csrf |
| 3 |
~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
CSRF tests |
| 6 |
|
| 7 |
:copyright: (c) 2019-2024 by J. Christopher Wagner (jwag). |
| 8 |
:license: MIT, see LICENSE for more details. |
| 9 |
""" |
| 10 |
|
| 11 |
from contextlib import contextmanager |
| 12 |
from datetime import date, timedelta |
| 13 |
|
| 14 |
import flask_wtf.csrf |
| 15 |
|
| 16 |
import pytest |
| 17 |
from flask_wtf import CSRFProtect |
| 18 |
from freezegun import freeze_time |
| 19 |
from flask import render_template_string |
| 20 |
|
| 21 |
from flask_security import Security, auth_required |
| 22 |
from tests.test_utils import get_form_input_value, get_session, logout |
| 23 |
|
| 24 |
REAL_VALIDATE_CSRF = None |
| 25 |
|
| 26 |
|
| 27 |
@contextmanager |
| 28 |
def mp_validate_csrf(): |
| 29 |
"""Make sure we are really calling CSRF validation and getting correct answer""" |
| 30 |
orig_validate_csrf = flask_wtf.csrf.validate_csrf |
| 31 |
try: |
| 32 |
mp = MpValidateCsrf(orig_validate_csrf) |
| 33 |
flask_wtf.csrf.validate_csrf = mp.mp_validate_csrf |
| 34 |
yield mp |
| 35 |
finally: |
| 36 |
flask_wtf.csrf.validate_csrf = orig_validate_csrf |
| 37 |
|
| 38 |
|
| 39 |
class MpValidateCsrf: |
| 40 |
success = 0 |
| 41 |
failure = 0 |
| 42 |
|
| 43 |
def __init__(self, real_validate_csrf): |
| 44 |
MpValidateCsrf.success = 0 |
| 45 |
MpValidateCsrf.failure = 0 |
| 46 |
global REAL_VALIDATE_CSRF |
| 47 |
REAL_VALIDATE_CSRF = real_validate_csrf |
| 48 |
|
| 49 |
@staticmethod |
| 50 |
def mp_validate_csrf(data, secret_key=None, time_limit=None, token_key=None): |
| 51 |
try: |
| 52 |
REAL_VALIDATE_CSRF(data, secret_key, time_limit, token_key) |
| 53 |
MpValidateCsrf.success += 1 |
| 54 |
except Exception: |
| 55 |
MpValidateCsrf.failure += 1 |
| 56 |
raise |
| 57 |
|
| 58 |
|
| 59 |
def _get_csrf_token(client): |
| 60 |
response = client.get( |
| 61 |
"/login", data={}, headers={"Content-Type": "application/json"} |
| 62 |
) |
| 63 |
return response.json["response"]["csrf_token"] |
| 64 |
|
| 65 |
|
| 66 |
def json_login( |
| 67 |
client, |
| 68 |
email="[email protected]", |
| 69 |
password="password", |
| 70 |
endpoint=None, |
| 71 |
use_header=False, |
| 72 |
remember=None, |
| 73 |
): |
| 74 |
# Return tuple (auth_token, csrf_token) |
| 75 |
csrf_token = _get_csrf_token(client) |
| 76 |
data = dict(email=email, password=password, remember=remember) |
| 77 |
|
| 78 |
if use_header: |
| 79 |
headers = {"X-CSRF-Token": csrf_token} |
| 80 |
else: |
| 81 |
headers = {} |
| 82 |
data["csrf_token"] = csrf_token |
| 83 |
|
| 84 |
response = client.post( |
| 85 |
endpoint or "/login?include_auth_token", |
| 86 |
content_type="application/json", |
| 87 |
json=data, |
| 88 |
headers=headers, |
| 89 |
) |
| 90 |
assert response.status_code == 200 |
| 91 |
rd = response.json["response"] |
| 92 |
return rd["user"]["authentication_token"], rd["csrf_token"] |
| 93 |
|
| 94 |
|
| 95 |
def json_logout(client): |
| 96 |
response = client.post("logout", content_type="application/json", data={}) |
| 97 |
assert response.status_code == 200 |
| 98 |
assert response.json["meta"]["code"] == 200 |
| 99 |
return response |
| 100 |
|
| 101 |
|
| 102 |
@pytest.mark.csrf() |
| 103 |
def test_login_csrf(app, client): |
| 104 |
# This shouldn't log in - but return login form with csrf token. |
| 105 |
data = dict(email="[email protected]", password="password", remember="y") |
| 106 |
response = client.post("/login", data=data) |
| 107 |
assert response.status_code == 200 |
| 108 |
assert b"The CSRF token is missing." in response.data |
| 109 |
|
| 110 |
data["csrf_token"] = get_form_input_value(response, "csrf_token") |
| 111 |
response = client.post("/login", data=data, follow_redirects=True) |
| 112 |
assert response.status_code == 200 |
| 113 |
assert b"Welcome matt" in response.data |
| 114 |
|
| 115 |
response = logout(client, follow_redirects=True) |
| 116 |
assert response.status_code == 200 |
| 117 |
assert b"Log in" in response.data |
| 118 |
|
| 119 |
|
| 120 |
def test_login_csrf_double(app, client): |
| 121 |
# Test if POST login while already logged in - just redirects to POST_LOGIN |
| 122 |
app.config["WTF_CSRF_ENABLED"] = True |
| 123 |
|
| 124 |
# This shouldn't log in - but return login form with csrf token. |
| 125 |
data = dict(email="[email protected]", password="password", remember="y") |
| 126 |
response = client.post("/login", data=data) |
| 127 |
assert response.status_code == 200 |
| 128 |
assert b"csrf_token" in response.data |
| 129 |
|
| 130 |
data["csrf_token"] = _get_csrf_token(client) |
| 131 |
response = client.post("/login", data=data, follow_redirects=True) |
| 132 |
assert response.status_code == 200 |
| 133 |
assert b"Welcome matt" in response.data |
| 134 |
|
| 135 |
data["csrf_token"] = _get_csrf_token(client) |
| 136 |
# Note - should redirect to POST_LOGIN with current user ignoring form data. |
| 137 |
data["email"] = "[email protected]" |
| 138 |
response = client.post("/login", data=data, follow_redirects=True) |
| 139 |
assert response.status_code == 200 |
| 140 |
assert b"Welcome matt" in response.data |
| 141 |
|
| 142 |
|
| 143 |
@pytest.mark.csrf() |
| 144 |
def test_login_csrf_json(app, client): |
| 145 |
with mp_validate_csrf() as mp: |
| 146 |
auth_token, csrf_token = json_login(client) |
| 147 |
assert auth_token |
| 148 |
assert csrf_token |
| 149 |
# Should be just one call to validate - since CSRFProtect not enabled. |
| 150 |
assert mp.success == 1 and mp.failure == 0 |
| 151 |
|
| 152 |
response = json_logout(client) |
| 153 |
session = get_session(response) |
| 154 |
assert "csrf_token" not in session |
| 155 |
|
| 156 |
|
| 157 |
@pytest.mark.csrf(csrfprotect=True) |
| 158 |
def test_login_csrf_json_header(app, client): |
| 159 |
with mp_validate_csrf() as mp: |
| 160 |
auth_token, csrf_token = json_login(client, use_header=True) |
| 161 |
assert auth_token |
| 162 |
assert csrf_token |
| 163 |
assert mp.success == 1 and mp.failure == 0 |
| 164 |
json_logout(client) |
| 165 |
|
| 166 |
|
| 167 |
@pytest.mark.settings(csrf_ignore_unauth_endpoints=True) |
| 168 |
def test_login_csrf_unauth_ok(app, client): |
| 169 |
app.config["WTF_CSRF_ENABLED"] = True |
| 170 |
|
| 171 |
with mp_validate_csrf() as mp: |
| 172 |
# This should log in. |
| 173 |
data = dict(email="[email protected]", password="password", remember="y") |
| 174 |
response = client.post("/login", data=data, follow_redirects=True) |
| 175 |
assert response.status_code == 200 |
| 176 |
assert b"Welcome matt" in response.data |
| 177 |
assert mp.success == 0 and mp.failure == 0 |
| 178 |
logout(client) |
| 179 |
|
| 180 |
|
| 181 |
@pytest.mark.settings(csrf_ignore_unauth_endpoints=True) |
| 182 |
def test_login_csrf_unauth_double(app, client, get_message): |
| 183 |
# Test double login w/o CSRF returns unauth required error message. |
| 184 |
app.config["WTF_CSRF_ENABLED"] = True |
| 185 |
|
| 186 |
# This should log in. |
| 187 |
data = dict(email="[email protected]", password="password", remember="y") |
| 188 |
response = client.post("/login", data=data, follow_redirects=True) |
| 189 |
assert response.status_code == 200 |
| 190 |
assert b"Welcome matt" in response.data |
| 191 |
|
| 192 |
# login in again - should work |
| 193 |
response = client.post("/login", content_type="application/json", json=data) |
| 194 |
assert response.status_code == 400 |
| 195 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 196 |
"ANONYMOUS_USER_REQUIRED" |
| 197 |
) |
| 198 |
|
| 199 |
|
| 200 |
@pytest.mark.csrf() |
| 201 |
@pytest.mark.recoverable() |
| 202 |
def test_reset(app, client): |
| 203 |
"""Test that form-based CSRF works for /reset""" |
| 204 |
response = client.get("/reset", content_type="application/json") |
| 205 |
csrf_token = response.json["response"]["csrf_token"] |
| 206 |
|
| 207 |
with mp_validate_csrf() as mp: |
| 208 |
data = dict(email="[email protected]") |
| 209 |
# should fail - no CSRF token - should get a JSON response |
| 210 |
response = client.post("/reset", content_type="application/json", json=data) |
| 211 |
assert response.status_code == 400 |
| 212 |
assert response.json["response"]["errors"][0] == "The CSRF token is missing." |
| 213 |
# test template also has error - since using just Flask-WTF form based CSRF - |
| 214 |
# should be an error on the csrf_token field. |
| 215 |
response = client.post("/reset", data=data) |
| 216 |
assert b'class="fs-error-msg">The CSRF token is missing' in response.data |
| 217 |
|
| 218 |
# test sending csrf_token works - JSON |
| 219 |
data["csrf_token"] = csrf_token |
| 220 |
response = client.post("/reset", content_type="application/json", json=data) |
| 221 |
assert response.status_code == 200 |
| 222 |
|
| 223 |
# test sending csrf_token works - forms |
| 224 |
response = client.post("/reset", data=data) |
| 225 |
assert b"Send password reset instructions" in response.data |
| 226 |
assert mp.success == 2 and mp.failure == 2 |
| 227 |
|
| 228 |
|
| 229 |
@pytest.mark.recoverable() |
| 230 |
@pytest.mark.csrf(csrfprotect=True) |
| 231 |
def test_cp_reset(app, client): |
| 232 |
"""Test that header based CSRF works for /reset when |
| 233 |
using WTF_CSRF_CHECK_DEFAULT=False. |
| 234 |
""" |
| 235 |
with mp_validate_csrf() as mp: |
| 236 |
data = dict(email="[email protected]") |
| 237 |
# should fail - no CSRF token |
| 238 |
response = client.post("/reset", content_type="application/json", json=data) |
| 239 |
assert response.status_code == 400 |
| 240 |
assert response.json["response"]["errors"][0] == "The CSRF token is missing." |
| 241 |
|
| 242 |
csrf_token = _get_csrf_token(client) |
| 243 |
response = client.post( |
| 244 |
"/reset", |
| 245 |
content_type="application/json", |
| 246 |
json=data, |
| 247 |
headers={"X-CSRF-Token": csrf_token}, |
| 248 |
) |
| 249 |
assert response.status_code == 200 |
| 250 |
assert mp.success == 1 and mp.failure == 1 |
| 251 |
|
| 252 |
|
| 253 |
@pytest.mark.changeable() |
| 254 |
@pytest.mark.csrf(csrfprotect=True) |
| 255 |
@pytest.mark.settings(csrf_header="X-XSRF-Token") |
| 256 |
def test_cp_with_token(app, client): |
| 257 |
# Make sure can use returned CSRF-Token in Header. |
| 258 |
# Since the csrf token isn't in the form - must enable app-wide CSRF |
| 259 |
# using CSRFProtect() - as the above mark does. |
| 260 |
# Using X-XSRF-Token as header tests that we properly |
| 261 |
# add that as a known header to WTFforms. |
| 262 |
auth_token, csrf_token = json_login(client, use_header=True) |
| 263 |
|
| 264 |
# make sure returned csrf_token works in header. |
| 265 |
data = dict( |
| 266 |
password="password", |
| 267 |
new_password="battery staple", |
| 268 |
new_password_confirm="battery staple", |
| 269 |
) |
| 270 |
|
| 271 |
with mp_validate_csrf() as mp: |
| 272 |
response = client.post( |
| 273 |
"/change", |
| 274 |
content_type="application/json", |
| 275 |
json=data, |
| 276 |
headers={"X-XSRF-Token": csrf_token}, |
| 277 |
) |
| 278 |
assert response.status_code == 200 |
| 279 |
assert mp.success == 1 and mp.failure == 0 |
| 280 |
json_logout(client) |
| 281 |
|
| 282 |
|
| 283 |
def test_cp_login_json_no_session(app, sqlalchemy_datastore): |
| 284 |
# Test with global CSRFProtect on and not sending cookie - nothing works. |
| 285 |
app.config["WTF_CSRF_ENABLED"] = True |
| 286 |
CSRFProtect(app) |
| 287 |
app.security = Security(app=app, datastore=sqlalchemy_datastore) |
| 288 |
|
| 289 |
client_nc = app.test_client(use_cookies=False) |
| 290 |
|
| 291 |
# This shouldn't log in - and will return 400 |
| 292 |
with mp_validate_csrf() as mp: |
| 293 |
data = dict(email="[email protected]", password="password", remember="y") |
| 294 |
response = client_nc.post( |
| 295 |
"/login", |
| 296 |
content_type="application/json", |
| 297 |
json=data, |
| 298 |
headers={"Accept": "application/json"}, |
| 299 |
) |
| 300 |
assert response.status_code == 400 |
| 301 |
|
| 302 |
# This still wont work since we don't send a session cookie |
| 303 |
response = client_nc.post( |
| 304 |
"/login", |
| 305 |
content_type="application/json", |
| 306 |
json=data, |
| 307 |
headers={"X-CSRF-Token": _get_csrf_token(client_nc)}, |
| 308 |
) |
| 309 |
assert response.status_code == 400 |
| 310 |
|
| 311 |
# Although failed - CSRF should have been called |
| 312 |
assert mp.failure == 2 |
| 313 |
|
| 314 |
|
| 315 |
@pytest.mark.settings(CSRF_PROTECT_MECHANISMS=["basic", "session"]) |
| 316 |
def test_cp_config(app, sqlalchemy_datastore): |
| 317 |
# Test improper config (must have WTF_CSRF_CHECK_DEFAULT false if setting |
| 318 |
# CSRF_PROTECT_MECHANISMS |
| 319 |
from flask_security import Security |
| 320 |
|
| 321 |
app.config["WTF_CSRF_ENABLED"] = True |
| 322 |
CSRFProtect(app) |
| 323 |
|
| 324 |
# The check is done on first request. |
| 325 |
with pytest.raises(ValueError) as ev: |
| 326 |
Security(app=app, datastore=sqlalchemy_datastore) |
| 327 |
assert "must be set to False" in str(ev.value) |
| 328 |
|
| 329 |
|
| 330 |
@pytest.mark.settings(CSRF_PROTECT_MECHANISMS=["basic", "session"]) |
| 331 |
def test_cp_config2(app, sqlalchemy_datastore): |
| 332 |
# Test improper config (must have CSRFProtect configured if setting |
| 333 |
# CSRF_PROTECT_MECHANISMS |
| 334 |
from flask_security import Security |
| 335 |
|
| 336 |
app.config["WTF_CSRF_ENABLED"] = True |
| 337 |
|
| 338 |
with pytest.raises(ValueError) as ev: |
| 339 |
Security(app=app, datastore=sqlalchemy_datastore) |
| 340 |
assert "CsrfProtect not part of application" in str(ev.value) |
| 341 |
|
| 342 |
|
| 343 |
@pytest.mark.changeable() |
| 344 |
@pytest.mark.csrf(csrfprotect=True) |
| 345 |
@pytest.mark.settings(CSRF_PROTECT_MECHANISMS=["basic", "session"]) |
| 346 |
def test_different_mechanisms(app, client): |
| 347 |
# Verify that using token doesn't require CSRF, but sessions do |
| 348 |
with mp_validate_csrf() as mp: |
| 349 |
auth_token, csrf_token = json_login(client, use_header=True) |
| 350 |
|
| 351 |
# session based change password should fail |
| 352 |
data = dict( |
| 353 |
password="password", |
| 354 |
new_password="battery staple", |
| 355 |
new_password_confirm="battery staple", |
| 356 |
) |
| 357 |
|
| 358 |
response = client.post( |
| 359 |
"/change", json=data, headers={"Content-Type": "application/json"} |
| 360 |
) |
| 361 |
assert response.status_code == 400 |
| 362 |
assert b"The CSRF token is missing" in response.data |
| 363 |
|
| 364 |
# token based should work |
| 365 |
response = client.post( |
| 366 |
"/change", |
| 367 |
json=data, |
| 368 |
headers={ |
| 369 |
"Content-Type": "application/json", |
| 370 |
"Authentication-Token": auth_token, |
| 371 |
}, |
| 372 |
) |
| 373 |
assert response.status_code == 200 |
| 374 |
assert mp.success == 1 and mp.failure == 1 |
| 375 |
|
| 376 |
|
| 377 |
@pytest.mark.changeable() |
| 378 |
@pytest.mark.settings( |
| 379 |
CSRF_PROTECT_MECHANISMS=["basic", "session"], csrf_ignore_unauth_endpoints=True |
| 380 |
) |
| 381 |
def test_different_mechanisms_nc(app, client_nc): |
| 382 |
# Verify that using token and no session cookie works |
| 383 |
# Note that we had to disable unauth_endpoints since you can't log in |
| 384 |
# w/ CSRF if you don't send in the session cookie. |
| 385 |
app.config["WTF_CSRF_ENABLED"] = True |
| 386 |
app.config["WTF_CSRF_CHECK_DEFAULT"] = False |
| 387 |
CSRFProtect(app) |
| 388 |
|
| 389 |
with mp_validate_csrf() as mp: |
| 390 |
auth_token, csrf_token = json_login(client_nc) |
| 391 |
|
| 392 |
# token based should work |
| 393 |
data = dict( |
| 394 |
password="password", |
| 395 |
new_password="battery staple", |
| 396 |
new_password_confirm="battery staple", |
| 397 |
) |
| 398 |
response = client_nc.post( |
| 399 |
"/change", |
| 400 |
json=data, |
| 401 |
headers={ |
| 402 |
"Content-Type": "application/json", |
| 403 |
"Authentication-Token": auth_token, |
| 404 |
}, |
| 405 |
) |
| 406 |
assert response.status_code == 200 |
| 407 |
assert mp.success == 0 and mp.failure == 0 |
| 408 |
|
| 409 |
|
| 410 |
@pytest.mark.changeable() |
| 411 |
@pytest.mark.csrf(csrfprotect=True) |
| 412 |
@pytest.mark.settings(csrf_protect_mechanisms=[]) |
| 413 |
def test_cp_with_token_empty_mechanisms(app, client): |
| 414 |
# If no mechanisms - shouldn't do any CSRF |
| 415 |
auth_token, csrf_token = json_login(client, use_header=True) |
| 416 |
|
| 417 |
# make sure returned csrf_token works in header. |
| 418 |
data = dict( |
| 419 |
password="password", |
| 420 |
new_password="battery staple", |
| 421 |
new_password_confirm="battery staple", |
| 422 |
) |
| 423 |
|
| 424 |
response = client.post( |
| 425 |
"/change", |
| 426 |
content_type="application/json", |
| 427 |
json=data, |
| 428 |
headers={ |
| 429 |
"Content-Type": "application/json", |
| 430 |
"Authentication-Token": auth_token, |
| 431 |
}, |
| 432 |
) |
| 433 |
assert response.status_code == 200 |
| 434 |
|
| 435 |
|
| 436 |
@pytest.mark.csrf(csrfprotect=True) |
| 437 |
@pytest.mark.settings(csrf_ignore_unauth_endpoints=True, CSRF_COOKIE_NAME="XSRF-Token") |
| 438 |
def test_csrf_cookie(app, client): |
| 439 |
json_login(client) |
| 440 |
assert client.get_cookie("XSRF-Token") |
| 441 |
|
| 442 |
# Make sure cleared on logout |
| 443 |
response = client.post("/logout", content_type="application/json") |
| 444 |
assert response.status_code == 200 |
| 445 |
assert not client.get_cookie("XSRF-Token") |
| 446 |
|
| 447 |
|
| 448 |
@pytest.mark.csrf(csrfprotect=True) |
| 449 |
@pytest.mark.settings(CSRF_COOKIE={"key": "XSRF-Token"}) |
| 450 |
@pytest.mark.changeable() |
| 451 |
def test_cp_with_token_cookie(app, client): |
| 452 |
# Make sure can use returned CSRF-Token cookie in Header when changing password |
| 453 |
json_login(client, use_header=True) |
| 454 |
|
| 455 |
# make sure returned csrf_token works in header. |
| 456 |
data = dict( |
| 457 |
password="password", |
| 458 |
new_password="battery staple", |
| 459 |
new_password_confirm="battery staple", |
| 460 |
) |
| 461 |
csrf_token = client.get_cookie("XSRF-Token") |
| 462 |
with mp_validate_csrf() as mp: |
| 463 |
response = client.post( |
| 464 |
"/change", |
| 465 |
content_type="application/json", |
| 466 |
json=data, |
| 467 |
headers={"X-XSRF-Token": csrf_token.value}, |
| 468 |
) |
| 469 |
assert response.status_code == 200 |
| 470 |
assert mp.success == 1 and mp.failure == 0 |
| 471 |
json_logout(client) |
| 472 |
assert not client.get_cookie("XSRF-Token") |
| 473 |
|
| 474 |
|
| 475 |
@pytest.mark.csrf(csrfprotect=True) |
| 476 |
@pytest.mark.app_settings(wtf_csrf_time_limit=1) |
| 477 |
@pytest.mark.settings(CSRF_COOKIE_NAME="XSRF-Token", csrf_ignore_unauth_endpoints=True) |
| 478 |
@pytest.mark.changeable() |
| 479 |
def test_cp_with_token_cookie_expire(app, client): |
| 480 |
# Make sure that we get a new Csrf-Token cookie if expired. |
| 481 |
# Note that we need relatively new-ish date since session cookies also expire. |
| 482 |
with freeze_time(date.today() + timedelta(days=-1)): |
| 483 |
json_login(client, use_header=True) |
| 484 |
|
| 485 |
# time unfrozen so should be expired |
| 486 |
data = dict( |
| 487 |
password="password", |
| 488 |
new_password="battery staple", |
| 489 |
new_password_confirm="battery staple", |
| 490 |
) |
| 491 |
csrf_token = client.get_cookie("XSRF-Token") |
| 492 |
with mp_validate_csrf() as mp: |
| 493 |
response = client.post( |
| 494 |
"/change", |
| 495 |
content_type="application/json", |
| 496 |
json=data, |
| 497 |
headers={"X-XSRF-Token": csrf_token.value}, |
| 498 |
) |
| 499 |
assert response.status_code == 400 |
| 500 |
assert b"expired" in response.data |
| 501 |
|
| 502 |
# Should have gotten a new CSRF cookie value |
| 503 |
new_csrf_token = client.get_cookie("XSRF-Token") |
| 504 |
assert csrf_token.value != new_csrf_token.value |
| 505 |
# 2 failures since the utils:csrf_cookie_handler will check |
| 506 |
assert mp.success == 0 and mp.failure == 2 |
| 507 |
json_logout(client) |
| 508 |
assert not client.get_cookie("XSRF-Token") |
| 509 |
|
| 510 |
|
| 511 |
@pytest.mark.csrf(csrfprotect=True) |
| 512 |
@pytest.mark.settings( |
| 513 |
CSRF_COOKIE_NAME="XSRF-Token", CSRF_COOKIE_REFRESH_EACH_REQUEST=True |
| 514 |
) |
| 515 |
@pytest.mark.changeable() |
| 516 |
def test_cp_with_token_cookie_refresh(app, client): |
| 517 |
# Test CSRF_COOKIE_REFRESH_EACH_REQUEST |
| 518 |
json_login(client, use_header=True) |
| 519 |
|
| 520 |
# make sure returned csrf_token works in header. |
| 521 |
data = dict( |
| 522 |
password="password", |
| 523 |
new_password="battery staple", |
| 524 |
new_password_confirm="battery staple", |
| 525 |
) |
| 526 |
|
| 527 |
csrf_cookie = client.get_cookie("XSRF-Token") |
| 528 |
with mp_validate_csrf() as mp: |
| 529 |
# Delete cookie - we should always get a new one |
| 530 |
client.delete_cookie("XSRF-Token") |
| 531 |
response = client.post( |
| 532 |
"/change", |
| 533 |
content_type="application/json", |
| 534 |
json=data, |
| 535 |
headers={"X-XSRF-Token": csrf_cookie.value}, |
| 536 |
) |
| 537 |
assert response.status_code == 200 |
| 538 |
assert client.get_cookie("XSRF-Token") |
| 539 |
assert mp.success == 1 and mp.failure == 0 |
| 540 |
|
| 541 |
# delete cookie again, do a 'GET' - the REFRESH_COOKIE_ON_EACH_REQUEST should |
| 542 |
# send us a new one |
| 543 |
client.delete_cookie("XSRF-Token") |
| 544 |
response = client.get("/change") |
| 545 |
assert response.status_code == 200 |
| 546 |
assert client.get_cookie("XSRF-Token") |
| 547 |
|
| 548 |
json_logout(client) |
| 549 |
assert not client.get_cookie("XSRF-Token") |
| 550 |
|
| 551 |
|
| 552 |
@pytest.mark.csrf(csrfprotect=True) |
| 553 |
@pytest.mark.settings(CSRF_COOKIE_NAME="XSRF-Token") |
| 554 |
@pytest.mark.changeable() |
| 555 |
def test_remember_login_csrf_cookie(app, client): |
| 556 |
# Test csrf cookie upon resuming a remember session |
| 557 |
# Login with remember_token generation |
| 558 |
json_login(client, use_header=True, remember=True) |
| 559 |
|
| 560 |
client.delete_cookie("XSRF-Token") |
| 561 |
client.delete_cookie("session") |
| 562 |
|
| 563 |
# Do a simple get request with the remember_token cookie present |
| 564 |
assert client.get_cookie("remember_token") |
| 565 |
response = client.get("/profile") |
| 566 |
assert response.status_code == 200 |
| 567 |
assert client.get_cookie("session") |
| 568 |
assert client.get_cookie("XSRF-Token") |
| 569 |
# Logout and check that everything cleans up nicely |
| 570 |
json_logout(client) |
| 571 |
assert not client.get_cookie("remember_token") |
| 572 |
assert not client.get_cookie("session") |
| 573 |
assert not client.get_cookie("XSRF-Token") |
| 574 |
|
| 575 |
|
| 576 |
@pytest.mark.csrf(csrfprotect=True) |
| 577 |
@pytest.mark.registerable() |
| 578 |
@pytest.mark.settings(csrf_header="X-CSRF-Token", password_confirm_required=False) |
| 579 |
def test_json_register_csrf_with_ignore_unauth_set_to_false(app, client): |
| 580 |
""" |
| 581 |
Test that you are able to register a user when using the JSON api |
| 582 |
and the CSRF_IGNORE_UNAUTH_ENDPOINTS is set to False. |
| 583 |
""" |
| 584 |
|
| 585 |
csrf_token = client.get("/login", headers={"Accept": "application/json"}).json[ |
| 586 |
"response" |
| 587 |
]["csrf_token"] |
| 588 |
|
| 589 |
email = "[email protected]" |
| 590 |
data = {"email": email, "password": "password"} |
| 591 |
|
| 592 |
response = client.post( |
| 593 |
"/register", json=data, headers={"Content-Type": "application/json"} |
| 594 |
) |
| 595 |
assert response.status_code == 400 |
| 596 |
assert response.json["response"]["errors"][0] == "The CSRF token is missing." |
| 597 |
|
| 598 |
response = client.post( |
| 599 |
"/register", |
| 600 |
json=data, |
| 601 |
headers={"Content-Type": "application/json", "X-CSRF-Token": csrf_token}, |
| 602 |
) |
| 603 |
assert response.status_code == 200 |
| 604 |
assert response.json["response"]["user"]["email"] == email |
| 605 |
|
| 606 |
|
| 607 |
@pytest.mark.csrf(csrfprotect=True) |
| 608 |
@pytest.mark.settings( |
| 609 |
csrf_protect_mechanisms=["session"], csrf_ignore_unauth_endpoints=True |
| 610 |
) |
| 611 |
def test_myform(app, client): |
| 612 |
# Create app form - and make sure protect_mechanisms properly skips CSRF |
| 613 |
# For this test - we don't configure CSRFProtect - just use form CSRF |
| 614 |
from flask_wtf import FlaskForm |
| 615 |
from wtforms import StringField |
| 616 |
|
| 617 |
class custom_form(FlaskForm): |
| 618 |
name = StringField("Name") |
| 619 |
|
| 620 |
@app.route("/custom", methods=["GET", "POST"]) |
| 621 |
@auth_required() |
| 622 |
def custom(): |
| 623 |
form = custom_form() |
| 624 |
if form.validate_on_submit(): |
| 625 |
return render_template_string(f"Nice POST {form.name.data}") |
| 626 |
return render_template_string( |
| 627 |
f"Hi {form.name.data}, anything wrong? {form.errors}" |
| 628 |
) |
| 629 |
|
| 630 |
auth_token, csrf_token = json_login(client, use_header=True) |
| 631 |
|
| 632 |
# using session - POST should fail - no CSRF |
| 633 |
response = client.post("/custom", json={"name": "first POST"}) |
| 634 |
assert response.status_code == 400 |
| 635 |
assert response.json["response"]["errors"][0] == "The CSRF token is missing." |
| 636 |
|
| 637 |
# use CSRF token - should work |
| 638 |
response = client.post( |
| 639 |
"/custom", json={"name": "second POST"}, headers={"X-XSRF-Token": csrf_token} |
| 640 |
) |
| 641 |
assert response.status_code == 200 |
| 642 |
|
| 643 |
# try with form input |
| 644 |
response = client.post( |
| 645 |
"/custom", data={"name": "form POST", "csrf_token": csrf_token} |
| 646 |
) |
| 647 |
assert response.data == b"Nice POST form POST" |
| 648 |
|
| 649 |
# now try authenticating via token - shouldn't need CSRF token |
| 650 |
client_nc = app.test_client(use_cookies=False) |
| 651 |
response = client_nc.post( |
| 652 |
"/custom", |
| 653 |
json={"name": "authtoken POST"}, |
| 654 |
headers={ |
| 655 |
"Content-Type": "application/json", |
| 656 |
"Authentication-Token": auth_token, |
| 657 |
}, |
| 658 |
) |
| 659 |
assert b"CSRF" not in response.data |
| 660 |
|
| 661 |
|
| 662 |
@pytest.mark.csrf(csrfprotect=True) |
| 663 |
def test_csrf_json_protect(app, client): |
| 664 |
# test sending CSRF token in json body for an unauth endpoint (/login) |
| 665 |
# In older code the @unauth_csrf() decorator would 'fall through' - if the |
| 666 |
# decorator CSRF checked failed it would fall through to the form CSRF check. |
| 667 |
# The decorator CSRF check returns a 400 JSON response. |
| 668 |
csrf_token = _get_csrf_token(client) |
| 669 |
response = client.post( |
| 670 |
"/login", |
| 671 |
json=dict(email="[email protected]", password="password", csrf_token=csrf_token), |
| 672 |
) |
| 673 |
assert response.status_code == 400 |
| 674 |
assert response.json["response"]["errors"][0] == "The CSRF token is missing." |