Debian Codegraph @

tests/test_changeable.py

raw
1 """
2 test_changeable
3 ~~~~~~~~~~~~~~~
4
5 Changeable tests
6
7 :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9 """
10
11 import base64
12
13 import pytest
14 from flask import Flask
15 import markupsafe
16
17 from flask_security import PasswordUtil, UserMixin, password_changed, user_authenticated
18 from flask_security.forms import _default_field_labels
19 from flask_security.utils import localize_callback
20 from tests.test_utils import (
21 authenticate,
22 check_location,
23 get_form_input_value,
24 get_session,
25 hash_password,
26 init_app_with_options,
27 json_authenticate,
28 logout,
29 )
30
31 pytestmark = pytest.mark.changeable()
32
33
34 def test_changeable_flag(app, clients, get_message, outbox):
35 recorded = []
36
37 @password_changed.connect_via(app)
38 def on_password_changed(app, user):
39 assert isinstance(app, Flask)
40 assert isinstance(user, UserMixin)
41 recorded.append(user)
42
43 authenticate(clients)
44
45 # Test change view
46 response = clients.get("/change", follow_redirects=True)
47 assert b"Change Password" in response.data
48
49 # Test wrong original password
50 response = clients.post(
51 "/change",
52 data={
53 "password": "notpassword",
54 "new_password": "newpassword",
55 "new_password_confirm": "newpassword",
56 },
57 follow_redirects=True,
58 )
59 assert get_message("INVALID_PASSWORD") in response.data
60
61 # Test mismatch
62 response = clients.post(
63 "/change",
64 data={
65 "password": "password",
66 "new_password": "newpassword",
67 "new_password_confirm": "notnewpassword",
68 },
69 follow_redirects=True,
70 )
71 assert get_message("RETYPE_PASSWORD_MISMATCH") in response.data
72
73 # Test missing password
74 response = clients.post(
75 "/change",
76 data={"password": " ", "new_password": "", "new_password_confirm": ""},
77 follow_redirects=True,
78 )
79 assert get_message("PASSWORD_NOT_PROVIDED") in response.data
80 response = clients.post(
81 "/change",
82 data={
83 "password": " ",
84 "new_password": "awesome password",
85 "new_password_confirm": "awesome password",
86 },
87 follow_redirects=True,
88 )
89 assert get_message("PASSWORD_NOT_PROVIDED") in response.data
90
91 # Test bad password
92 response = clients.post(
93 "/change",
94 data={"password": "password", "new_password": "a", "new_password_confirm": "a"},
95 follow_redirects=True,
96 )
97 assert get_message("PASSWORD_INVALID_LENGTH", length=8) in response.data
98
99 # Test same as previous
100 response = clients.post(
101 "/change",
102 data={
103 "password": "password",
104 "new_password": "password",
105 "new_password_confirm": "password",
106 },
107 follow_redirects=True,
108 )
109 assert get_message("PASSWORD_IS_THE_SAME") in response.data
110
111 # Test successful submit sends email notification
112 response = clients.post(
113 "/change",
114 data={
115 "password": "password",
116 "new_password": "new strong password",
117 "new_password_confirm": "new strong password",
118 },
119 follow_redirects=True,
120 )
121
122 assert get_message("PASSWORD_CHANGE") in response.data
123 assert b"Home Page" in response.data
124 assert len(recorded) == 1
125 assert len(outbox) == 1
126 assert "Your password has been changed" in outbox[0].body
127
128 # Test leading and trailing whitespace not stripped
129 response = clients.post(
130 "/change",
131 data={
132 "password": "new strong password",
133 "new_password": " new strong password ",
134 "new_password_confirm": " new strong password ",
135 },
136 follow_redirects=True,
137 )
138 assert get_message("PASSWORD_CHANGE") in response.data
139
140 # Test JSON
141 data = (
142 '{"password": " new strong password ", '
143 '"new_password": "new stronger password2", '
144 '"new_password_confirm": "new stronger password2"}'
145 )
146 response = clients.post(
147 "/change", data=data, headers={"Content-Type": "application/json"}
148 )
149 assert response.status_code == 200
150 assert response.headers["Content-Type"] == "application/json"
151
152 # Test JSON errors
153 data = '{"password": "newpassword"}'
154 response = clients.post(
155 "/change", data=data, headers={"Content-Type": "application/json"}
156 )
157 assert response.status_code == 400
158 assert response.json["response"]["field_errors"]["new_password"] == [
159 "Password not provided"
160 ]
161
162
163 def test_change_invalidates_session(app, client):
164 # Make sure that if we change our password - prior sessions are invalidated.
165
166 # changing password effectively re-logs in user - verify the signal
167 auths = []
168
169 @user_authenticated.connect_via(app)
170 def authned(myapp, user, **extra_args):
171 auths.append((user.email, extra_args["authn_via"]))
172
173 # No remember cookie since that also be reset and auto-login.
174 data = dict(email="[email protected]", password="password", remember="")
175 response = client.post("/login", data=data)
176 sess = get_session(response)
177 cur_user_id = sess.get("_user_id", sess.get("user_id"))
178
179 response = client.post(
180 "/change",
181 data={
182 "password": "password",
183 "new_password": "new strong password",
184 "new_password_confirm": "new strong password",
185 },
186 follow_redirects=True,
187 )
188 # First auth was the initial login above - second should be from /change
189 assert auths[1][0] == "[email protected]"
190 assert "change" in auths[1][1]
191
192 # Should have received a new session cookie - so should still be logged in
193 response = client.get("/profile", follow_redirects=True)
194 assert b"Profile Page" in response.data
195
196 # Now use old session - shouldn't work.
197 with client.session_transaction() as oldsess:
198 oldsess["_user_id"] = cur_user_id
199 oldsess["user_id"] = cur_user_id
200
201 # try to access protected endpoint - shouldn't work
202 response = client.get("/profile")
203 assert response.status_code in [302, 303]
204 assert response.location == "/login?next=/profile"
205
206
207 def test_change_updates_remember(app, client):
208 # Test that on change password - remember cookie updated
209 authenticate(client, remember=True)
210
211 response = client.post(
212 "/change",
213 data={
214 "password": "password",
215 "new_password": "new strong password",
216 "new_password_confirm": "new strong password",
217 },
218 follow_redirects=True,
219 )
220
221 # Should have received a new session cookie - so should still be logged in
222 response = client.get("/profile", follow_redirects=True)
223 assert b"Profile Page" in response.data
224
225 assert client.get_cookie("remember_token")
226 client.delete_cookie("session")
227 response = client.get("/profile", follow_redirects=True)
228 assert b"Profile Page" in response.data
229
230
231 def test_change_invalidates_auth_token(app, client):
232 # if change password, by default that should invalidate auth tokens
233 response = json_authenticate(client)
234 token = response.json["response"]["user"]["authentication_token"]
235 headers = {"Authentication-Token": token}
236 # make sure can access restricted page
237 response = client.get("/token", headers=headers)
238 assert b"Token Authentication" in response.data
239
240 response = client.post(
241 "/change",
242 data={
243 "password": "password",
244 "new_password": "new strong password",
245 "new_password_confirm": "new strong password",
246 },
247 follow_redirects=True,
248 )
249 assert response.status_code == 200
250
251 # authtoken should now be invalid
252 response = client.get("/token", headers=headers)
253 assert response.status_code in [302, 303]
254 assert response.location == "/login?next=/token"
255
256
257 def test_auth_uniquifier(app):
258 pytest.importorskip("sqlalchemy")
259 pytest.importorskip("flask_sqlalchemy")
260 # If add fs_token_uniquifier to user model - change password shouldn't invalidate
261 # auth tokens.
262 from sqlalchemy import Column, String
263 from flask_sqlalchemy import SQLAlchemy
264 from flask_security.models import fsqla_v2 as fsqla
265 from flask_security import Security, SQLAlchemyUserDatastore
266
267 app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
268 db = SQLAlchemy(app)
269
270 fsqla.FsModels.set_db_info(db)
271
272 class Role(db.Model, fsqla.FsRoleMixin):
273 pass
274
275 class User(db.Model, fsqla.FsUserMixin):
276 fs_token_uniquifier = Column(String(64), unique=True, nullable=False)
277
278 with app.app_context():
279 db.create_all()
280
281 ds = SQLAlchemyUserDatastore(db, User, Role)
282 app.security = Security(app, datastore=ds)
283
284 with app.app_context():
285 ds.create_user(
286 email="[email protected]",
287 password=hash_password("password"),
288 )
289 ds.commit()
290
291 tcl = app.test_client()
292
293 # standard login with auth token
294 response = json_authenticate(tcl)
295 token = response.json["response"]["user"]["authentication_token"]
296 headers = {"Authentication-Token": token}
297 # make sure can access restricted page
298 response = tcl.get("/token", headers=headers)
299 assert b"Token Authentication" in response.data
300
301 # change password
302 response = tcl.post(
303 "/change",
304 data={
305 "password": "password",
306 "new_password": "new strong password",
307 "new_password_confirm": "new strong password",
308 },
309 follow_redirects=True,
310 )
311 assert response.status_code == 200
312
313 # authtoken should still be valid
314 response = tcl.get("/token", headers=headers)
315 assert response.status_code == 200
316
317 with app.app_context():
318 db.engine.dispose()
319
320
321 @pytest.mark.babel(babel_default_locale="cic_US", test_xlations=True)
322 def test_xlation(app, client, get_message_local, outbox):
323 # Test form and email translation
324 authenticate(client)
325
326 response = client.get("/change", follow_redirects=True)
327 with app.test_request_context():
328 # Check header
329 header = localize_callback("Change Password")
330 assert "OKAY!" in header # ensures actual translation
331 assert f"<h1>{header}</h1>".encode() in response.data
332 submit = localize_callback(_default_field_labels["change_password"])
333 assert "OKAY!" in submit
334 assert f'value="{submit}"'.encode() in response.data
335
336 response = client.post(
337 "/change",
338 data={
339 "password": "password",
340 "new_password": "new strong password",
341 "new_password_confirm": "new strong password",
342 },
343 follow_redirects=True,
344 )
345
346 with app.test_request_context():
347 flash = get_message_local("PASSWORD_CHANGE")
348 assert "OKAY!" in flash
349 assert f'<li class="success">{flash}</li>'.encode() in response.data
350 assert b"Home Page" in response.data
351 assert len(outbox) == 1
352 subj = localize_callback(
353 app.config["SECURITY_EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE"]
354 )
355 assert "OKAY!" in subj
356 assert subj in outbox[0].subject
357
358 body = localize_callback("Your password has been changed.")
359 assert "OKAY!" in body
360 assert str(markupsafe.escape(body)) in outbox[0].alts["html"]
361 assert body in outbox[0].body
362
363
364 @pytest.mark.settings(change_url="/custom_change")
365 def test_custom_change_url(client):
366 authenticate(client)
367 response = client.get("/custom_change")
368 assert response.status_code == 200
369
370
371 @pytest.mark.settings(change_password_template="custom_security/change_password.html")
372 def test_custom_change_template(client):
373 authenticate(client)
374 response = client.get("/change")
375 assert b"CUSTOM CHANGE PASSWORD" in response.data
376
377
378 @pytest.mark.settings(send_password_change_email=False)
379 def test_disable_change_emails(app, client, outbox):
380 client.post(
381 "/change",
382 data={
383 "password": "password",
384 "new_password": "newpassword",
385 "new_password_confirm": "newpassword",
386 },
387 follow_redirects=True,
388 )
389 assert len(outbox) == 0
390
391
392 @pytest.mark.settings(post_change_view="/profile")
393 def test_custom_post_change_view(client):
394 authenticate(client)
395 response = client.post(
396 "/change",
397 data={
398 "password": "password",
399 "new_password": "new strong password",
400 "new_password_confirm": "new strong password",
401 },
402 follow_redirects=True,
403 )
404
405 assert b"Profile Page" in response.data
406
407
408 def test_token_change(app, client_nc):
409 # Verify can change password using token auth only
410 login_response = json_authenticate(client_nc)
411 token = login_response.json["response"]["user"]["authentication_token"]
412
413 data = dict(
414 password="password",
415 new_password="new strong password",
416 new_password_confirm="new strong password",
417 )
418 response = client_nc.post(
419 "/change?include_auth_token=1",
420 json=data,
421 headers={"Content-Type": "application/json", "Authentication-Token": token},
422 )
423 assert response.status_code == 200
424 assert "authentication_token" in response.json["response"]["user"]
425
426
427 @pytest.mark.settings(api_enabled_methods=["basic"])
428 def test_basic_change(app, client_nc, get_message):
429 # Verify can change password using basic auth
430 data = dict(
431 password="password",
432 new_password="new strong password",
433 new_password_confirm="new strong password",
434 )
435 response = client_nc.post("/change", data=data)
436 assert get_message("UNAUTHENTICATED") in response.data
437 assert "WWW-Authenticate" in response.headers
438
439 response = client_nc.post(
440 "/change",
441 data=data,
442 headers={
443 "Authorization": "Basic %s"
444 % base64.b64encode(b"[email protected]:password").decode("utf-8")
445 },
446 follow_redirects=True,
447 )
448 assert response.status_code == 200
449 # No session so no flashing
450 assert b"Home Page" in response.data
451
452
453 def __test_easy_password(client):
454 authenticate(client)
455
456 data = (
457 '{"password": "password", '
458 '"new_password": "mattmatt2", '
459 '"new_password_confirm": "mattmatt2"}'
460 )
461 response = client.post(
462 "/change", data=data, headers={"Content-Type": "application/json"}
463 )
464 assert response.headers["Content-Type"] == "application/json"
465 return response
466
467
468 @pytest.mark.settings(password_complexity_checker="zxcvbn")
469 def test_easy_password(app, client):
470 response = __test_easy_password(client)
471 assert response.status_code == 400
472 # Response from zxcvbn
473 assert "Repeats like" in response.json["response"]["errors"][0]
474
475
476 @pytest.mark.settings(password_complexity_checker="zxcvbn", zxcvbn_minimum_score=0)
477 def test_easy_password_ok(app, client):
478 response = __test_easy_password(client)
479 assert response.status_code == 200
480
481
482 def test_my_validator(app, sqlalchemy_datastore):
483 class MyPwUtil(PasswordUtil):
484 def validate(self, password, is_register, **kwargs):
485 user = kwargs["user"]
486 # This is setup in createusers for matt.
487 assert user.security_number == 123456
488 return ["Are you crazy?"], password
489
490 init_app_with_options(
491 app, sqlalchemy_datastore, **{"security_args": {"password_util_cls": MyPwUtil}}
492 )
493 tcl = app.test_client()
494
495 authenticate(tcl)
496
497 data = (
498 '{"password": "password", '
499 '"new_password": "mattmatt2", '
500 '"new_password_confirm": "mattmatt2"}'
501 )
502 response = tcl.post(
503 "/change", data=data, headers={"Content-Type": "application/json"}
504 )
505 assert response.headers["Content-Type"] == "application/json"
506 assert response.status_code == 400
507 assert "Are you crazy" in response.json["response"]["errors"][0]
508
509
510 @pytest.mark.settings(password_length_min=12)
511 def test_override_length(app, client, get_message):
512 authenticate(client)
513 response = client.post(
514 "/change",
515 data={
516 "password": "password",
517 "new_password": "01234567890",
518 "new_password_confirm": "01234567890",
519 },
520 follow_redirects=True,
521 )
522 assert get_message("PASSWORD_INVALID_LENGTH", length=12) in response.data
523
524
525 def test_unicode_length(app, client, get_message):
526 # From NIST and OWASP - each unicode code point should count as a character.
527 authenticate(client)
528
529 # Emoji's are 4 bytes in utf-8
530 data = dict(
531 password="password",
532 new_password="\N{CYCLONE}\N{SUNRISE}\N{FOGGY}"
533 "\N{VOLCANO}\N{CRESCENT MOON}\N{MILKY WAY}"
534 "\N{FOG}\N{THERMOMETER}\N{ROSE}",
535 new_password_confirm="\N{CYCLONE}\N{SUNRISE}\N{FOGGY}"
536 "\N{VOLCANO}\N{CRESCENT MOON}\N{MILKY WAY}"
537 "\N{FOG}\N{THERMOMETER}\N{ROSE}",
538 )
539 response = client.post(
540 "/change", json=data, headers={"Content-Type": "application/json"}
541 )
542 assert response.headers["Content-Type"] == "application/json"
543 assert response.status_code == 200
544
545
546 def test_unicode_invalid_length(app, client, get_message):
547 # From NIST and OWASP - each unicode code point should count as a character.
548 authenticate(client)
549
550 # Emoji's are 4 bytes in utf-8
551 data = dict(
552 password="password",
553 new_password="\N{CYCLONE}\N{CYCLONE}\N{FOGGY}\N{FOGGY}",
554 new_password_confirm="\N{CYCLONE}\N{CYCLONE}\N{FOGGY}\N{FOGGY}",
555 )
556 response = client.post(
557 "/change", json=data, headers={"Content-Type": "application/json"}
558 )
559 assert response.headers["Content-Type"] == "application/json"
560 assert response.status_code == 400
561 assert get_message("PASSWORD_INVALID_LENGTH", length=8) in response.data
562
563
564 def test_pwd_normalize(app, client):
565 """Verify that can log in with both original and normalized pwd"""
566 authenticate(client)
567
568 data = dict(
569 password="password",
570 new_password="new strong password\N{ROMAN NUMERAL ONE}",
571 new_password_confirm="new strong password\N{ROMAN NUMERAL ONE}",
572 )
573 response = client.post(
574 "/change",
575 json=data,
576 headers={"Content-Type": "application/json"},
577 )
578 assert response.status_code == 200
579 logout(client)
580
581 # use original typed-in pwd
582 response = client.post(
583 "/login",
584 json=dict(
585 email="[email protected]", password="new strong password\N{ROMAN NUMERAL ONE}"
586 ),
587 headers={"Content-Type": "application/json"},
588 )
589 assert response.status_code == 200
590 logout(client)
591
592 # try with normalized password
593 response = client.post(
594 "/login",
595 json=dict(
596 email="[email protected]",
597 password="new strong password\N{LATIN CAPITAL LETTER I}",
598 ),
599 headers={"Content-Type": "application/json"},
600 )
601 assert response.status_code == 200
602
603 # Verify can change password using original password
604 data = dict(
605 password="new strong password\N{ROMAN NUMERAL ONE}",
606 new_password="new strong password\N{ROMAN NUMERAL TWO}",
607 new_password_confirm="new strong password\N{ROMAN NUMERAL TWO}",
608 )
609 response = client.post(
610 "/change",
611 json=data,
612 headers={"Content-Type": "application/json"},
613 )
614 assert response.status_code == 200
615
616
617 @pytest.mark.settings(password_normalize_form=None)
618 def test_pwd_no_normalize(app, client):
619 """Verify that can log in with original but not normalized if have
620 disabled normalization
621 """
622 authenticate(client)
623
624 data = dict(
625 password="password",
626 new_password="new strong password\N{ROMAN NUMERAL ONE}",
627 new_password_confirm="new strong password\N{ROMAN NUMERAL ONE}",
628 )
629 response = client.post(
630 "/change",
631 json=data,
632 headers={"Content-Type": "application/json"},
633 )
634 assert response.status_code == 200
635 logout(client)
636
637 # try with normalized password - should fail
638 response = client.post(
639 "/login",
640 json=dict(
641 email="[email protected]",
642 password="new strong password\N{LATIN CAPITAL LETTER I}",
643 ),
644 headers={"Content-Type": "application/json"},
645 )
646 assert response.status_code == 400
647
648 # use original typed-in pwd
649 response = client.post(
650 "/login",
651 json=dict(
652 email="[email protected]", password="new strong password\N{ROMAN NUMERAL ONE}"
653 ),
654 headers={"Content-Type": "application/json"},
655 )
656 assert response.status_code == 200
657
658 # Verify can change password using original password
659 data = dict(
660 password="new strong password\N{ROMAN NUMERAL ONE}",
661 new_password="new strong password\N{ROMAN NUMERAL TWO}",
662 new_password_confirm="new strong password\N{ROMAN NUMERAL TWO}",
663 )
664 response = client.post(
665 "/change",
666 json=data,
667 headers={"Content-Type": "application/json"},
668 )
669 assert response.status_code == 200
670
671
672 @pytest.mark.csrf(ignore_unauth=True)
673 @pytest.mark.settings(post_change_view="/post_change_view")
674 def test_csrf(app, client):
675 # enable CSRF, make sure template shows CSRF errors.
676 authenticate(client)
677 data = {
678 "password": "password",
679 "new_password": "new strong password",
680 "new_password_confirm": "new strong password",
681 }
682 response = client.post("/change", data=data)
683 assert b"The CSRF token is missing" in response.data
684 # Note that we get a CSRF token EVEN for errors - this seems odd
685 # but can't find anything that says its a security issue
686 csrf_token = get_form_input_value(response, "csrf_token")
687
688 data["csrf_token"] = csrf_token
689 response = client.post("/change", data=data)
690 assert check_location(app, response.location, "/post_change_view")
691
692
693 @pytest.mark.csrf(ignore_unauth=True, csrfprotect=True)
694 def test_csrf_json(app, client):
695 # This tests the handle_csrf code path - especially the JSON code path
696 # that should return a JSON response!
697 authenticate(client)
698 data = {
699 "password": "password",
700 "new_password": "new strong password",
701 "new_password_confirm": "new strong password",
702 }
703 response = client.post("/change", json=data)
704 assert response.status_code == 400
705 assert response.json["response"]["errors"][0] == "The CSRF token is missing."
706
707 # check form path also
708 response = client.post("/change", data=data)
709 assert response.status_code == 400
710 assert b"The CSRF token is missing." in response.data
711
712 response = client.get("/change", content_type="application/json")
713 csrf_token = response.json["response"]["csrf_token"]
714 response = client.post("/change", json=data, headers={"X-CSRF-Token": csrf_token})
715 assert response.status_code == 200