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