Debian Codegraph @

tests/test_csrf.py

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