Debian Codegraph @

tests/test_unified_signin.py

raw
1 """
2 test_unified_signin
3 ~~~~~~~~~~~~~~~~~~~
4
5 Unified signin tests
6
7 :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9
10 """
11
12 import base64
13 from contextlib import contextmanager
14 from datetime import timedelta
15 import markupsafe
16 from passlib.totp import TOTP
17 import re
18 from urllib.parse import parse_qsl, urlsplit
19
20 import pytest
21 from flask import Flask
22 from tests.conftest import v2_param
23 from tests.test_utils import (
24 SmsBadSender,
25 SmsTestSender,
26 FakeSerializer,
27 authenticate,
28 capture_flashes,
29 capture_reset_password_requests,
30 check_location,
31 check_signals,
32 get_form_action,
33 get_session,
34 is_authenticated,
35 logout,
36 reset_fresh,
37 reset_fresh_auth_token,
38 setup_tf_sms,
39 get_form_input,
40 )
41 from tests.test_webauthn import HackWebauthnUtil, reg_2_keys
42
43 from flask_security import (
44 SmsSenderFactory,
45 UserMixin,
46 uia_email_mapper,
47 uia_phone_mapper,
48 us_profile_changed,
49 us_security_token_sent,
50 user_authenticated,
51 )
52
53 from flask_security.utils import get_identity_attributes
54
55 pytestmark = pytest.mark.unified_signin()
56
57 SmsSenderFactory.senders["test"] = SmsTestSender
58 SmsSenderFactory.senders["bad"] = SmsBadSender
59
60 UIA_EMAIL_PHONE = [
61 {"email": {"mapper": uia_email_mapper, "case_insensitive": True}},
62 {"us_phone_number": {"mapper": uia_phone_mapper}},
63 ]
64
65
66 @contextmanager
67 def capture_send_code_requests():
68 login_requests = []
69
70 def _on(app, **data):
71 assert isinstance(app, Flask)
72 assert all(v in data for v in ["user", "method", "token"])
73 assert isinstance(data["user"], UserMixin)
74 login_requests.append(data)
75
76 us_security_token_sent.connect(_on)
77
78 try:
79 yield login_requests
80 finally:
81 us_security_token_sent.disconnect(_on)
82
83
84 def us_authenticate(client, identity="[email protected]"):
85 with capture_send_code_requests() as requests:
86 response = client.post(
87 "/us-signin/send-code",
88 json=dict(identity=identity, chosen_method="email"),
89 headers={"Content-Type": "application/json"},
90 )
91 assert response.status_code == 200
92
93 response = client.post(
94 "/us-signin?include_auth_token",
95 json=dict(identity=identity, passcode=requests[0]["token"]),
96 headers={"Content-Type": "application/json"},
97 )
98 assert response.status_code == 200
99 return response.json["response"]["user"]["authentication_token"]
100
101
102 def us_tf_authenticate(app, client, json=False, validate=True, remember=False):
103 """Login/Authenticate using two factor and unified signin
104 This is the equivalent of utils:authenticate
105 """
106 prev_sms = app.config["SECURITY_SMS_SERVICE"]
107 app.config["SECURITY_SMS_SERVICE"] = "test"
108 sms_sender = SmsSenderFactory.createSender("test")
109 json_data = dict(identity="[email protected]", passcode="password", remember=remember)
110 response = client.post(
111 "/us-signin", json=json_data, headers={"Content-Type": "application/json"}
112 )
113
114 assert b'"code": 200' in response.data
115 app.config["SECURITY_SMS_SERVICE"] = prev_sms
116
117 if validate:
118 code = sms_sender.messages[0].split()[-1]
119 if json:
120 response = client.post(
121 "/tf-validate",
122 json=dict(code=code),
123 headers={"Content-Type": "application/json"},
124 )
125 assert b'"code": 200' in response.data
126 else:
127 response = client.post(
128 "/tf-validate", data=dict(code=code), follow_redirects=True
129 )
130 assert response.status_code == 200
131
132
133 def set_phone(app, email="[email protected]", phone="650-273-3780"):
134 # A quick way to 'setup' SMS
135 with app.test_request_context("/"):
136 user = app.security.datastore.find_user(email=email)
137 totp_secret = app.security._totp_factory.generate_totp_secret()
138 app.security.datastore.us_set(user, "sms", totp_secret, phone)
139 app.security.datastore.commit()
140
141
142 def set_email(app, email="[email protected]"):
143 # A quick way to 'setup' email
144 with app.test_request_context("/"):
145 user = app.security.datastore.find_user(email=email)
146 totp_secret = app.security._totp_factory.generate_totp_secret()
147 app.security.datastore.us_set(user, "email", totp_secret)
148 app.security.datastore.commit()
149
150
151 def test_simple_signin(app, clients, get_message, outbox, signals):
152 set_email(app)
153
154 # Test missing choice
155 data = dict(identity="[email protected]")
156 response = clients.post("/us-signin/send-code", data=data, follow_redirects=True)
157 assert get_message("US_METHOD_NOT_AVAILABLE") in response.data
158
159 # Test login using invalid email
160 data = dict(identity="[email protected]", chosen_method="email")
161 response = clients.post("/us-signin/send-code", data=data, follow_redirects=True)
162 assert get_message("US_SPECIFY_IDENTITY") in response.data
163
164 # test disabled account
165 set_email(app, email="[email protected]")
166 with app.test_request_context("/"):
167 user = app.security.datastore.find_user(email="[email protected]")
168 app.security.datastore.deactivate_user(user)
169 app.security.datastore.commit()
170
171 data = dict(identity="[email protected]", chosen_method="email")
172 response = clients.post("/us-signin/send-code", data=data, follow_redirects=True)
173 assert b"Code has been sent" not in response.data
174 assert get_message("DISABLED_ACCOUNT") in response.data
175
176 with capture_send_code_requests() as requests:
177 response = clients.post(
178 "/us-signin/send-code",
179 data=dict(identity="[email protected]", chosen_method="email"),
180 follow_redirects=True,
181 )
182 assert response.status_code == 200
183 assert b"Sign In" in response.data
184 assert len(requests) == 1
185 assert len(outbox) == 1
186
187 # try bad code
188 response = clients.post(
189 "/us-signin",
190 data=dict(identity="[email protected]", passcode="blahblah"),
191 follow_redirects=True,
192 )
193 assert get_message("INVALID_PASSWORD_CODE") in response.data
194 assert signals["user_failed_authn"][0]["request_endpoint"] == "security.us_signin"
195 assert signals["user_failed_authn"][0]["user"].email == "[email protected]"
196 assert signals["user_failed_authn"][0]["auth_type"] == "passcode"
197 assert not signals["user_failed_authn"][0]["tfa"]
198
199 # Correct code
200 assert not clients.get_cookie("remember_token")
201 assert not clients.get_cookie("session")
202 response = clients.post(
203 "/us-signin",
204 data=dict(identity="[email protected]", passcode=requests[0]["token"]),
205 follow_redirects=False,
206 )
207 assert not clients.get_cookie("remember_token")
208 assert signals["user_authenticated"][0]["authn_via"] == ["email"]
209
210 assert is_authenticated(clients, get_message)
211
212 logout(clients)
213 assert not is_authenticated(clients, get_message)
214
215 # login via SMS
216 sms_sender = SmsSenderFactory.createSender("test")
217 set_phone(app)
218 response = clients.post(
219 "/us-signin/send-code",
220 data=dict(identity="[email protected]", chosen_method="sms"),
221 follow_redirects=True,
222 )
223 assert response.status_code == 200
224 assert b"Sign In" in response.data
225
226 code = sms_sender.messages[0].split()[-1].strip(".")
227 response = clients.post(
228 "/us-signin",
229 data=dict(identity="[email protected]", passcode=code, remember=True),
230 follow_redirects=True,
231 )
232 assert response.status_code == 200
233 assert clients.get_cookie("remember_token")
234 assert signals["user_authenticated"][1]["authn_via"] == ["sms"]
235
236 assert is_authenticated(clients, get_message)
237
238 logout(clients)
239 assert not clients.get_cookie("remember_token")
240
241
242 def test_simple_signin_json(app, client_nc, get_message, outbox, signals):
243 set_email(app)
244 headers = {"Accept": "application/json", "Content-Type": "application/json"}
245
246 with capture_flashes() as flashes:
247 response = client_nc.get("/us-signin", headers=headers)
248 jresponse = response.json["response"]
249 assert (
250 jresponse["available_methods"] == app.config["SECURITY_US_ENABLED_METHODS"]
251 )
252 assert jresponse["identity_attributes"] == get_identity_attributes(app=app)
253 assert set(jresponse["code_methods"]) == {"email", "sms"}
254
255 with capture_send_code_requests() as requests:
256 response = client_nc.post(
257 "/us-signin/send-code",
258 json=dict(identity="[email protected]", chosen_method="email"),
259 headers=headers,
260 follow_redirects=True,
261 )
262 assert response.status_code == 200
263 assert "csrf_token" in response.json["response"]
264 assert "user" not in response.json["response"]
265 assert len(requests) == 1
266 assert len(outbox) == 1
267
268 # try bad code
269 response = client_nc.post(
270 "/us-signin",
271 json=dict(identity="[email protected]", passcode="blahblah"),
272 headers=headers,
273 follow_redirects=True,
274 )
275 assert response.status_code == 400
276 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
277 "INVALID_PASSWORD_CODE"
278 )
279 assert (
280 signals["user_failed_authn"][0]["request_endpoint"] == "security.us_signin"
281 )
282 assert signals["user_failed_authn"][0]["user"].email == "[email protected]"
283 assert signals["user_failed_authn"][0]["auth_type"] == "passcode"
284 assert not signals["user_failed_authn"][0]["tfa"]
285
286 # Login successfully with code
287 response = client_nc.post(
288 "/us-signin?include_auth_token",
289 json=dict(identity="[email protected]", passcode=requests[0]["token"]),
290 headers=headers,
291 follow_redirects=True,
292 )
293 assert response.status_code == 200
294 assert "authentication_token" in response.json["response"]["user"]
295 assert signals["user_authenticated"][0]["authn_via"] == ["email"]
296
297 logout(client_nc)
298 assert not is_authenticated(client_nc, get_message)
299
300 # login via SMS
301 sms_sender = SmsSenderFactory.createSender("test")
302 set_phone(app)
303 response = client_nc.post(
304 "/us-signin/send-code",
305 json=dict(identity="[email protected]", chosen_method="sms"),
306 headers=headers,
307 follow_redirects=True,
308 )
309 assert response.status_code == 200
310
311 code = sms_sender.messages[0].split()[-1].strip(".")
312 response = client_nc.post(
313 "/us-signin?include_auth_token",
314 json=dict(identity="[email protected]", passcode=code),
315 headers=headers,
316 follow_redirects=True,
317 )
318 assert response.status_code == 200
319 assert "authentication_token" in response.json["response"]["user"]
320 assert len(flashes) == 0
321
322
323 @pytest.mark.changeable()
324 def test_signin_pwd_json(app, client, get_message):
325 # Make sure us-signin accepts a normalized and original password.
326 authenticate(client)
327 headers = {"Accept": "application/json", "Content-Type": "application/json"}
328 data = dict(
329 password="password",
330 new_password="new strong password\N{ROMAN NUMERAL ONE}",
331 new_password_confirm="new strong password\N{ROMAN NUMERAL ONE}",
332 )
333 response = client.post(
334 "/change",
335 json=data,
336 headers={"Content-Type": "application/json"},
337 )
338 assert response.status_code == 200
339 logout(client)
340
341 response = client.post(
342 "/us-signin",
343 json=dict(
344 identity="[email protected]", passcode="new strong password\N{ROMAN NUMERAL ONE}"
345 ),
346 headers=headers,
347 follow_redirects=False,
348 )
349 assert response.status_code == 200
350 logout(client)
351
352 response = client.post(
353 "/us-signin",
354 json=dict(
355 identity="[email protected]",
356 passcode="new strong password\N{LATIN CAPITAL LETTER I}",
357 ),
358 headers=headers,
359 follow_redirects=False,
360 )
361 assert response.status_code == 200
362
363
364 @pytest.mark.registerable()
365 @pytest.mark.settings(
366 password_required=False,
367 us_email_template="security/email/us_instructions_test",
368 email_html=False,
369 )
370 def test_us_passwordless(app, client, get_message, outbox):
371 # Check passwordless.
372 # Check contents of email template - this uses a test template
373 # in order to check all context vars since the default template
374 # doesn't have all of them.
375 response = client.post(
376 "/register", data=dict(email="[email protected]"), follow_redirects=True
377 )
378 logout(client)
379 with capture_send_code_requests() as requests:
380 response = client.post(
381 "/us-signin/send-code",
382 data=dict(identity="[email protected]", chosen_method="email"),
383 follow_redirects=True,
384 )
385 # 2 emails - first from registration.
386 assert len(outbox) == 2
387 matcher = re.findall(r"\w+:.*", outbox[1].body, re.IGNORECASE)
388 # should be 6 - link, email, token, config item, username, within
389 # and entire real template included
390 assert matcher[1].split(":")[1] == "[email protected]"
391 token = matcher[2].split(":")[1]
392 assert token == requests[0]["token"] # deprecated
393 assert token == requests[0]["login_token"]
394 assert matcher[3].split(":")[1] == "True" # register_blueprint
395 assert matcher[4].split(":")[1] == "[email protected]"
396 assert matcher[5].split(":")[1] == "2 minutes"
397 # regular text template is included in the test template
398 assert "This code/link will expire in 2 minutes." in outbox[1].body
399
400 # check link
401 link = matcher[0].split(":", 1)[1]
402 response = client.get(link, follow_redirects=True)
403 assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") in response.data
404
405 # check us-setup has 'email' but not password
406 response = client.get("/us-setup", json={})
407 assert response.json["response"]["active_methods"] == ["email"]
408
409
410 @pytest.mark.registerable()
411 @pytest.mark.confirmable()
412 @pytest.mark.settings(
413 password_required=False,
414 us_email_template="security/email/us_instructions_test",
415 email_html=False,
416 )
417 def test_us_passwordless_confirm(app, client, get_message, outbox):
418 # Check passwordless with confirmation required.
419 response = client.post(
420 "/register", data=dict(email="[email protected]"), follow_redirects=True
421 )
422 # Try logging in - should get confirmation required.
423 response = client.post(
424 "/us-signin/send-code",
425 data=dict(identity="[email protected]", chosen_method="email"),
426 follow_redirects=True,
427 )
428 assert get_message("CONFIRMATION_REQUIRED") in response.data
429 # grab welcome email which has confirmation link (test version of welcome.txt)
430 matcher = re.findall(r"\w+:.*", outbox[0].body, re.IGNORECASE)
431 link = matcher[0].split(":", 1)[1]
432 response = client.get(link, follow_redirects=True)
433 assert get_message("EMAIL_CONFIRMED") in response.data
434 logout(client)
435
436 # should be able to authenticate now.
437 response = client.post(
438 "/us-signin/send-code",
439 data=dict(identity="[email protected]", chosen_method="email"),
440 follow_redirects=True,
441 )
442 # 2 emails - first from registration.
443 assert len(outbox) == 2
444 matcher = re.findall(r"\w+:.*", outbox[1].body, re.IGNORECASE)
445 # authenticate with link
446 link = matcher[0].split(":", 1)[1]
447 response = client.get(link, follow_redirects=True)
448 assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") in response.data
449
450
451 @pytest.mark.registerable()
452 @pytest.mark.confirmable()
453 @pytest.mark.settings(
454 password_required=False,
455 us_email_template="security/email/us_instructions_test",
456 email_html=False,
457 )
458 def test_us_passwordless_confirm_json(app, client, get_message, outbox):
459 # Check passwordless with confirmation required.
460 headers = {"Accept": "application/json", "Content-Type": "application/json"}
461 response = client.post("/register", json=dict(email="[email protected]"))
462 # Try logging in - should get confirmation required.
463 response = client.post(
464 "/us-signin/send-code",
465 json=dict(identity="[email protected]", chosen_method="email"),
466 )
467 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
468 "CONFIRMATION_REQUIRED"
469 )
470
471 # grab welcome email which has confirmation link (test version of welcome.txt)
472 matcher = re.findall(r"\w+:.*", outbox[0].body, re.IGNORECASE)
473 link = matcher[0].split(":", 1)[1]
474 response = client.get(link, headers=headers, follow_redirects=False)
475 assert check_location(app, response.location, "/login")
476
477 # should be able to authenticate now.
478 response = client.post(
479 "/us-signin/send-code",
480 json=dict(identity="[email protected]", chosen_method="email"),
481 )
482 # 2 emails - first from registration.
483 assert len(outbox) == 2
484 matcher = re.findall(r"\w+:.*", outbox[1].body, re.IGNORECASE)
485 # authenticate with link
486 link = matcher[0].split(":", 1)[1]
487 response = client.get(link, headers=headers, follow_redirects=True)
488 assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") in response.data
489
490
491 def test_admin_setup_user_reset(app, client_nc, get_message):
492 # Test that we can setup SMS using datastore admin method, and that
493 # the datastore admin reset (reset_user_access) disables it.
494 headers = {"Accept": "application/json", "Content-Type": "application/json"}
495
496 sms_sender = SmsSenderFactory.createSender("test")
497 set_phone(app)
498 response = client_nc.post(
499 "/us-signin/send-code",
500 json=dict(identity="[email protected]", chosen_method="sms"),
501 headers=headers,
502 follow_redirects=True,
503 )
504 assert response.status_code == 200
505
506 assert len(sms_sender.messages) == 1
507 code = sms_sender.messages[0].split()[-1].strip(".")
508 response = client_nc.post(
509 "/us-signin?include_auth_token",
510 json=dict(identity="[email protected]", passcode=code),
511 headers=headers,
512 follow_redirects=True,
513 )
514 assert response.status_code == 200
515
516 # logout, reset access
517 logout(client_nc)
518 with app.test_request_context("/"):
519 user = app.security.datastore.find_user(email="[email protected]")
520 app.security.datastore.reset_user_access(user)
521 app.security.datastore.commit()
522
523 response = client_nc.post(
524 "/us-signin/send-code",
525 json=dict(identity="[email protected]", chosen_method="sms"),
526 headers=headers,
527 follow_redirects=True,
528 )
529 assert response.status_code == 400
530 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
531 "US_METHOD_NOT_AVAILABLE"
532 )
533 # Nothing should have been sent.
534 assert len(sms_sender.messages) == 1
535
536
537 def test_admin_setup_reset(app, client_nc, get_message):
538 # Test that we can setup SMS using datastore admin method, and that
539 # the datastore admin reset (us_reset) disables it.
540 headers = {"Accept": "application/json", "Content-Type": "application/json"}
541
542 sms_sender = SmsSenderFactory.createSender("test")
543 set_phone(app)
544 response = client_nc.post(
545 "/us-signin/send-code",
546 json=dict(identity="[email protected]", chosen_method="sms"),
547 headers=headers,
548 follow_redirects=True,
549 )
550 assert response.status_code == 200
551 assert len(sms_sender.messages) == 1
552
553 with app.test_request_context("/"):
554 user = app.security.datastore.find_user(email="[email protected]")
555 app.security.datastore.us_reset(user)
556 app.security.datastore.commit()
557
558 response = client_nc.post(
559 "/us-signin/send-code",
560 json=dict(identity="[email protected]", chosen_method="sms"),
561 headers=headers,
562 follow_redirects=True,
563 )
564 assert response.status_code == 400
565 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
566 "US_METHOD_NOT_AVAILABLE"
567 )
568 # Nothing should have been sent.
569 assert len(sms_sender.messages) == 1
570
571
572 @pytest.mark.settings(post_login_view="/post_login")
573 def test_get_already_authenticated(app, client):
574 response = authenticate(client, follow_redirects=True)
575 assert b"Welcome [email protected]" in response.data
576 # This should ignore next
577 response = client.get("/us-signin?next=/page1", follow_redirects=True)
578 assert b"Post Login" in response.data
579
580 # should still get extra goodies
581 headers = {"Accept": "application/json", "Content-Type": "application/json"}
582 response = client.get("/us-signin", headers=headers)
583 assert response.status_code == 200
584
585 jresponse = response.json["response"]
586 assert all(
587 a in jresponse
588 for a in ["code_methods", "identity_attributes", "available_methods"]
589 )
590 assert "authentication_token" not in jresponse["user"]
591 assert all(a in jresponse["user"] for a in ["email", "last_update"])
592
593
594 @pytest.mark.settings(post_login_view="/post_login")
595 def test_post_already_authenticated(client, get_message):
596 response = authenticate(client, follow_redirects=True)
597 assert b"Welcome [email protected]" in response.data
598 data = dict(email="[email protected]", password="password")
599 response = client.post("/us-signin", data=data, follow_redirects=True)
600 assert b"Post Login" in response.data
601
602 headers = {"Accept": "application/json", "Content-Type": "application/json"}
603 response = client.post("/us-signin", json=data, headers=headers)
604 assert response.status_code == 400
605 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
606 "ANONYMOUS_USER_REQUIRED"
607 )
608
609
610 @pytest.mark.settings(us_email_subject="Code For You")
611 def test_verify_link(app, client, get_message, outbox, signals):
612 set_email(app)
613
614 with capture_send_code_requests() as requests:
615 response = client.post(
616 "/us-signin/send-code",
617 data=dict(identity="[email protected]", chosen_method="email"),
618 follow_redirects=True,
619 )
620 assert response.status_code == 200
621 assert b"Sign In" in response.data
622
623 assert outbox[0].recipients == ["[email protected]"]
624 assert outbox[0].sender == "no-reply@localhost"
625 assert outbox[0].subject == "Code For You"
626 matcher = re.match(
627 r".*(http://[^\s*]*).*", outbox[0].body, re.IGNORECASE | re.DOTALL
628 )
629 magic_link = matcher.group(1)
630
631 # Try with missing code
632 response = client.get("[email protected]", follow_redirects=False)
633 assert "/us-signin" in response.location
634 response = client.get("[email protected]", follow_redirects=True)
635 assert get_message("API_ERROR") in response.data
636
637 # Try unknown user
638 response = client.get("us-verify-link?id=123435&code=12345", follow_redirects=True)
639 assert get_message("USER_DOES_NOT_EXIST") in response.data
640
641 # Try bad code
642 response = client.get(
643 f"us-verify-link?id={requests[0]['user'].fs_uniquifier}&code=12345",
644 follow_redirects=True,
645 )
646 assert get_message("INVALID_CODE") in response.data
647 assert (
648 signals["user_failed_authn"][0]["request_endpoint"] == "security.us_verify_link"
649 )
650 assert signals["user_failed_authn"][0]["user"].email == "[email protected]"
651 assert signals["user_failed_authn"][0]["auth_type"] == "passcode"
652 assert not signals["user_failed_authn"][0]["tfa"]
653
654 # Try actual link
655 response = client.get(magic_link, follow_redirects=True)
656 assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") in response.data
657 assert signals["user_authenticated"][0]["authn_via"] == ["email"]
658
659 # verify logged in
660 assert is_authenticated(client, get_message)
661 check_signals(signals, {"user_failed_authn": 1, "us_security_token_sent": 1})
662
663
664 @pytest.mark.settings(
665 redirect_host="localhost:8081",
666 redirect_behavior="spa",
667 login_error_view="/login-error",
668 post_login_view="/post-login",
669 )
670 def test_verify_link_spa(app, client, get_message, outbox, signals):
671 # N.B. we use client here since this only works/ is supported if using
672 # sessions.
673 set_email(app)
674 headers = {"Accept": "application/json", "Content-Type": "application/json"}
675
676 with capture_send_code_requests() as requests:
677 response = client.post(
678 "/us-signin/send-code",
679 json=dict(identity="[email protected]", chosen_method="email"),
680 headers=headers,
681 )
682 assert response.status_code == 200
683
684 matcher = re.match(
685 r".*(http://[^\s*]*).*", outbox[0].body, re.IGNORECASE | re.DOTALL
686 )
687 magic_link = matcher.group(1)
688
689 # Try with no code
690 response = client.get("[email protected]", follow_redirects=False)
691 assert response.status_code in [302, 303]
692 split = urlsplit(response.headers["Location"])
693 assert "localhost:8081" == split.netloc
694 assert "/login-error" == split.path
695 qparams = dict(parse_qsl(split.query))
696 assert get_message("API_ERROR") == qparams["error"].encode("utf-8")
697
698 # Try unknown user
699 response = client.get("us-verify-link?id=98765&code=12345", follow_redirects=False)
700 assert response.status_code in [302, 303]
701 split = urlsplit(response.headers["Location"])
702 assert "localhost:8081" == split.netloc
703 assert "/login-error" == split.path
704 qparams = dict(parse_qsl(split.query))
705 assert get_message("USER_DOES_NOT_EXIST") == qparams["error"].encode("utf-8")
706
707 # Try bad code
708 response = client.get(
709 f"us-verify-link?id={requests[0]['user'].fs_uniquifier}&code=12345",
710 follow_redirects=False,
711 )
712 assert response.status_code in [302, 303]
713 split = urlsplit(response.headers["Location"])
714 assert "localhost:8081" == split.netloc
715 assert "/login-error" == split.path
716 qparams = dict(parse_qsl(split.query))
717 assert get_message("INVALID_CODE") == qparams["error"].encode("utf-8")
718 assert (
719 signals["user_failed_authn"][0]["request_endpoint"] == "security.us_verify_link"
720 )
721 assert signals["user_failed_authn"][0]["user"].email == "[email protected]"
722 assert signals["user_failed_authn"][0]["auth_type"] == "passcode"
723 assert not signals["user_failed_authn"][0]["tfa"]
724
725 # Try actual link
726 response = client.get(magic_link, follow_redirects=False)
727 assert response.status_code in [302, 303]
728 split = urlsplit(response.headers["Location"])
729 assert "localhost:8081" == split.netloc
730 assert "/post-login" == split.path
731 qparams = dict(parse_qsl(split.query))
732 assert qparams["email"] == "[email protected]"
733 check_signals(signals, {"user_failed_authn": 1, "us_security_token_sent": 1})
734
735 assert is_authenticated(client, get_message)
736
737
738 def test_setup(app, clients, get_message, signals):
739 tcl = clients
740 set_email(app)
741 us_authenticate(tcl)
742 response = tcl.get("us-setup")
743 # Email should be in delete options since we just set that up.
744 assert all(
745 i in response.data
746 for i in [b"delete_method-0", b"chosen_method-0", b"chosen_method-1"]
747 )
748
749 # test not supplying anything to do
750 response = tcl.post("us-setup", data=dict(phone="6505551212"))
751 assert get_message("API_ERROR") in response.data
752
753 # test missing phone
754 response = tcl.post("us-setup", data=dict(chosen_method="sms", phone=""))
755 assert response.status_code == 200
756 assert get_message("PHONE_INVALID") in response.data
757
758 # test invalid phone
759 response = tcl.post(
760 "us-setup", data=dict(chosen_method="sms", phone="NOT-A-NUMBER")
761 )
762 assert response.status_code == 200
763 assert get_message("PHONE_INVALID") in response.data
764 assert b"Enter code here to complete setup" not in response.data
765
766 sms_sender = SmsSenderFactory.createSender("test")
767 response = tcl.post(
768 "us-setup", data=dict(chosen_method="sms", phone="650-555-1212")
769 )
770 assert response.status_code == 200
771 assert b"Submit Code" in response.data
772 assert b"Enter code here to complete setup" in response.data
773
774 verify_url = get_form_action(response, 1)
775
776 # Try invalid code
777 response = tcl.post(verify_url, data=dict(passcode=12345), follow_redirects=True)
778 assert get_message("INVALID_PASSWORD_CODE") in response.data
779 # a bad code during setup shouldn't trigger the signal
780 assert len(signals["user_failed_authn"]) == 0
781
782 code = sms_sender.messages[0].split()[-1].strip(".")
783 response = tcl.post(verify_url, data=dict(passcode=code), follow_redirects=True)
784 assert response.status_code == 200
785 assert get_message("US_SETUP_SUCCESSFUL") in response.data
786
787
788 @pytest.mark.settings(
789 us_email_template="security/email/us_instructions_test", email_html=False
790 )
791 def test_setup_email(app, client, get_message, outbox):
792 # setup with email - make sure magic link isn't sent and code is.
793 # N.B. this is using the test us_instructions template
794 set_email(app)
795 us_authenticate(client)
796 response = client.post("us-setup", data=dict(chosen_method="email"))
797 assert response.status_code == 200
798 assert b"Enter code here to complete setup" in response.data
799
800 verify_url = get_form_action(response, 1)
801
802 # verify no magic link - us_authenticate received first email - we want the second
803 matcher = re.findall(r"\w+:.*", outbox[1].body, re.IGNORECASE)
804 # should be 4 - link, email, token, config item
805 assert matcher[0].split(":")[1] == "None"
806 assert matcher[1].split(":")[1] == "[email protected]"
807
808 code = matcher[2].split(":")[1]
809 response = client.post(verify_url, data=dict(passcode=code), follow_redirects=True)
810 assert response.status_code == 200
811 assert get_message("US_SETUP_SUCCESSFUL") in response.data
812
813
814 @pytest.mark.settings(
815 us_enabled_methods=["email", "sms"],
816 user_identity_attributes=UIA_EMAIL_PHONE,
817 freshness=timedelta(hours=-1),
818 )
819 def test_setup_json(app, client_nc, get_message):
820 # This shows that by setting freshness to negative doesn't require session.
821 @us_profile_changed.connect_via(app)
822 def pc(sender, user, methods, delete, **kwargs):
823 assert not delete
824 assert methods == ["sms"]
825 assert user.us_phone_number == "+16505551212"
826
827 set_email(app)
828 token = us_authenticate(client_nc)
829 headers = {
830 "Authentication-Token": token,
831 "Accept": "application/json",
832 "Content-Type": "application/json",
833 }
834 response = client_nc.get("/us-setup", headers=headers)
835 assert response.status_code == 200
836 assert response.json["response"]["available_methods"] == ["email", "sms"]
837 assert set(response.json["response"]["setup_methods"]) == {"email", "sms"}
838 assert set(response.json["response"]["active_methods"]) == {"email", "password"}
839
840 sms_sender = SmsSenderFactory.createSender("test")
841 response = client_nc.post(
842 "us-setup",
843 json=dict(chosen_method="sms", phone="650-555-1212"),
844 headers=headers,
845 )
846 assert response.status_code == 200
847 state = response.json["response"]["state"]
848 assert state
849
850 # send invalid code
851 response = client_nc.post(
852 "/us-setup/" + state, json=dict(passcode=12344), headers=headers
853 )
854 assert response.status_code == 400
855 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
856 "INVALID_PASSWORD_CODE"
857 )
858 code = sms_sender.messages[0].split()[-1].strip(".")
859 response = client_nc.post(
860 "/us-setup/" + state, json=dict(passcode=code), headers=headers
861 )
862 assert response.status_code == 200
863 assert response.json["response"]["chosen_method"] == "sms"
864 assert response.json["response"]["phone"] == "+16505551212"
865
866 # Verify sms in list of 'active' methods
867 response = client_nc.get("/us-setup", headers=headers)
868 assert response.status_code == 200
869 assert set(response.json["response"]["active_methods"]) == {
870 "email",
871 "sms",
872 "password",
873 }
874
875 # now login with phone - send in different format than we set up with.
876 headers = {"Accept": "application/json", "Content-Type": "application/json"}
877
878 sms_sender = SmsSenderFactory.createSender("test")
879 response = client_nc.post(
880 "/us-signin/send-code",
881 json=dict(identity="6505551212", chosen_method="sms"),
882 headers=headers,
883 )
884 assert response.status_code == 200
885 code = sms_sender.messages[0].split()[-1].strip(".")
886 response = client_nc.post(
887 "/us-signin?include_auth_token",
888 json=dict(identity="[email protected]", passcode=code),
889 headers=headers,
890 )
891 assert response.status_code == 200
892 assert "authentication_token" in response.json["response"]["user"]
893
894
895 @pytest.mark.settings(
896 us_enabled_methods=["email", "sms"],
897 user_identity_attributes=UIA_EMAIL_PHONE,
898 us_email_template="security/email/us_instructions_test",
899 email_html=False,
900 )
901 def test_setup_json_no_session(app, client_nc, get_message, outbox):
902 # Test that with normal config freshness is required and we can use auth_token
903 # for that
904 set_email(app)
905 us_authenticate(client_nc)
906 token = reset_fresh_auth_token(app, app.config["SECURITY_FRESHNESS"])
907 headers = {
908 "Authentication-Token": token,
909 "Accept": "application/json",
910 "Content-Type": "application/json",
911 }
912 response = client_nc.get("/us-setup", headers=headers)
913 assert response.status_code == 401
914 assert response.json["response"]["reauth_required"]
915 assert "WWW-Authenticate" not in response.headers
916
917 # re-verify
918 client_nc.post(
919 "/us-verify/send-code",
920 json=dict(identity="[email protected]", chosen_method="email"),
921 headers=headers,
922 )
923 matcher = re.match(r".*Token:(\d+).*", outbox[1].body, re.IGNORECASE | re.DOTALL)
924 code = matcher.group(1)
925 response = client_nc.post(
926 "/us-verify?include_auth_token", json=dict(passcode=code), headers=headers
927 )
928 assert response.status_code == 200
929 token = response.json["response"]["user"]["authentication_token"]
930 headers["Authentication-Token"] = token
931
932 # should work now
933 response = client_nc.get("/us-setup", headers=headers)
934 assert response.status_code == 200
935
936
937 @pytest.mark.settings(api_enabled_methods=["basic"])
938 def test_setup_basic(app, client, get_message):
939 # If using Basic Auth - always fresh so should be able to setup (not sure the
940 # use case but...)
941 headers = {
942 "Authorization": "Basic %s"
943 % base64.b64encode(b"[email protected]:password").decode("utf-8")
944 }
945 response = client.get("/us-setup", headers=headers)
946 assert response.status_code == 200
947 assert b"Setup Unified Sign In" in response.data
948
949
950 def test_setup_bad_token(app, client, get_message):
951 set_email(app)
952 headers = {"Accept": "application/json", "Content-Type": "application/json"}
953 us_authenticate(client)
954
955 # bogus state
956 response = client.post(
957 "/us-setup/not a token", json=dict(passcode=12345), headers=headers
958 )
959 assert response.status_code == 400
960 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
961 "API_ERROR"
962 )
963
964 # same w/o json
965 response = client.post(
966 "/us-setup/not a token", data=dict(passcode=12345), follow_redirects=True
967 )
968 assert get_message("API_ERROR") in response.data
969
970
971 @pytest.mark.settings(us_setup_within=timedelta(seconds=47))
972 def test_setup_timeout(app, client, get_message):
973 # Test setup timeout
974 set_email(app)
975 us_authenticate(client)
976 headers = {"Accept": "application/json", "Content-Type": "application/json"}
977
978 sms_sender = SmsSenderFactory.createSender("test")
979 app.security.us_setup_serializer = FakeSerializer(47.0)
980 response = client.post(
981 "us-setup",
982 json=dict(chosen_method="sms", phone="650-555-1212"),
983 headers=headers,
984 )
985 assert response.status_code == 200
986 state = response.json["response"]["state"]
987
988 code = sms_sender.messages[0].split()[-1].strip(".")
989 response = client.post(
990 "/us-setup/" + state, json=dict(passcode=code), headers=headers
991 )
992 assert response.status_code == 400
993 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
994 "US_SETUP_EXPIRED", within="47 seconds"
995 )
996
997
998 @pytest.mark.settings(
999 us_enabled_methods=["email", "sms"],
1000 user_identity_attributes=UIA_EMAIL_PHONE,
1001 )
1002 def test_unique_phone(app, client, get_message):
1003 # Test that us_phone_number is properly validated to be unique
1004 set_email(app, email="[email protected]")
1005 us_authenticate(client, identity="[email protected]")
1006
1007 sms_sender = SmsSenderFactory.createSender("test")
1008 response = client.post(
1009 "us-setup",
1010 json=dict(chosen_method="sms", phone="650-555-1212"),
1011 )
1012 assert response.status_code == 200
1013 state = response.json["response"]["state"]
1014 assert state
1015 code = sms_sender.messages[0].split()[-1].strip(".")
1016 response = client.post("/us-setup/" + state, json=dict(passcode=code))
1017 assert response.status_code == 200
1018
1019 logout(client)
1020
1021 set_email(app, email="[email protected]")
1022 us_authenticate(client, identity="[email protected]")
1023 response = client.post(
1024 "us-setup",
1025 json=dict(chosen_method="sms", phone="650-555-1212"),
1026 )
1027 assert response.status_code == 400
1028 assert response.json["response"]["errors"][0].encode() == get_message(
1029 "IDENTITY_ALREADY_ASSOCIATED", attr="us_phone_number", value="+16505551212"
1030 )
1031
1032
1033 @pytest.mark.settings(freshness=timedelta(minutes=0))
1034 def test_verify(app, clients, get_message, signals):
1035 client = clients
1036 # Test setup when re-authenticate required
1037 # With freshness set to 0 - the first call should require reauth (by
1038 # redirecting); but the second should work due to grace period.
1039 set_email(app)
1040 us_authenticate(client)
1041 response = client.get("us-setup", follow_redirects=False)
1042 verify_url = response.location
1043 assert check_location(app, response.location, "/us-verify?next=/us-setup")
1044 logout(client)
1045 us_authenticate(client)
1046
1047 response = client.get("us-setup", follow_redirects=True)
1048 form_response = response.data.decode("utf-8")
1049 assert "Reauthenticate" in form_response
1050 send_code_url = get_form_action(response, 1)
1051
1052 # Send unknown method
1053 response = client.post(
1054 send_code_url,
1055 data=dict(identity="[email protected]", chosen_method="sms2"),
1056 follow_redirects=True,
1057 )
1058 assert response.status_code == 200
1059 assert b"Not a valid choice" in response.data
1060
1061 # Verify using SMS
1062 sms_sender = SmsSenderFactory.createSender("test")
1063 set_phone(app)
1064 response = client.post(
1065 send_code_url,
1066 data=dict(identity="[email protected]", chosen_method="sms"),
1067 follow_redirects=True,
1068 )
1069 assert response.status_code == 200
1070 assert b"Code has been sent" in response.data
1071
1072 code = sms_sender.messages[0].split()[-1].strip(".")
1073 response = client.post(verify_url, data=dict(passcode=code), follow_redirects=False)
1074 assert check_location(app, response.location, "/us-setup")
1075 check_signals(signals, {"user_failed_authn": 0, "us_security_token_sent": 3})
1076
1077
1078 def test_verify_json(app, client, get_message, signals):
1079 # Test setup when re-authenticate required
1080 # N.B. with freshness=0 we never set a grace period and should never be able to
1081 # get to /us-setup
1082 set_email(app)
1083 us_authenticate(client)
1084 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1085
1086 app.config["SECURITY_FRESHNESS"] = timedelta(minutes=0)
1087 response = client.get("us-setup", headers=headers)
1088 assert response.status_code == 401
1089 assert response.json["response"]["reauth_required"]
1090
1091 # figure out which methods are usable
1092 response = client.get("us-verify", headers=headers)
1093 assert response.json["response"]["available_methods"] == [
1094 "password",
1095 "email",
1096 "authenticator",
1097 "sms",
1098 ]
1099 # code_methods should just contain active/setup methods.
1100 assert set(response.json["response"]["code_methods"]) == {
1101 "email",
1102 }
1103 assert not response.json["response"]["oauth_enabled"]
1104 assert not response.json["response"]["oauth_providers"]
1105
1106 response = client.post(
1107 "us-verify/send-code",
1108 json=dict(chosen_method="orb"),
1109 headers=headers,
1110 )
1111 assert response.status_code == 400
1112
1113 # Verify using SMS
1114 sms_sender = SmsSenderFactory.createSender("test")
1115 set_phone(app)
1116 response = client.post(
1117 "us-verify/send-code",
1118 json=dict(chosen_method="sms"),
1119 headers=headers,
1120 )
1121 assert response.status_code == 200
1122
1123 # Try bad code
1124 response = client.post("us-verify", json=dict(passcode=42), headers=headers)
1125 assert response.status_code == 400
1126 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1127 "INVALID_PASSWORD_CODE"
1128 )
1129 assert response.json["response"]["field_errors"]["passcode"][0].encode(
1130 "utf-8"
1131 ) == get_message("INVALID_PASSWORD_CODE")
1132 assert signals["user_failed_authn"][0]["request_endpoint"] == "security.us_verify"
1133 assert signals["user_failed_authn"][0]["user"].email == "[email protected]"
1134 assert signals["user_failed_authn"][0]["auth_type"] == "passcode"
1135 assert not signals["user_failed_authn"][0]["tfa"]
1136
1137 response = client.post("us-verify", json=dict(passcode=None), headers=headers)
1138 assert response.status_code == 400
1139 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1140 "INVALID_PASSWORD_CODE"
1141 )
1142
1143 code = sms_sender.messages[0].split()[-1].strip(".")
1144 response = client.post("us-verify", json=dict(passcode=code), headers=headers)
1145 assert response.status_code == 200
1146
1147 app.config["SECURITY_FRESHNESS"] = timedelta(minutes=60)
1148 response = client.get("us-setup", headers=headers)
1149 assert response.status_code == 200
1150 assert len(signals["user_failed_authn"]) == 1
1151 check_signals(signals, {"user_failed_authn": 1, "us_security_token_sent": 2})
1152
1153
1154 @pytest.mark.settings(freshness=timedelta(minutes=-1))
1155 def test_setup_nofresh(app, client, get_message):
1156 set_email(app)
1157 us_authenticate(client)
1158 response = client.get("us-setup", follow_redirects=False)
1159 assert response.status_code == 200
1160
1161 response = client.get("us-verify")
1162 assert response.status_code == 404
1163
1164
1165 @pytest.mark.settings(us_enabled_methods=["sms"])
1166 def test_invalid_method(app, client, get_message):
1167 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1168
1169 response = client.get("/us-signin", headers=headers)
1170 assert response.json["response"]["available_methods"] == ["sms"]
1171
1172 # verify json error
1173 response = client.post(
1174 "/us-signin/send-code",
1175 json=dict(identity="[email protected]", chosen_method="email"),
1176 headers=headers,
1177 follow_redirects=True,
1178 )
1179 assert response.status_code == 400
1180 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1181 "US_METHOD_NOT_AVAILABLE"
1182 )
1183
1184 # verify form error
1185 response = client.post(
1186 "/us-signin/send-code",
1187 data=dict(identity="[email protected]", chosen_method="email"),
1188 follow_redirects=True,
1189 )
1190 assert response.status_code == 200
1191 assert get_message("US_METHOD_NOT_AVAILABLE") in response.data
1192
1193
1194 @pytest.mark.settings(us_enabled_methods=["sms", "email"])
1195 def test_invalid_method_setup(app, client, get_message):
1196 set_email(app)
1197 us_authenticate(client)
1198 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1199
1200 response = client.get("/us-setup", headers=headers)
1201 assert response.json["response"]["available_methods"] == ["sms", "email"]
1202
1203 # verify json error
1204 response = client.post(
1205 "/us-setup",
1206 json=dict(email="[email protected]", chosen_method="authenticator"),
1207 headers=headers,
1208 follow_redirects=True,
1209 )
1210 assert response.status_code == 400
1211 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1212 "US_METHOD_NOT_AVAILABLE"
1213 )
1214
1215 response = client.post(
1216 "/us-setup",
1217 data=dict(email="[email protected]", chosen_method="authenticators"),
1218 follow_redirects=True,
1219 )
1220 assert get_message("US_METHOD_NOT_AVAILABLE") in response.data
1221
1222
1223 def test_setup_new_totp(app, client, get_message):
1224 # us-setup should generate a new totp secret for each setup
1225 # Verify existing codes no longer work
1226 set_email(app)
1227 us_authenticate(client)
1228
1229 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1230
1231 # Start by generating a good code - this will generate a new totp
1232 sms_sender = SmsSenderFactory.createSender("test")
1233 response = client.post(
1234 "us-setup",
1235 json=dict(chosen_method="sms", phone="650-555-1212"),
1236 headers=headers,
1237 )
1238 assert response.status_code == 200
1239 assert "authr_key" not in response.json["response"]
1240 code = sms_sender.messages[0].split()[-1].strip(".")
1241
1242 # Now start setup again - it should generate a new totp - so the previous 'code'
1243 # should no longer work
1244 sms_sender2 = SmsSenderFactory.createSender("test")
1245 response = client.post(
1246 "us-setup",
1247 json=dict(chosen_method="sms", phone="650-555-1212"),
1248 headers=headers,
1249 )
1250 assert response.status_code == 200
1251 state = response.json["response"]["state"]
1252 # Use old code
1253 response = client.post(
1254 "/us-setup/" + state, json=dict(passcode=code), headers=headers
1255 )
1256 assert response.status_code == 400
1257
1258 # Use new code
1259 code = sms_sender2.messages[0].split()[-1].strip(".")
1260 response = client.post(
1261 "/us-setup/" + state, json=dict(passcode=code), headers=headers
1262 )
1263 assert response.status_code == 200
1264 assert response.json["response"]["chosen_method"] == "sms"
1265 assert response.json["response"]["phone"] == "+16505551212"
1266
1267
1268 def test_qrcode(app, client, get_message):
1269 # Test forms based authenticator setup - can't really parse QRcode - but can use
1270 # the key sent as part of the response.
1271 set_email(app, email="[email protected]")
1272 us_authenticate(client, identity="[email protected]")
1273 response = client.post("us-setup", data=dict(chosen_method="authenticator"))
1274 assert response.status_code == 200
1275 # verify png QRcode is present
1276 assert b"data:image/svg+xml;base64," in response.data
1277
1278 # parse out key
1279 rd = response.data.decode("utf-8")
1280 matcher = re.match(r".*((?:\S{4}-){7}\S{4}).*", rd, re.DOTALL)
1281 totp_secret = matcher.group(1)
1282
1283 # Generate token from passed totp_secret and confirm setup
1284 totp = TOTP(totp_secret)
1285 code = totp.generate().token
1286
1287 # get verify link e.g. /us-setup/{state}
1288 verify_url = get_form_action(response, 1)
1289
1290 response = client.post(verify_url, data=dict(passcode=code), follow_redirects=True)
1291 assert response.status_code == 200
1292 assert get_message("US_SETUP_SUCCESSFUL") in response.data
1293
1294
1295 def test_next(app, client, get_message):
1296 set_email(app)
1297 with capture_send_code_requests() as requests:
1298 response = client.post(
1299 "/us-signin/send-code",
1300 data=dict(identity="[email protected]", chosen_method="email"),
1301 follow_redirects=True,
1302 )
1303 assert response.status_code == 200
1304
1305 response = client.post(
1306 "/us-signin?next=/post_login",
1307 data=dict(identity="[email protected]", passcode=requests[0]["token"]),
1308 follow_redirects=False,
1309 )
1310 assert "/post_login" in response.location
1311
1312 logout(client)
1313 # Test form.next
1314 response = client.post(
1315 "/us-signin",
1316 data=dict(
1317 identity="[email protected]", passcode=requests[0]["token"], next="/post_login"
1318 ),
1319 follow_redirects=False,
1320 )
1321
1322 assert "/post_login" in response.location
1323
1324
1325 def test_us_verify_form_next(app, client, get_message):
1326 # /us-verify should honor form.next and validate it (issue #1108)
1327 set_email(app)
1328 us_authenticate(client)
1329
1330 response = client.get("/us-verify?next=/profile")
1331 assert b'name="next"' in response.data
1332 assert b'value="/profile"' in response.data
1333
1334 response = client.post(
1335 "/us-verify",
1336 data=dict(passcode="password", next="/profile"),
1337 follow_redirects=False,
1338 )
1339 assert check_location(app, response.location, "/profile")
1340
1341 response = client.post(
1342 "/us-verify",
1343 data=dict(passcode="password", next="http://evil.example/phish"),
1344 follow_redirects=False,
1345 )
1346 assert response.status_code == 200
1347 assert get_message("INVALID_REDIRECT") in response.data
1348
1349
1350 @pytest.mark.registerable()
1351 @pytest.mark.confirmable()
1352 @pytest.mark.settings(requires_confirmation_error_view="/confirm")
1353 def test_requires_confirmation_error_redirect(app, client):
1354 data = dict(
1355 email="[email protected]", password="password", password_confirm="password", next=""
1356 )
1357 response = client.post("/register", data=data, follow_redirects=True)
1358 set_email(app, email="[email protected]")
1359
1360 response = client.post(
1361 "/us-signin/send-code",
1362 data=dict(identity="[email protected]", chosen_method="email"),
1363 follow_redirects=False,
1364 )
1365 assert response.location == "/confirm?email=jyl%40lp.com"
1366
1367 response = client.post(
1368 "/us-signin",
1369 data=dict(identity="[email protected]", passcode="password"),
1370 follow_redirects=False,
1371 )
1372 assert response.location == "/confirm?email=jyl%40lp.com"
1373
1374
1375 @pytest.mark.registerable()
1376 @pytest.mark.confirmable()
1377 def test_confirmable(app, client, get_message, signals):
1378 # Verify can't log in if need confirmation.
1379 data = dict(
1380 email="[email protected]", password="password", password_confirm="password", next=""
1381 )
1382 response = client.post("/register", data=data, follow_redirects=True)
1383 assert response.status_code == 200
1384 set_email(app, email="[email protected]")
1385
1386 response = client.post(
1387 "/us-signin/send-code",
1388 data=dict(identity="[email protected]", chosen_method="email"),
1389 follow_redirects=True,
1390 )
1391 assert response.status_code == 200
1392
1393 assert get_message("CONFIRMATION_REQUIRED") in response.data
1394 check_signals(signals, "user_registered")
1395
1396 # Verify not authenticated
1397 assert not is_authenticated(client, get_message)
1398
1399
1400 @pytest.mark.parametrize("app", v2_param, indirect=True)
1401 @pytest.mark.registerable()
1402 @pytest.mark.recoverable()
1403 @pytest.mark.settings(password_required=False)
1404 def test_can_add_password(app, client, get_message):
1405 # Test that if register w/o a password, can use 'recover password' to assign one
1406 data = dict(email="[email protected]", password="", password_confirm="")
1407 response = client.post("/register", data=data, follow_redirects=True)
1408 assert b"Welcome [email protected]" in response.data
1409 logout(client)
1410
1411 with capture_reset_password_requests() as requests:
1412 client.post("/reset", data=dict(email="[email protected]"), follow_redirects=True)
1413 token = requests[0]["token"]
1414
1415 response = client.post(
1416 "/reset/" + token,
1417 data={"password": "awesome sunset", "password_confirm": "awesome sunset"},
1418 follow_redirects=True,
1419 )
1420
1421 assert get_message("PASSWORD_RESET_NO_LOGIN") in response.data
1422
1423 # authenticate with new password using standard/old login endpoint.
1424 response = authenticate(
1425 client, "[email protected]", "awesome sunset", follow_redirects=True
1426 )
1427 assert b"Welcome [email protected]" in response.data
1428
1429 logout(client)
1430 # authenticate with password and us-signin endpoint
1431 response = client.post(
1432 "/us-signin",
1433 data=dict(identity="[email protected]", passcode="awesome sunset"),
1434 follow_redirects=True,
1435 )
1436 assert b"Welcome [email protected]" in response.data
1437
1438
1439 @pytest.mark.parametrize("app", v2_param, indirect=True)
1440 @pytest.mark.registerable()
1441 @pytest.mark.changeable()
1442 @pytest.mark.settings(
1443 password_required=False,
1444 us_email_template="security/email/us_instructions_test",
1445 email_html=False,
1446 )
1447 def test_change_empty_password(app, client, outbox):
1448 # test that if register w/o a password - can 'change' it.
1449 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1450
1451 data = dict(email="[email protected]", password="", password_confirm="")
1452 response = client.post("/register", data=data, follow_redirects=True)
1453 # should have been logged in since no confirmation
1454
1455 # make sure requires a fresh authentication
1456 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
1457 data = dict(
1458 password="",
1459 new_password="awesome sunset",
1460 new_password_confirm="awesome sunset",
1461 )
1462
1463 response = client.post("/change", json=data)
1464 assert response.status_code == 401
1465 assert response.json["response"]["reauth_required"]
1466
1467 client.post(
1468 "/us-verify/send-code",
1469 json=dict(identity="[email protected]", chosen_method="email"),
1470 )
1471 matcher = re.match(r".*Token:(\d+).*", outbox[1].body, re.IGNORECASE | re.DOTALL)
1472 code = matcher.group(1)
1473 response = client.post("/us-verify", json=dict(passcode=code))
1474 assert response.status_code == 200
1475
1476 response = client.get("/change", headers=headers)
1477 assert not response.json["response"]["active_password"]
1478 response = client.get("/change")
1479 assert b"You do not" in response.data
1480
1481 # now should be able to change
1482 response = client.post("/change", json=data)
1483 assert response.status_code == 200
1484 logout(client)
1485
1486 response = client.post(
1487 "/login", json=dict(email="[email protected]", password="awesome sunset")
1488 )
1489 assert response.status_code == 200
1490
1491
1492 @pytest.mark.parametrize("app", v2_param, indirect=True)
1493 @pytest.mark.registerable()
1494 @pytest.mark.settings(password_required=False)
1495 def test_empty_password(app, client, get_message):
1496 # test that if no password - can't log in with empty password
1497 data = dict(email="[email protected]", password="", password_confirm="")
1498 response = client.post("/register", data=data, follow_redirects=True)
1499 logout(client)
1500
1501 response = client.post("/us-signin", json=dict(identity="[email protected]", passcode=""))
1502 assert response.status_code == 400
1503 assert response.json["response"]["field_errors"]["passcode"][0].encode(
1504 "utf-8"
1505 ) == get_message("INVALID_PASSWORD_CODE")
1506 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1507 "INVALID_PASSWORD_CODE"
1508 )
1509
1510
1511 @pytest.mark.settings(
1512 us_enabled_methods=["password"],
1513 user_identity_attributes=[
1514 {"email": {"mapper": uia_email_mapper}},
1515 {"username": {"mapper": lambda x: x}},
1516 ],
1517 )
1518 def test_regular_login(app, client, get_message):
1519 # If "password" in methods - then should be able to login with good-ol
1520 # login/password.
1521 # By having username - this also checks that we properly stop at the first
1522 # mapping.
1523 auths = []
1524
1525 @user_authenticated.connect_via(app)
1526 def authned(myapp, user, **extra_args):
1527 auths.append((user.email, extra_args["authn_via"]))
1528
1529 response = client.post(
1530 "/us-signin",
1531 data=dict(identity="[email protected]", passcode="password", remember=True),
1532 follow_redirects=True,
1533 )
1534 assert response.status_code == 200
1535 assert client.get_cookie("remember_token")
1536 assert "password" in auths[0][1]
1537 assert is_authenticated(client, get_message)
1538
1539
1540 @pytest.mark.settings(
1541 us_enabled_methods=["sms"], user_identity_attributes=UIA_EMAIL_PHONE
1542 )
1543 def test_regular_login_disallowed(app, client, get_message):
1544 # If "password" not in methods - then should not be able to use password
1545 response = client.post(
1546 "/us-signin",
1547 data=dict(identity="[email protected]", passcode="password", remember=True),
1548 follow_redirects=True,
1549 )
1550 assert get_message("INVALID_PASSWORD_CODE") in response.data
1551
1552
1553 @pytest.mark.two_factor()
1554 @pytest.mark.settings(two_factor_required=True)
1555 def test_tf(app, client, get_message):
1556 # Test basic two-factor - default for signing in with password.
1557 response = client.post(
1558 "/us-signin",
1559 data=dict(identity="[email protected]", passcode="password", remember=True),
1560 follow_redirects=True,
1561 )
1562 assert response.status_code == 200
1563 message = b"Two-Factor authentication adds an extra layer of security"
1564 assert message in response.data
1565 assert b"Set up using SMS" in response.data
1566
1567 sms_sender = SmsSenderFactory.createSender("test")
1568 data = dict(setup="sms", phone="+442083661177")
1569 response = client.post("/tf-setup", data=data, follow_redirects=True)
1570 assert b"Enter code to complete setup" in response.data
1571 code = sms_sender.messages[0].split()[-1]
1572
1573 response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
1574 assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data
1575
1576
1577 @pytest.mark.two_factor()
1578 @pytest.mark.settings(two_factor_required=True)
1579 def test_tf_link(app, client, get_message, outbox):
1580 # Verify two-factor required when using magic link
1581 set_email(app)
1582 response = client.post(
1583 "/us-signin/send-code",
1584 data=dict(identity="[email protected]", chosen_method="email"),
1585 follow_redirects=True,
1586 )
1587 assert response.status_code == 200
1588 assert b"Sign In" in response.data
1589
1590 matcher = re.match(
1591 r".*(http://[^\s*]*).*", outbox[0].body, re.IGNORECASE | re.DOTALL
1592 )
1593 magic_link = matcher.group(1)
1594 response = client.get(magic_link, follow_redirects=True)
1595 assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") not in response.data
1596 message = b"Two-Factor authentication adds an extra layer of security"
1597 assert message in response.data
1598
1599
1600 @pytest.mark.two_factor()
1601 @pytest.mark.settings(two_factor_required=True, us_mfa_required=["password"])
1602 def test_tf_link_not_email(app, client, get_message, outbox):
1603 # Verify two-factor not required when using magic link and us_mfa_required set
1604 auths = []
1605
1606 @user_authenticated.connect_via(app)
1607 def authned(myapp, user, **extra_args):
1608 auths.append((user.email, extra_args["authn_via"]))
1609
1610 set_email(app)
1611 response = client.post(
1612 "/us-signin/send-code",
1613 data=dict(identity="[email protected]", chosen_method="email"),
1614 follow_redirects=True,
1615 )
1616 assert response.status_code == 200
1617 assert b"Sign In" in response.data
1618
1619 matcher = re.match(
1620 r".*(http://[^\s*]*).*", outbox[0].body, re.IGNORECASE | re.DOTALL
1621 )
1622 magic_link = matcher.group(1)
1623 client.get(magic_link, follow_redirects=True)
1624 assert "email" in auths[0][1]
1625 assert is_authenticated(client, get_message)
1626
1627
1628 @pytest.mark.two_factor()
1629 @pytest.mark.settings(
1630 two_factor_required=True,
1631 redirect_host="localhost:8081",
1632 redirect_behavior="spa",
1633 login_error_view="/login-error",
1634 )
1635 def test_tf_link_spa(app, client, get_message, outbox):
1636 # Verify two-factor required when using magic link and SPA
1637 # This currently isn't supported and should redirect to an error.
1638 set_email(app)
1639 response = client.post(
1640 "/us-signin/send-code",
1641 data=dict(identity="[email protected]", chosen_method="email"),
1642 follow_redirects=True,
1643 )
1644 assert response.status_code == 200
1645 assert b"Sign In" in response.data
1646
1647 matcher = re.match(
1648 r".*(http://[^\s*]*).*", outbox[0].body, re.IGNORECASE | re.DOTALL
1649 )
1650 magic_link = matcher.group(1)
1651 response = client.get(magic_link, follow_redirects=False)
1652 split = urlsplit(response.location)
1653 assert "localhost:8081" == split.netloc
1654 assert "/login-error" == split.path
1655 qparams = dict(parse_qsl(split.query))
1656 assert qparams["tf_required"] == "1"
1657 assert qparams["email"] == "[email protected]"
1658
1659
1660 @pytest.mark.two_factor()
1661 @pytest.mark.settings(
1662 two_factor_required=True, user_identity_attributes=UIA_EMAIL_PHONE
1663 )
1664 def test_tf_not(app, client, get_message):
1665 # Test basic two-factor - when first factor doesn't require second (e.g. SMS)
1666 # 1. sign in and setup TFA
1667 client.post(
1668 "/us-signin",
1669 data=dict(identity="[email protected]", passcode="password", remember=True),
1670 follow_redirects=True,
1671 )
1672
1673 sms_sender = SmsSenderFactory.createSender("test")
1674 data = dict(setup="sms", phone="+442083661177")
1675 client.post("/tf-setup", data=data, follow_redirects=True)
1676 code = sms_sender.messages[0].split()[-1]
1677 client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
1678
1679 # 2. setup unified sign in with SMS
1680 response = client.post(
1681 "us-setup", data=dict(chosen_method="sms", phone="650-555-1212")
1682 )
1683 verify_url = get_form_action(response, 1)
1684 code = sms_sender.messages[0].split()[-1].strip(".")
1685 response = client.post(verify_url, data=dict(passcode=code), follow_redirects=True)
1686 assert response.status_code == 200
1687 assert get_message("US_SETUP_SUCCESSFUL") in response.data
1688
1689 # 3. logout
1690 logout(client)
1691
1692 # 4. sign in with SMS - should not require TFA
1693 client.post(
1694 "/us-signin/send-code",
1695 data=dict(identity="[email protected]", chosen_method="sms"),
1696 follow_redirects=True,
1697 )
1698
1699 code = sms_sender.messages[0].split()[-1].strip(".")
1700 response = client.post(
1701 "/us-signin",
1702 data=dict(identity="6505551212", passcode=code),
1703 follow_redirects=True,
1704 )
1705 assert response.status_code == 200
1706 # assert "sms" in auths[1][1]
1707
1708 # Verify authenticated
1709 assert is_authenticated(client, get_message)
1710
1711
1712 @pytest.mark.settings(sms_service="bad")
1713 def test_bad_sender(app, client, get_message):
1714 # If SMS sender fails - make sure propagated
1715 # Test form, json, x signin, setup
1716 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1717
1718 set_phone(app)
1719 data = dict(identity="[email protected]", chosen_method="sms")
1720 response = client.post("/us-signin/send-code", data=data, follow_redirects=True)
1721 assert get_message("FAILED_TO_SEND_CODE") in response.data
1722
1723 response = client.post("us-signin/send-code", json=data, headers=headers)
1724 assert response.status_code == 500
1725 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1726 "FAILED_TO_SEND_CODE"
1727 )
1728
1729 # Now test setup
1730 set_email(app)
1731 us_authenticate(client)
1732 data = dict(chosen_method="sms", phone="650-555-1212")
1733 response = client.post("us-setup", data=data)
1734 assert get_message("FAILED_TO_SEND_CODE") in response.data
1735
1736 response = client.post("us-setup", json=data, headers=headers)
1737 assert response.status_code == 500
1738 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1739 "FAILED_TO_SEND_CODE"
1740 )
1741
1742 # Test us-verify
1743 data = dict(chosen_method="sms")
1744 response = client.post("/us-verify/send-code", data=data)
1745 assert get_message("FAILED_TO_SEND_CODE") in response.data
1746 response = client.post("us-verify/send-code", json=data)
1747 assert response.status_code == 500
1748 assert response.json["response"]["field_errors"]["chosen_method"][0].encode(
1749 "utf-8"
1750 ) == get_message("FAILED_TO_SEND_CODE")
1751
1752
1753 def _send_code(self, method, **kwargs):
1754 assert method == "sms"
1755 return "NO SMS AVAILABLE"
1756
1757
1758 @pytest.mark.app_settings(TESTING_USER_INJECT=dict(us_send_security_token=_send_code))
1759 @pytest.mark.registerable()
1760 def test_replace_send_code(app, client, get_message):
1761 set_phone(app, "[email protected]")
1762 data = dict(identity="[email protected]", chosen_method="sms")
1763 response = client.post("/us-signin/send-code", data=data, follow_redirects=True)
1764 assert b"NO SMS AVAILABLE" in response.data
1765
1766
1767 @pytest.mark.settings(us_enabled_methods=["password"])
1768 def test_only_passwd(app, client, get_message):
1769 authenticate(client)
1770 response = client.get("us-setup")
1771 assert b"No method" in response.data
1772
1773 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1774 response = client.get("us-setup", headers=headers)
1775 assert response.json["response"]["available_methods"] == ["password"]
1776 assert not response.json["response"]["setup_methods"]
1777
1778
1779 @pytest.mark.settings(us_enabled_methods=["password", "authenticator"])
1780 def test_passwd_and_authenticator(app, client, get_message):
1781 authenticate(client)
1782 response = client.get("us-setup")
1783 assert b"authenticator app" in response.data
1784
1785 # Check that we get QRcode URL and no 'code sent'
1786 response = client.post("us-setup", data=dict(chosen_method="authenticator"))
1787 assert response.status_code == 200
1788 assert b"Code has been sent" not in response.data
1789 assert b"Open an authenticator app" in response.data
1790 # verify png QRcode is present
1791 assert b"data:image/svg+xml;base64," in response.data
1792
1793 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1794 response = client.get("us-setup", headers=headers)
1795 assert response.json["response"]["available_methods"] == [
1796 "password",
1797 "authenticator",
1798 ]
1799 assert response.json["response"]["setup_methods"] == ["authenticator"]
1800
1801
1802 def test_totp_generation(app, client, get_message):
1803 # Test that we generate a new totp on each setup of a different method
1804 # and that on failure to validate, the secret is NOT changed in the DB
1805 # and on successful validation, it is.
1806 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1807
1808 authenticate(client, email="[email protected]")
1809 with app.app_context():
1810 user = app.security.datastore.find_user(email="[email protected]")
1811 ts = app.security.datastore.us_get_totp_secrets(user)
1812 assert "authenticator" not in ts
1813
1814 response = client.post(
1815 "us-setup", json=dict(chosen_method="authenticator"), headers=headers
1816 )
1817 assert response.status_code == 200
1818 jr = response.json["response"]
1819 assert jr["authr_issuer"] == "tests"
1820 assert jr["authr_username"] == "[email protected]"
1821 assert "authr_key" in response.json["response"]
1822 assert len(jr["authr_b32key"]) % 8 == 0 and re.match(
1823 r"^[A-Z2-7]+=*$", jr["authr_b32key"]
1824 )
1825 assert (
1826 jr["authr_uri"]
1827 == f"otpauth://totp/tests:[email protected]?secret={jr['authr_b32key']}&issuer=tests"
1828 )
1829
1830 state = response.json["response"]["state"]
1831
1832 # Generate token from passed totp_secret and confirm setup
1833 totp_key = response.json["response"]["authr_key"]
1834 totp = TOTP(totp_key)
1835 code = totp.generate().token
1836
1837 response = client.post(
1838 "/us-setup/" + state, json=dict(passcode=code), headers=headers
1839 )
1840 assert response.status_code == 200
1841 assert response.json["response"]["chosen_method"] == "authenticator"
1842
1843 # success - totp_secret in DB should have been saved
1844 with app.app_context():
1845 user = app.security.datastore.find_user(email="[email protected]")
1846 ts = app.security.datastore.us_get_totp_secrets(user)
1847 assert (
1848 app.security._totp_factory.get_totp_pretty_key(ts["authenticator"])
1849 == totp_key
1850 )
1851
1852 # Now setup SMS and verify that authenticator totp hasn't changed
1853 sms_sender = SmsSenderFactory.createSender("test")
1854 response = client.post(
1855 "us-setup",
1856 json=dict(chosen_method="sms", phone="650-555-1212"),
1857 headers=headers,
1858 )
1859 assert response.status_code == 200
1860 code = sms_sender.messages[0].split()[-1].strip(".")
1861 state = response.json["response"]["state"]
1862 response = client.post(
1863 "/us-setup/" + state, json=dict(passcode=code), headers=headers
1864 )
1865 assert response.status_code == 200
1866 assert response.json["response"]["chosen_method"] == "sms"
1867 assert response.json["response"]["phone"] == "+16505551212"
1868
1869 # make sure authenticator totp hasn't changed.
1870 with app.app_context():
1871 user = app.security.datastore.find_user(email="[email protected]")
1872 ts = app.security.datastore.us_get_totp_secrets(user)
1873 assert (
1874 app.security._totp_factory.get_totp_pretty_key(ts["authenticator"])
1875 == totp_key
1876 )
1877
1878 # Ok - setup again - but send invalid code - check totp in DB didn't change.
1879 response = client.post(
1880 "us-setup", json=dict(chosen_method="authenticator"), headers=headers
1881 )
1882 assert response.status_code == 200
1883 state = response.json["response"]["state"]
1884 totp_key = response.json["response"]["authr_key"]
1885
1886 # validate with wrong code
1887 response = client.post(
1888 "/us-setup/" + state, json=dict(passcode=123345), headers=headers
1889 )
1890 assert response.status_code == 400
1891
1892 # Make sure totp_secret in DB didn't change
1893 with app.app_context():
1894 user = app.security.datastore.find_user(email="[email protected]")
1895 ts = app.security.datastore.us_get_totp_secrets(user)
1896 assert (
1897 app.security._totp_factory.get_totp_pretty_key(ts["authenticator"])
1898 != totp_key
1899 )
1900
1901
1902 @pytest.mark.two_factor()
1903 @pytest.mark.settings(
1904 two_factor_required=True,
1905 user_identity_attributes=UIA_EMAIL_PHONE,
1906 two_factor_always_validate=False,
1907 )
1908 def test_us_tf_validity(app, client, get_message):
1909 us_tf_authenticate(app, client, remember=True)
1910 assert client.get_cookie(app.config["SECURITY_TWO_FACTOR_VALIDITY_COOKIE_NAME"])
1911 logout(client)
1912 # logout does NOT remove this cookie
1913 assert client.get_cookie(app.config["SECURITY_TWO_FACTOR_VALIDITY_COOKIE_NAME"])
1914
1915 # This time shouldn't require code
1916 data = dict(identity="[email protected]", passcode="password")
1917 response = client.post("/us-signin", json=data)
1918 assert response.json["meta"]["code"] == 200
1919 assert is_authenticated(client, get_message)
1920 logout(client)
1921
1922 data = dict(identity="[email protected]", passcode="password")
1923 response = client.post("/us-signin", data=data, follow_redirects=True)
1924 assert b"Please enter your authentication code" in response.data
1925
1926 response = client.post(
1927 "/us-signin",
1928 json=data,
1929 follow_redirects=True,
1930 headers={"Content-Type": "application/json"},
1931 )
1932 assert response.status_code == 200
1933 assert response.json["response"]["tf_primary_method"] == "authenticator"
1934 assert response.json["response"]["tf_required"]
1935 assert response.json["response"]["tf_state"] == "ready"
1936
1937
1938 @pytest.mark.webauthn(webauthn_util_cls=HackWebauthnUtil)
1939 def test_us_verify_wan(app, client, get_message):
1940 # test get correct options when requiring a reauthentication and have wan keys
1941 # setup.
1942 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1943
1944 reg_2_keys(client)
1945
1946 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
1947 response = client.get("us-setup", headers=headers)
1948 assert response.status_code == 401
1949 assert response.json["response"]["reauth_required"]
1950 assert response.json["response"]["has_webauthn_verify_credential"]
1951
1952 # the us-verify form should have the webauthn verify form attached
1953 response = client.get("us-verify")
1954 assert b'action="/wan-verify"' in response.data
1955
1956 app.config["SECURITY_WAN_ALLOW_AS_VERIFY"] = None
1957 response = client.get("us-setup", headers=headers)
1958 assert response.status_code == 401
1959 assert response.json["response"]["reauth_required"]
1960 assert not response.json["response"]["has_webauthn_verify_credential"]
1961
1962 # the us-verify form should NOT have the webauthn verify form attached
1963 response = client.get("us-verify")
1964 assert b'action="/wan-verify"' not in response.data
1965
1966
1967 def test_setup_delete(app, client, get_message):
1968 set_email(app)
1969 us_authenticate(client)
1970 response = client.get("us-setup")
1971 # Email should be in delete options since we just set that up.
1972 assert all(
1973 i in response.data
1974 for i in [b"delete_method-0", b"chosen_method-0", b"chosen_method-1"]
1975 )
1976 response = client.post("us-setup", data=dict(delete_method="email"))
1977
1978 response = client.get("us-setup")
1979 # All should be in possible setups.
1980 assert all(
1981 i in response.data
1982 for i in [b"chosen_method-0", b"chosen_method-1", b"chosen_method-2"]
1983 )
1984
1985 response = client.post("us-setup", json=dict(delete_method="email"))
1986 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1987 "US_METHOD_NOT_AVAILABLE"
1988 )
1989
1990
1991 def test_setup_delete_json(app, client, get_message):
1992 recorded = []
1993
1994 @us_profile_changed.connect_via(app)
1995 def pc(sender, user, methods, delete, **kwargs):
1996 if "sms" in methods:
1997 if delete:
1998 assert not user.us_phone_number
1999 recorded.append("delete")
2000 else:
2001 assert user.us_phone_number == "+16505551212"
2002 recorded.append("setup")
2003
2004 headers = {"Accept": "application/json", "Content-Type": "application/json"}
2005 set_email(app)
2006 us_authenticate(client)
2007 response = client.get("us-setup", headers=headers)
2008 # Email should be in delete options since we just set that up.
2009 assert "email" in response.json["response"]["active_methods"]
2010
2011 response = client.post("us-setup", json=dict(delete_method="email"))
2012 assert response.status_code == 200
2013
2014 response = client.get("us-setup", headers=headers)
2015 assert response.json["response"]["active_methods"] == ["password"]
2016
2017 response = client.post("us-setup", json=dict(delete_method="email"))
2018 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
2019 "US_METHOD_NOT_AVAILABLE"
2020 )
2021
2022 # setup and delete SMS
2023 sms_sender = SmsSenderFactory.createSender("test")
2024 response = client.post(
2025 "us-setup",
2026 json=dict(chosen_method="sms", phone="650-555-1212"),
2027 headers=headers,
2028 )
2029 assert response.status_code == 200
2030 state = response.json["response"]["state"]
2031 assert state
2032 code = sms_sender.messages[0].split()[-1].strip(".")
2033 response = client.post(
2034 "/us-setup/" + state, json=dict(passcode=code), headers=headers
2035 )
2036 assert response.status_code == 200
2037 assert response.json["response"]["chosen_method"] == "sms"
2038 assert response.json["response"]["phone"] == "+16505551212"
2039
2040 # verify SMS in active methods
2041 response = client.get("/us-setup", headers=headers)
2042 assert response.status_code == 200
2043 assert set(response.json["response"]["active_methods"]) == {"sms", "password"}
2044
2045 # delete SMS
2046 response = client.post("/us-setup", json=(dict(delete_method="sms")))
2047 assert response.status_code == 200
2048 response = client.get("/us-setup", headers=headers)
2049 assert response.json["response"]["active_methods"] == ["password"]
2050 assert recorded[0] == "setup"
2051 assert recorded[1] == "delete"
2052
2053
2054 def test_setup_delete_multi_json(app, client, get_message):
2055 recorded = []
2056
2057 @us_profile_changed.connect_via(app)
2058 def pc(sender, user, methods, delete, **kwargs):
2059 recorded.append((delete, methods))
2060
2061 headers = {"Accept": "application/json", "Content-Type": "application/json"}
2062 set_email(app)
2063 set_phone(app)
2064 us_authenticate(client)
2065 response = client.get("us-setup", headers=headers)
2066 # Email and sms should be in delete options since we just set that up.
2067 assert set(response.json["response"]["active_methods"]) == {
2068 "sms",
2069 "password",
2070 "email",
2071 }
2072
2073 response = client.post("us-setup", json=dict(delete_method=["email", "sms"]))
2074 assert response.status_code == 200
2075
2076 response = client.get("us-setup", headers=headers)
2077 assert response.json["response"]["active_methods"] == ["password"]
2078 assert len(recorded) == 1
2079 assert set(recorded[0][1]) == {"sms", "email"}
2080
2081
2082 @pytest.mark.settings(return_generic_responses=True)
2083 def test_generic_response(app, client, get_message):
2084 # test not-setup choice
2085 data = dict(identity="[email protected]", chosen_method="email")
2086 response = client.post("/us-signin/send-code", data=data, follow_redirects=True)
2087 assert get_message("GENERIC_US_SIGNIN") in response.data
2088
2089 # for JSON still return 200 as if everything is fine and a code was sent.
2090 response = client.post("/us-signin/send-code", json=data)
2091 assert response.status_code == 200
2092 assert not any(e in response.json["response"].keys() for e in ["error", "errors"])
2093
2094 # Correct method should return same thing
2095 set_phone(app)
2096 data = dict(identity="[email protected]", chosen_method="sms")
2097 response = client.post("/us-signin/send-code", data=data, follow_redirects=True)
2098 assert get_message("GENERIC_US_SIGNIN") in response.data
2099
2100 # for JSON still return 200 as if everything is fine and a code was sent.
2101 response = client.post("/us-signin/send-code", json=data)
2102 assert response.status_code == 200
2103 assert not any(
2104 e in response.json["response"].keys() for e in ["field_errors", "errors"]
2105 )
2106
2107 # Unknown identity should return same thing
2108 data = dict(identity="[email protected]", chosen_method="email")
2109 response = client.post("/us-signin/send-code", data=data, follow_redirects=True)
2110 assert get_message("GENERIC_US_SIGNIN") in response.data
2111
2112 # for JSON still return 200 as if everything is fine and a code was sent.
2113 response = client.post("/us-signin/send-code", json=data)
2114 assert response.status_code == 200
2115 assert not any(
2116 e in response.json["response"].keys() for e in ["field_errors", "errors"]
2117 )
2118
2119 #
2120 # Now test us-signin itself
2121 #
2122 data = dict(identity="[email protected]", code="12345")
2123 response = client.post("/us-signin", data=data)
2124 assert get_message("GENERIC_AUTHN_FAILED") in response.data
2125
2126 data = dict(identity="[email protected]", code="12345")
2127 response = client.post("/us-signin", json=data)
2128 assert response.status_code == 400
2129 assert list(response.json["response"]["field_errors"].keys()) == [""]
2130 assert len(response.json["response"]["field_errors"][""]) == 1
2131 assert response.json["response"]["field_errors"][""][0].encode(
2132 "utf-8"
2133 ) == get_message("GENERIC_AUTHN_FAILED")
2134 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
2135 "GENERIC_AUTHN_FAILED"
2136 )
2137
2138 # same with unknown user
2139 data = dict(identity="[email protected]", code="12345")
2140 response = client.post("/us-signin", data=data)
2141 assert get_message("GENERIC_AUTHN_FAILED") in response.data
2142
2143 data = dict(identity="[email protected]", code="12345")
2144 response = client.post("/us-signin", json=data)
2145 assert response.status_code == 400
2146 assert list(response.json["response"]["field_errors"].keys()) == [""]
2147 assert len(response.json["response"]["field_errors"][""]) == 1
2148 assert response.json["response"]["field_errors"][""][0].encode(
2149 "utf-8"
2150 ) == get_message("GENERIC_AUTHN_FAILED")
2151 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
2152 "GENERIC_AUTHN_FAILED"
2153 )
2154
2155 #
2156 # Test /us-verify-link
2157 #
2158 set_email(app)
2159 with capture_send_code_requests() as requests:
2160 response = client.post(
2161 "/us-signin/send-code",
2162 data=dict(identity="[email protected]", chosen_method="email"),
2163 follow_redirects=True,
2164 )
2165
2166 uid = requests[0]["user"].fs_uniquifier
2167 code = requests[0]["login_token"]
2168
2169 # Try bad/unknown id
2170 response = client.get("us-verify-link?id=98765&code=12345", follow_redirects=True)
2171 assert get_message("GENERIC_AUTHN_FAILED") in response.data
2172
2173 # Try bad code
2174 response = client.get(
2175 f"us-verify-link?id={uid}&code=12345",
2176 follow_redirects=True,
2177 )
2178 assert get_message("GENERIC_AUTHN_FAILED") in response.data
2179
2180 # Try deactivated user
2181 with app.test_request_context("/"):
2182 user = app.security.datastore.find_user(email="[email protected]")
2183 app.security.datastore.deactivate_user(user)
2184 app.security.datastore.commit()
2185 response = client.get(
2186 f"us-verify-link?id={uid}&code={code}",
2187 follow_redirects=True,
2188 )
2189 assert get_message("GENERIC_AUTHN_FAILED") in response.data
2190
2191
2192 @pytest.mark.settings(url_prefix="/auth", us_signin_replaces_login=True)
2193 def test_propagate_next(app, client):
2194 # verify we propagate the ?next param all the way through a unified signin
2195 # Also test blueprint prefix since we rarely actually test that.
2196 set_phone(app)
2197 with capture_send_code_requests() as codes:
2198 response = client.get("profile", follow_redirects=True)
2199 assert "?next=/profile" in response.request.url
2200 signin_url = get_form_action(response, 0)
2201 sendcode_url = get_form_action(response, 1)
2202 response = client.post(
2203 sendcode_url, data=dict(identity="[email protected]", chosen_method="sms")
2204 )
2205 data = dict(identity="[email protected]", passcode=codes[0]["login_token"])
2206 response = client.post(signin_url, data=data, follow_redirects=False)
2207 assert "/profile" in response.location
2208
2209
2210 @pytest.mark.two_factor()
2211 @pytest.mark.settings(url_prefix="/auth", us_signin_replaces_login=True)
2212 def test_propagate_next_tf(app, client):
2213 # test next is propagated with a second factor
2214 response = client.post(
2215 "/auth/login", json=dict(identity="[email protected]", passcode="password")
2216 )
2217 sms_sender = setup_tf_sms(client, url_prefix=app.config["SECURITY_URL_PREFIX"])
2218 logout(client, endpoint="/auth/logout")
2219
2220 response = client.get("/profile", follow_redirects=True)
2221 assert "?next=/profile" in response.request.url
2222 signin_url = get_form_action(response, 0)
2223 response = client.post(
2224 signin_url,
2225 data=dict(identity="[email protected]", passcode="password"),
2226 follow_redirects=True,
2227 )
2228 sendcode_url = get_form_action(response, 0)
2229 response = client.post(
2230 sendcode_url,
2231 data=dict(code=sms_sender.messages[0].split()[-1]),
2232 follow_redirects=True,
2233 )
2234 assert b"Profile Page" in response.data
2235
2236 # Try form.next
2237 logout(client, endpoint="/auth/logout")
2238
2239 response = client.post(
2240 "/auth/us-signin",
2241 data=dict(identity="[email protected]", passcode="password", next="/im-in"),
2242 follow_redirects=True,
2243 )
2244 sendcode_url = get_form_action(response, 0)
2245 response = client.post(
2246 sendcode_url,
2247 data=dict(code=sms_sender.messages[0].split()[-1]),
2248 follow_redirects=False,
2249 )
2250 assert "/im-in" in response.location
2251
2252
2253 @pytest.mark.babel(babel_default_locale="cic_US", test_xlations=True)
2254 def test_xlation(app, client, get_message_local):
2255 # Test setup method translation
2256 set_email(app)
2257 us_authenticate(client)
2258 response = client.get("us-setup")
2259
2260 with app.test_request_context():
2261 assert markupsafe.escape("SMS").encode() in response.data
2262 p = [
2263 "Currently active sign in options: email OKAY!, password OKAY!. OKAY!",
2264 "Currently active sign in options: password OKAY!, email OKAY!. OKAY!",
2265 ]
2266 assert any(markupsafe.escape(s).encode() in response.data for s in p)
2267
2268
2269 @pytest.mark.registerable()
2270 @pytest.mark.settings(password_required=False)
2271 @pytest.mark.babel(babel_default_locale="cic_US", test_xlations=True)
2272 def test_empty_password_xlate(app, client, get_message):
2273 # test that if no password (and no other setup method) we get correct xlated
2274 # template
2275 data = dict(email="[email protected]", password="", password_confirm="")
2276 # register w/o password - this will automatically set up 'email'
2277 client.post("/register", data=data, follow_redirects=True)
2278 # will be auto-logged in since no confirmation
2279
2280 response = client.get("us-setup")
2281 with app.test_request_context():
2282 assert (
2283 markupsafe.escape(
2284 "Currently active sign in options: email OKAY!. OKAY!"
2285 ).encode()
2286 in response.data
2287 )
2288
2289 # white-box testing - there are 2 places in us-setup code that set active methods
2290 response = client.post("us-setup", data=dict(delete_method="email"))
2291 with app.test_request_context():
2292 assert (
2293 markupsafe.escape(
2294 "Currently active sign in options: none OKAY!. OKAY!"
2295 ).encode()
2296 in response.data
2297 )
2298
2299 response = client.get("us-setup")
2300 with app.test_request_context():
2301 assert (
2302 markupsafe.escape(
2303 "Currently active sign in options: none OKAY!. OKAY!"
2304 ).encode()
2305 in response.data
2306 )
2307
2308
2309 @pytest.mark.two_factor()
2310 @pytest.mark.csrf(csrfprotect=True)
2311 @pytest.mark.settings(CSRF_COOKIE_NAME="XSRF-Token")
2312 def test_csrf_2fa_us_cookie(app, client):
2313 # Use XSRF-Token cookie for entire login sequence
2314 sms_sender = SmsSenderFactory.createSender("test")
2315 response = client.get(
2316 "/us-signin", data={}, headers={"Content-Type": "application/json"}
2317 )
2318 assert client.get_cookie("XSRF-Token")
2319 csrf_token = response.json["response"]["csrf_token"]
2320 assert csrf_token == client.get_cookie("XSRF-Token").value
2321
2322 # verify requires CSRF
2323 response = client.post(
2324 "/us-signin",
2325 json=dict(identity="[email protected]", passcode="password"),
2326 headers={"Content-Type": "application/json"},
2327 )
2328 assert response.status_code == 400
2329 assert response.json["response"]["errors"][0] == "The CSRF token is missing."
2330
2331 response = client.post(
2332 "/us-signin",
2333 json=dict(identity="[email protected]", passcode="password"),
2334 headers={
2335 "Content-Type": "application/json",
2336 "X-CSRF-Token": client.get_cookie("XSRF-Token").value,
2337 },
2338 )
2339 assert b'"code": 200' in response.data
2340 session = get_session(response)
2341 assert session["tf_state"] == "ready"
2342
2343 assert sms_sender.get_count() == 1
2344 code = sms_sender.messages[0].split()[-1]
2345
2346 response = client.post(
2347 "/tf-validate",
2348 json=dict(code=code),
2349 headers={
2350 "Content-Type": "application/json",
2351 "X-CSRF-Token": client.get_cookie("XSRF-Token").value,
2352 },
2353 )
2354 assert response.status_code == 200
2355
2356 # verify original session csrf_token still works.
2357 response = client.post(
2358 "/json_auth",
2359 json=dict(label="label"),
2360 headers={"Content-Type": "application/json", "X-CSRF-Token": csrf_token},
2361 )
2362 assert response.status_code == 200
2363
2364 # use XSRF_Cookie to send in csrf_token
2365 response = client.post(
2366 "/json_auth",
2367 json=dict(label="label"),
2368 headers={
2369 "Content-Type": "application/json",
2370 "X-CSRF-Token": client.get_cookie("XSRF-Token").value,
2371 },
2372 )
2373 assert response.status_code == 200
2374 assert response.json["label"] == "label"
2375
2376
2377 @pytest.mark.settings(us_enabled_methods=["password", "email"])
2378 def test_us_setup_email(app, client, get_message):
2379 set_email(app)
2380 us_authenticate(client)
2381 chosen_methods_choices = []
2382
2383 def recorder(template, us_setup_form, **kwargs):
2384 chosen_methods_choices.extend(us_setup_form.chosen_method.choices)
2385 return "ok"
2386
2387 app.security.render_template = recorder
2388
2389 client.get("/us-setup")
2390
2391 assert len(chosen_methods_choices) == 0
2392
2393
2394 @pytest.mark.settings(us_enabled_methods=["email", "authenticator"])
2395 def test_us_setup_authenticator(app, client, get_message):
2396 set_email(app)
2397 us_authenticate(client)
2398 chosen_methods_choices = []
2399
2400 def recorder(template, us_setup_form, **kwargs):
2401 chosen_methods_choices.extend(us_setup_form.chosen_method.choices)
2402 return "ok"
2403
2404 app.security.render_template = recorder
2405
2406 client.get("/us-setup")
2407
2408 assert len(chosen_methods_choices) == 1
2409 assert chosen_methods_choices[0][0] == "authenticator"
2410
2411
2412 @pytest.mark.settings(us_enabled_methods=["email", "sms"])
2413 def test_us_setup_sms(app, client, get_message):
2414 set_email(app)
2415 us_authenticate(client)
2416 chosen_methods_choices = []
2417
2418 def recorder(template, us_setup_form, **kwargs):
2419 chosen_methods_choices.extend(us_setup_form.chosen_method.choices)
2420 return "ok"
2421
2422 app.security.render_template = recorder
2423
2424 client.get("/us-setup")
2425
2426 assert len(chosen_methods_choices) == 1
2427 assert chosen_methods_choices[0][0] == "sms"
2428
2429
2430 @pytest.mark.settings(us_enabled_methods=["email", "sms", "authenticator"])
2431 def test_us_setup_authenticator_sms(app, client, get_message):
2432 set_email(app)
2433 us_authenticate(client)
2434 chosen_methods_choices = []
2435
2436 def recorder(template, us_setup_form, **kwargs):
2437 chosen_methods_choices.extend(us_setup_form.chosen_method.choices)
2438 return "ok"
2439
2440 app.security.render_template = recorder
2441
2442 client.get("/us-setup")
2443
2444 assert len(chosen_methods_choices) == 2
2445 assert chosen_methods_choices[0][0] == "authenticator"
2446 assert chosen_methods_choices[1][0] == "sms"
2447
2448
2449 def _tf_required(self, tf_setup_methods, tf_fresh):
2450 if self.email == "[email protected]":
2451 return False, tf_setup_methods
2452 return True, tf_setup_methods
2453
2454
2455 @pytest.mark.two_factor()
2456 @pytest.mark.app_settings(TESTING_USER_INJECT=dict(check_tf_required=_tf_required))
2457 @pytest.mark.settings(two_factor_required=True)
2458 def test_override_tf_required(app, client, get_message):
2459 data = dict(identity="[email protected]", passcode="password")
2460 response = client.post("/us-signin", json=data)
2461 assert response.status_code == 200
2462 assert response.json["response"]["tf_required"]
2463
2464 data = dict(identity="[email protected]", passcode="password")
2465 response = client.post("/us-signin", json=data)
2466 assert response.status_code == 200
2467 assert not response.json["response"]["tf_required"]
2468
2469
2470 def _locked(self, form_error):
2471 if self.email == "[email protected]":
2472 form_error.append("You are not allowed to do that")
2473 return True
2474 return False
2475
2476
2477 @pytest.mark.app_settings(TESTING_USER_INJECT=dict(is_locked=_locked))
2478 def test_override_user_locked(app, client, get_message):
2479 data = dict(identity="[email protected]", passcode="password")
2480 response = client.post("/us-signin", json=data)
2481 assert response.status_code == 200
2482 logout(client)
2483
2484 data = dict(identity="[email protected]", passcode="password")
2485 response = client.post("/us-signin", json=data)
2486 assert response.status_code == 400
2487 assert response.json["response"]["errors"] == ["You are not allowed to do that"]
2488 assert response.json["response"]["field_errors"]["identity"] == [
2489 "You are not allowed to do that"
2490 ]
2491
2492
2493 @pytest.mark.app_settings(TESTING_USER_INJECT=dict(is_locked=_locked))
2494 @pytest.mark.settings(return_generic_responses=True)
2495 def test_override_user_locked_gr(app, client, get_message):
2496 data = dict(identity="[email protected]", passcode="password")
2497 response = client.post("/us-signin", json=data)
2498 assert response.status_code == 400
2499 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
2500 "GENERIC_AUTHN_FAILED"
2501 )
2502 assert "identity" not in response.json["response"]["field_errors"]
2503
2504
2505 @pytest.mark.settings(default_remember_me=True)
2506 def test_remember_login_form(app, client):
2507 # ensure form has the checkbox set if default set.
2508 response = client.get("/us-signin")
2509 assert response.status_code == 200
2510 r = get_form_input(response, "remember")
2511 assert "checked" in r