Debian Codegraph @

tests/test_webauthn.py

raw
1 """
2 test_webauthn
3 ~~~~~~~~~~~~~~~~~~~
4
5 WebAuthn tests
6
7 :copyright: (c) 2021-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9
10 """
11
12 from base64 import urlsafe_b64encode
13 import copy
14 import datetime
15 import json
16 import re
17
18 import pytest
19
20 from tests.test_two_factor import tf_in_session
21 from tests.test_utils import (
22 FakeSerializer,
23 authenticate,
24 capture_flashes,
25 check_location,
26 get_existing_session,
27 get_form_action,
28 get_form_input_value,
29 is_authenticated,
30 json_authenticate,
31 logout,
32 reset_fresh,
33 setup_tf_sms,
34 verify_token,
35 check_signals,
36 get_form_input,
37 )
38
39 from flask_security import (
40 WebauthnUtil,
41 user_authenticated,
42 wan_registered,
43 wan_deleted,
44 )
45
46 # We can't/don't test the actual client-side JavaScript and browser APIs - so
47 # to create reproducible tests, use view_scaffold, set breakpoints in the views and
48 # cut-and-paste the responses. That requires that 'challenge' and 'rp_origin' be
49 # identical between view_scaffold and tests here.
50 CHALLENGE = "smCCiy_k2CqQydSQ_kPEjV5a2d0ApfatcpQ1aXDmQPo"
51 REG_DATA1 = {
52 "id": "wUUqNOjY35dcT-vpikZpZx-T91NjIe4PqrV8j7jYPOc",
53 "rawId": "wUUqNOjY35dcT-vpikZpZx-T91NjIe4PqrV8j7jYPOc",
54 "type": "public-key",
55 "response": {
56 "attestationObject": "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVikSZYN5YgOjGh0NB"
57 "cPZHZgW4_krrmihjLHmVzzuoMdl2NFAAAAAQAAAAAAAAAAAAAAAAAAA"
58 "AAAIMFFKjTo2N-XXE_r6YpGaWcfk_dTYyHuD6q1fI-42DznpQECAy"
59 "YgASFYIFRipoWMEiDuCtLUvSlqCFZBqxvUuNqZKavlWgvN2BK8Il"
60 "ggLOV4eez9k0det5oIZGyKanGkmWa0hygnjjFmf8Rep6c",
61 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiYzIxR"
62 "FEybDVYMnN5UTNGUmVXUlRVVjlyVUVWcVZqVmhNbVF3UVhCbVlYUmpjRk"
63 "V4WVZoRWJWRlFidyIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6NT"
64 "AwMSIsImNyb3NzT3JpZ2luIjpmYWxzZX0",
65 "transports": ["usb"],
66 },
67 "extensions": '{"credProps": {}}',
68 }
69 SIGNIN_DATA1 = {
70 "id": "wUUqNOjY35dcT-vpikZpZx-T91NjIe4PqrV8j7jYPOc",
71 "rawId": "wUUqNOjY35dcT-vpikZpZx-T91NjIe4PqrV8j7jYPOc",
72 "type": "public-key",
73 "response": {
74 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MBAAAABQ==",
75 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYzIxRFEy"
76 "bDVYMnN5UTNGUmVXUlRVVjlyVUVWcVZqVmhNbVF3UVhCbVlYUmpjRkV4"
77 "WVZoRWJWRlFidyIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTAw"
78 "MSIsImNyb3NzT3JpZ2luIjpmYWxzZX0=",
79 "signature": "MEUCIH5VdRXxfnoxfrVk72gvWAn91QH-l2UrIohk5YOWi9XpAiEAn6f9oHtFS"
80 "68HVf6K_Ku0L33C0sID2HzpJWSiTNgJlbU=",
81 },
82 "assertionClientExtensions": "{}",
83 }
84 REG_DATA2 = {
85 "id": "lpMv8FTVHVSxteQJ3N4azlSxXiBJADA7IK-NleETceZYODy51_Cqt7Rx6pfVP1BI",
86 "rawId": "lpMv8FTVHVSxteQJ3N4azlSxXiBJADA7IK-NleETceZYODy51_Cqt7Rx6pfVP1BI",
87 "type": "public-key",
88 "response": {
89 "attestationObject": "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVjCSZYN5YgOj"
90 "Gh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2PFAAAAAgAAAAAAAAAAA"
91 "AAAAAAAAAAAMJaTL_BU1R1UsbXkCdzeGs5UsV4gSQAwOyCvjZXhE3"
92 "HmWDg8udfwqre0ceqX1T9QSKUBAgMmIAEhWCCWky_wVNUdVL"
93 "G15AncLU8mBQCtY10BjnSDoOUlRjkU1CJYIIA1U9vNDpZ"
94 "TihC2x0CxRZ-trF_zazYosuEqYdHSOIjZoWtjcmVkUHJvdGVjdAI",
95 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoi"
96 "YzIxRFEybDVYMnN5UTNGUmVXUlRVVjlyVUVWcVZqVmhNbVF3UV"
97 "hCbVlYUmpjRkV4WVZoRWJWRlFidyIsIm9yaWdpbiI6Imh0dHA6L"
98 "y9sb2NhbGhvc3Q6NTAwMSIsImNyb3NzT3JpZ2luIjpmYWxzZX0",
99 "transports": ["nfc", "usb"],
100 },
101 "extensions": '{"credProps": {"rk": True}}',
102 }
103
104 # This has user_verification=True - i.e. a multi-factor capable key
105 REG_DATA_UV = {
106 "id": "s3xZpfGy0ZH-sSkfxIsgChwbkw_O0jOFtZeJ1LXUMEa8atG1oEskNqmFJCfgKZGy",
107 "rawId": "s3xZpfGy0ZH-sSkfxIsgChwbkw_O0jOFtZeJ1LXUMEa8atG1oEskNqmFJCfgKZGy",
108 "type": "public-key",
109 "response": {
110 "attestationObject": "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVjC"
111 "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2PFAAAABAAAAA"
112 "AAAAAAAAAAAAAAAAAAMLN8WaXxstGR_rEpH8SLIAocG5MPztIzhbWXi"
113 "dS11DBGvGrRtaBLJDaphSQn4CmRsqUBAgMmIAEhWCCzfFml8bLRkf"
114 "6xKR_EUnaoI333MuxRlv5-LwojDibdTyJYIFMifFwn-RfkDDgsTHF"
115 "jWgE6bld-Jc4nhFMTkQja9P8IoWtjcmVkUHJvdGVjdAI",
116 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiYzI"
117 "xRFEybDVYMnN5UTNGUmVXUlRVVjlyVUVWcVZqVmhNbVF3UVhCbVlY"
118 "UmpjRkV4WVZoRWJWRlFidyIsIm9yaWdpbiI6Imh0dHA6Ly9sb2Nhb"
119 "Ghvc3Q6NTAwMSIsImNyb3NzT3JpZ2luIjpmYWxzZX0",
120 "transports": ["nfc", "usb"],
121 },
122 "extensions": '{"credProps":{"rk":true}}',
123 }
124
125 SIGNIN_DATA_UV = {
126 "id": "s3xZpfGy0ZH-sSkfxIsgChwbkw_O0jOFtZeJ1LXUMEa8atG1oEskNqmFJCfgKZGy",
127 "rawId": "s3xZpfGy0ZH-sSkfxIsgChwbkw_O0jOFtZeJ1LXUMEa8atG1oEskNqmFJCfgKZGy",
128 "type": "public-key",
129 "response": {
130 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==",
131 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYzIxRFEy"
132 "bDVYMnN5UTNGUmVXUlRVVjlyVUVWcVZqVmhNbVF3UVhCbVlYUmpjRkV4W"
133 "VZoRWJWRlFidyIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTAwMSI"
134 "sImNyb3NzT3JpZ2luIjpmYWxzZX0=",
135 "signature": "MEUCIQDR0m9Ob4nqVGiAPUf1Tu5XohDh2frl1LJ6G41GURlUIgIgKUPfkw"
136 "AjP2863L2nDhcR2EKqoGEQLqlQ5xymZstyO6o=",
137 },
138 "assertionClientExtensions": "{}",
139 }
140
141 REG_DATA_UH = {
142 "id": "rHb1OXVM--dgGcWg0u3cfomyc-Tu4l4kK8GjVkS8bms-foXmBAlWHyTzuhgGgCnx",
143 "rawId": "rHb1OXVM--dgGcWg0u3cfomyc-Tu4l4kK8GjVkS8bms-foXmBAlWHyTzuhgGgCnx",
144 "type": "public-key",
145 "response": {
146 "attestationObject": "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVjCSZYN5YgOjGh0NBc"
147 "PZHZgW4_krrmihjLHmVzzuoMd"
148 "l2PFAAAAAgAAAAAAAAAAAAAAAAAAAAAAMKx29Tl1TPvnYBnFoNLt3H6J"
149 "snPk7uJeJCvBo1ZEvG5rPn6F"
150 "5gQJVh8k87oYBoAp8aUBAgMmIAEhWCCsdvU5dUz752AZxaDSyN-ocBL"
151 "Bo99GevEWTnUxSkMRICJYIILE"
152 "DLF8cQNM5l6ZgDxIYpvU88xgbq44lmR6oCBbNaHhoWtjcmVkUHJvdG"
153 "VjdAI",
154 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiYzIx"
155 "RFEybDVYMnN5UTNGUmVXUlRVVjl"
156 "yVUVWcVZqVmhNbVF3UVhCbVlYUmpjRkV4WVZoRWJWRlFidyIsIm9yaWdpbi"
157 "I6Imh0dHA6Ly9sb2NhbGhvc3"
158 "Q6NTAwMSIsImNyb3NzT3JpZ2luIjpmYWxzZX0",
159 "transports": ["nfc", "usb"],
160 },
161 "extensions": '{"credProps":{"rk": true}}',
162 }
163 SIGNIN_DATA_UH = {
164 "id": "rHb1OXVM--dgGcWg0u3cfomyc-Tu4l4kK8GjVkS8bms-foXmBAlWHyTzuhgGgCnx",
165 "rawId": "rHb1OXVM--dgGcWg0u3cfomyc-Tu4l4kK8GjVkS8bms-foXmBAlWHyTzuhgGgCnx",
166 "type": "public-key",
167 "response": {
168 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==",
169 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYzIxRFEy"
170 "bDVYMnN5UTNGUmVXUlRVVjlyVUVWcVZqVmhNbVF3UVhCbVlYUmpjR"
171 "kV4WVZoRWJWRlFidyIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q"
172 "6NTAwMSIsImNyb3NzT3JpZ2luIjpmYWxzZX0=",
173 "signature": "MEUCIQCbKwaQv_GzrWfc0nVXqhe6WZs_5Sb2b7xHC9iDW9aHeQIgF2PlfM7FdyV"
174 "xcPhofekJjLBgDMTbK4mwIWHgiExZ54s=",
175 "userHandle": "NTgxMTU3YmM2MGU3NGM1OTg0OTBjYTI1ZTgwNjc4MDY=",
176 },
177 "assertionClientExtensions": "{}",
178 }
179
180
181 class HackWebauthnUtil(WebauthnUtil):
182 def generate_challenge(self, nbytes=None):
183 return CHALLENGE
184
185 def origin(self):
186 # This is from view_scaffold
187 return "http://localhost:5001"
188
189
190 pytestmark = pytest.mark.webauthn(webauthn_util_cls=HackWebauthnUtil)
191
192
193 def _register_start(
194 client, name="testr1", usage="secondary", endpoint="wan-register", csrf_token=None
195 ):
196 response = client.post(
197 endpoint, data=dict(name=name, usage=usage, csrf_token=csrf_token)
198 )
199 matcher = re.match(
200 r".*handleRegister\(\'(.*)\'\).*",
201 response.data.decode("utf-8"),
202 re.IGNORECASE | re.DOTALL,
203 )
204 register_options = json.loads(matcher.group(1))
205 response_url = get_form_action(response)
206 return register_options, response_url
207
208
209 def _register_start_json(client, name="testr1", usage="secondary", csrf_token=None):
210 response = client.post(
211 "wan-register", json=dict(name=name, usage=usage, csrf_token=csrf_token)
212 )
213 register_options = response.json["response"]["credential_options"]
214 response_url = f'wan-register/{response.json["response"]["wan_state"]}'
215 return register_options, response_url
216
217
218 def reg_2_keys(client):
219 # Register 2 keys - one first, one secondary
220 # This can be used by other tests outside this module.
221 authenticate(client)
222 register_options, response_url = _register_start_json(
223 client, name="first", usage="first"
224 )
225 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA_UV)))
226 assert response.status_code == 200
227
228 register_options, response_url = _register_start_json(
229 client, name="second", usage="secondary"
230 )
231 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
232 assert response.status_code == 200
233
234 return {
235 "first": {"id": REG_DATA_UV["id"], "signin": SIGNIN_DATA_UV},
236 "secondary": {"id": REG_DATA1["id"], "signin": SIGNIN_DATA1},
237 }
238
239
240 def reg_first_key(client, csrf_token=None):
241 # Register a primary key - assumes already authenticated
242 # This can be used by other tests outside this module.
243 register_options, response_url = _register_start_json(
244 client, name="first", usage="first", csrf_token=csrf_token
245 )
246 response = client.post(
247 response_url,
248 json=dict(credential=json.dumps(REG_DATA_UV), csrf_token=csrf_token),
249 )
250 assert response.status_code == 200
251 return {"id": REG_DATA_UV["id"], "signin": SIGNIN_DATA_UV}
252
253
254 def _signin_start(
255 client,
256 identity=None,
257 endpoint="wan-signin",
258 csrf_token=None,
259 ):
260 response = client.post(
261 endpoint, data=dict(identity=identity, csrf_token=csrf_token)
262 )
263 matcher = re.match(
264 r".*handleSignin\(\'(.*)\'\).*",
265 response.data.decode("utf-8"),
266 re.IGNORECASE | re.DOTALL,
267 )
268 signin_options = json.loads(matcher.group(1))
269 response_url = get_form_action(response)
270 return signin_options, response_url
271
272
273 def _signin_start_json(client, identity=None, remember=False, endpoint="wan-signin"):
274 headers = {"Accept": "application/json", "Content-Type": "application/json"}
275
276 response = client.post(
277 endpoint, headers=headers, json=dict(identity=identity, remember=remember)
278 )
279 signin_options = response.json["response"]["credential_options"]
280 response_url = f'wan-signin/{response.json["response"]["wan_state"]}'
281 return signin_options, response_url, response.json
282
283
284 def wan_signin(client, identity, signin_data, wan_signin_url):
285 # perform complete sign in - useful for tests outside this module.
286 signin_options, response_url = _signin_start(
287 client, identity, endpoint=wan_signin_url
288 )
289 response = client.post(
290 response_url,
291 data=dict(credential=json.dumps(signin_data)),
292 follow_redirects=True,
293 )
294 assert response.status_code == 200
295 return response
296
297
298 def reset_signcount(app, email, keyname):
299 # Due to replay attack prevention, we can only use a key once since the server
300 # increments the sign_count and we can't do that on the client side!
301 with app.app_context():
302 user = app.security.datastore.find_user(email=email)
303 cred = [c for c in user.webauthn if c.name == keyname][0]
304 cred.sign_count = cred.sign_count - 1
305 app.security.datastore.put(cred)
306 app.security.datastore.commit()
307
308
309 def test_basic(app, clients, get_message):
310 auths = []
311
312 @user_authenticated.connect_via(app)
313 def authned(myapp, user, **extra_args):
314 auths.append((user.email, extra_args["authn_via"]))
315
316 @wan_registered.connect_via(app)
317 def pc(sender, user, name, **extra_args):
318 assert name == "testr1"
319 assert len(user.webauthn) == 1
320
321 authenticate(clients)
322
323 response = clients.get("/wan-register")
324 # default config allows for both primary and secondary usage
325 # so form should have selector
326 assert get_form_input_value(response, "usage-0")
327 assert get_form_input_value(response, "usage-1")
328
329 # post with no name
330 response = clients.post("/wan-register", data=dict())
331 assert get_message("WEBAUTHN_NAME_REQUIRED") in response.data
332
333 register_options, response_url = _register_start(clients, usage="first")
334 assert register_options["rp"]["name"] == "My Flask App"
335 assert register_options["user"]["name"] == "[email protected]"
336 assert not register_options["excludeCredentials"]
337 assert register_options["authenticatorSelection"]["residentKey"] == "preferred"
338 assert register_options["extensions"]["credProps"]
339
340 # Register using the static data above
341 response = clients.post(
342 response_url, data=dict(credential=json.dumps(REG_DATA1)), follow_redirects=True
343 )
344 assert response.status_code == 200
345 assert get_message("WEBAUTHN_REGISTER_SUCCESSFUL", name="testr1") in response.data
346 assert b"testr1" in response.data
347
348 # sign in - simple case use identity so we get back allowCredentials
349 logout(clients)
350 signin_options, response_url = _signin_start(clients, "[email protected]")
351 assert signin_options["timeout"] == app.config["SECURITY_WAN_SIGNIN_TIMEOUT"]
352 assert signin_options["userVerification"] == "preferred"
353 allow_credentials = signin_options["allowCredentials"]
354 assert len(allow_credentials) == 1
355 assert allow_credentials[0]["id"] == REG_DATA1["id"]
356 assert allow_credentials[0]["transports"] == ["usb"]
357
358 response = clients.post(
359 response_url,
360 data=dict(credential=json.dumps(SIGNIN_DATA1)),
361 follow_redirects=True,
362 )
363 assert response.status_code == 200
364 assert b"Welcome [email protected]" in response.data
365 assert len(auths) == 2
366 assert auths[1][1] == ["webauthn"]
367
368 # verify actually logged in
369 response = clients.get("/profile", follow_redirects=False)
370 assert response.status_code == 200
371
372
373 def test_basic_json(app, clients, get_message):
374 headers = {"Accept": "application/json", "Content-Type": "application/json"}
375
376 auths = []
377
378 @user_authenticated.connect_via(app)
379 def authned(myapp, user, **extra_args):
380 auths.append((user.email, extra_args["authn_via"]))
381
382 authenticate(clients)
383
384 # post with no name
385 response = clients.post("/wan-register", json=dict())
386 assert response.status_code == 400
387 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
388 "WEBAUTHN_NAME_REQUIRED"
389 )
390
391 register_options, response_url = _register_start_json(clients, usage="first")
392 assert register_options["rp"]["name"] == "My Flask App"
393 assert register_options["user"]["name"] == "[email protected]"
394
395 # Register using the static data above
396 response = clients.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
397 assert response.status_code == 200
398
399 # reset lastuse_datetime so we can verify signing in correctly alters it
400 fake_dt = datetime.datetime(2020, 4, 7, 9, 27)
401 with app.app_context():
402 user = app.security.datastore.find_user(email="[email protected]")
403 for cred in user.webauthn:
404 cred.lastuse_datetime = fake_dt
405 app.security.datastore.put(cred)
406 app.security.datastore.commit()
407 if hasattr(app.security.datastore.db, "close_db") and callable(
408 app.security.datastore.db.close_db
409 ):
410 app.security.datastore.db.close_db(None)
411
412 response = clients.get("/wan-register", headers=headers)
413 active_creds = response.json["response"]["registered_credentials"]
414 assert active_creds[0]["name"] == "testr1"
415 assert datetime.datetime.fromisoformat(active_creds[0]["lastuse"]) == fake_dt
416
417 # sign in - simple case use identity so we get back allowCredentials
418 logout(clients)
419 signin_options, response_url, rjson = _signin_start_json(clients, "[email protected]")
420 assert signin_options["userVerification"] == "preferred"
421 allow_credentials = signin_options["allowCredentials"]
422 assert len(allow_credentials) == 1
423 assert allow_credentials[0]["id"] == REG_DATA1["id"]
424 assert "user" not in rjson["response"]
425
426 response = clients.post(
427 f"{response_url}?include_auth_token",
428 json=dict(credential=json.dumps(SIGNIN_DATA1)),
429 )
430 assert response.status_code == 200
431 assert response.json["response"]["user"]["email"] == "[email protected]"
432 assert auths[1][1] == ["webauthn"]
433
434 # verify actually logged in
435 assert is_authenticated(clients, get_message)
436 verify_token(clients, response.json["response"]["user"]["authentication_token"])
437
438 # fetch credentials and verify lastuse was updated
439 response = clients.get("/wan-register", headers=headers)
440 active_creds = response.json["response"]["registered_credentials"]
441 assert datetime.datetime.fromisoformat(active_creds[0]["lastuse"]) != fake_dt
442 assert active_creds[0]["transports"] == ["usb"]
443 assert active_creds[0]["usage"] == "first"
444
445 logout(clients)
446 # verify that unknown identities are just ignored when USER_HINTS is True
447 response = clients.post("/wan-signin", json=dict(identity="[email protected]"))
448 assert response.status_code == 200
449
450
451 @pytest.mark.settings(wan_allow_user_hints=False)
452 def test_basic_json_nohints(app, client, get_message):
453 # Test that with no hints allowed, we don't get any credentials and we can still
454 # sign in.
455 authenticate(client)
456 register_options, response_url = _register_start_json(client, usage="first")
457 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
458 assert response.status_code == 200
459 # With no hints we default to requiring a resident key
460 # With allow as primary we default to requiring a cross-platform key
461 assert (
462 register_options["authenticatorSelection"]["authenticatorAttachment"]
463 == "cross-platform"
464 )
465 assert register_options["authenticatorSelection"]["residentKey"] == "required"
466 logout(client)
467
468 signin_options, response_url, rjson = _signin_start_json(client, "[email protected]")
469 allow_credentials = signin_options["allowCredentials"]
470 assert len(allow_credentials) == 0
471 assert "user" not in rjson["response"]
472
473 response = client.post(
474 response_url,
475 json=dict(credential=json.dumps(SIGNIN_DATA1)),
476 )
477 assert response.status_code == 200
478 assert response.json["response"]["user"]["email"] == "[email protected]"
479
480
481 def test_usage(app, client, get_message):
482 authenticate(client)
483 register_options, response_url = _register_start_json(client, usage="secondary")
484 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
485 assert response.status_code == 200
486 logout(client)
487
488 signin_options, response_url, _ = _signin_start_json(client, "[email protected]")
489 response = client.post(
490 response_url,
491 json=dict(credential=json.dumps(SIGNIN_DATA1)),
492 )
493 assert response.status_code == 400
494 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
495 "WEBAUTHN_CREDENTIAL_WRONG_USAGE"
496 )
497
498
499 def test_constraints(app, clients, get_message):
500 """Test that nickname is unique for a given user but different users
501 can have the same nickname.
502 Also that credential_id is unique across the app.
503 """
504 authenticate(clients)
505 register_options, response_url = _register_start_json(clients, name="testr3")
506 response = clients.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
507 assert response.status_code == 200
508
509 # register same name again
510 response = clients.post("wan-register", json=dict(name="testr3"))
511 assert response.status_code == 400
512 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
513 "WEBAUTHN_NAME_INUSE", name="testr3"
514 )
515
516 logout(clients)
517
518 # Different user - should get credential id in use error
519 authenticate(clients, email="[email protected]")
520 register_options, response_url = _register_start_json(clients, name="testr3")
521 response = clients.post(response_url, json=dict(credential=json.dumps(REG_DATA2)))
522 assert response.status_code == 200
523
524 # Try to register with identical credential ID as other user
525 register_options, response_url = _register_start_json(clients, name="testr4")
526 response = clients.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
527 assert response.status_code == 400
528 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
529 "WEBAUTHN_CREDENTIAL_ID_INUSE"
530 )
531
532
533 def test_bad_data_register(app, client, get_message):
534 authenticate(client)
535 register_options, response_url = _register_start_json(client, name="testr3")
536
537 # first try mangling json - should get API_ERROR
538 response = client.post(response_url, json=dict(credential='"hi there"'))
539 assert response.status_code == 400
540 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
541 "API_ERROR"
542 )
543 response = client.post(response_url, json=dict(credential=""))
544 assert response.status_code == 400
545 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
546 "API_ERROR"
547 )
548
549 # Now pass incorrect keys
550 bad_register = copy.deepcopy(REG_DATA1)
551 del bad_register["rawId"]
552 response = client.post(response_url, json=dict(credential=json.dumps(bad_register)))
553 assert response.status_code == 400
554 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
555 "API_ERROR"
556 )
557
558 # now muck with attestation - should get VERIFY ERROR
559 bad_register = copy.deepcopy(REG_DATA1)
560 bad_register["rawId"] = "unknown"
561 response = client.post(response_url, json=dict(credential=json.dumps(bad_register)))
562 assert response.status_code == 400
563 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
564 "WEBAUTHN_NO_VERIFY", cause="id and raw_id were not equivalent"
565 )
566
567 # same with forms
568 with capture_flashes() as flashes:
569 response = client.post(
570 response_url,
571 data=dict(credential=json.dumps(bad_register)),
572 follow_redirects=False,
573 )
574 assert response.status_code in [302, 303]
575 assert "/wan-register" in response.location
576 assert flashes[0]["category"] == "error"
577 assert flashes[0]["message"].encode("utf-8") == get_message(
578 "WEBAUTHN_NO_VERIFY", cause="id and raw_id were not equivalent"
579 )
580
581
582 def test_bad_data_signin(app, client, get_message, signals):
583 authenticate(client)
584 register_options, response_url = _register_start_json(client, usage="first")
585 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
586 assert response.status_code == 200
587
588 logout(client)
589 signin_options, response_url, _ = _signin_start_json(client, "[email protected]")
590 response = client.post(response_url, json=dict(credential='"hi there"'))
591 assert response.status_code == 400
592 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
593 "API_ERROR"
594 )
595 response = client.post(response_url, json=dict(credential=""))
596 assert response.status_code == 400
597 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
598 "API_ERROR"
599 )
600
601 # Now pass incorrect keys
602 bad_signin = copy.deepcopy(SIGNIN_DATA1)
603 del bad_signin["rawId"]
604 response = client.post(response_url, json=dict(credential=json.dumps(bad_signin)))
605 assert response.status_code == 400
606 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
607 "API_ERROR"
608 )
609
610 # now muck with attestation - should get VERIFY ERROR
611 bad_signin = copy.deepcopy(SIGNIN_DATA1)
612 bad_signin["response"]["signature"] = bad_signin["response"]["signature"].replace(
613 "M", "N"
614 )
615 response = client.post(response_url, json=dict(credential=json.dumps(bad_signin)))
616 assert response.status_code == 400
617 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
618 "WEBAUTHN_NO_VERIFY", cause="Could not verify authentication signature"
619 )
620 assert (
621 signals["user_failed_authn"][0]["request_endpoint"]
622 == "security.wan_signin_response"
623 )
624 assert signals["user_failed_authn"][0]["user"].email == "[email protected]"
625 assert signals["user_failed_authn"][0]["auth_type"] == "passkey"
626 assert not signals["user_failed_authn"][0]["tfa"]
627 check_signals(
628 signals, ["user_failed_authn", "wan_registered", "user_authenticated"]
629 )
630
631
632 def test_delete(app, clients, get_message):
633 @wan_deleted.connect_via(app)
634 def pc(sender, user, name, **extra_args):
635 assert name == "testr3"
636 assert len(user.webauthn) == 1
637
638 authenticate(clients)
639 register_options, response_url = _register_start(clients, name="testr3")
640 response = clients.post(
641 response_url, data=dict(credential=json.dumps(REG_DATA1)), follow_redirects=True
642 )
643 assert response.status_code == 200
644 assert get_message("WEBAUTHN_REGISTER_SUCCESSFUL", name="testr3") in response.data
645
646 response = clients.get("/wan-register")
647 assert b"testr3" in response.data
648
649 # Make sure GET works - this is important if we get a freshness redirect when
650 # attempting to delete - the verify endpoint will redirect back to here.
651 response = clients.get("/wan-delete", follow_redirects=False)
652 assert response.status_code in [302, 303]
653
654 """
655 response = clients.post("/wan-delete")
656 assert get_message("WEBAUTHN_NAME_REQUIRED") in response.data
657 """
658
659 response = clients.post(
660 "/wan-delete", data=dict(name="testr1"), follow_redirects=True
661 )
662 assert get_message("WEBAUTHN_NAME_NOT_FOUND", name="testr1") in response.data
663
664 with capture_flashes() as flashes:
665 response = clients.post(
666 "/wan-delete", data=dict(name="testr3"), follow_redirects=True
667 )
668 assert flashes[0]["category"] == "info"
669 assert flashes[0]["message"].encode("utf-8") == get_message(
670 "WEBAUTHN_CREDENTIAL_DELETED", name="testr3"
671 )
672 response = clients.get("/wan-register")
673 assert b"testr3" not in response.data
674
675
676 def test_delete_json(app, clients, get_message):
677 headers = {"Accept": "application/json", "Content-Type": "application/json"}
678
679 authenticate(clients)
680 register_options, response_url = _register_start_json(clients, name="testr3")
681 response = clients.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
682 assert response.status_code == 200
683
684 response = clients.get("/wan-register", headers=headers)
685 active_creds = response.json["response"]["registered_credentials"]
686 assert active_creds[0]["name"] == "testr3"
687
688 response = clients.post("/wan-delete", json=dict())
689 assert response.status_code == 400
690 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
691 "WEBAUTHN_NAME_REQUIRED"
692 )
693
694 response = clients.post("/wan-delete", json=dict(name="testr1"))
695 assert response.status_code == 400
696 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
697 "WEBAUTHN_NAME_NOT_FOUND", name="testr1"
698 )
699
700 response = clients.post("/wan-delete", json=dict(name="testr3"))
701 assert response.status_code == 200
702
703
704 def test_disabled_account(app, client, get_message):
705 # With USER_HINTS enabled, should get 200 on initial signin POST, but
706 # not receive a list of registered credentials.
707 authenticate(client)
708
709 register_options, response_url = _register_start_json(
710 client, name="testr3", usage="first"
711 )
712 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
713 assert response.status_code == 200
714 logout(client)
715
716 with app.test_request_context("/"):
717 user = app.security.datastore.find_user(email="[email protected]")
718 app.security.datastore.deactivate_user(user)
719 app.security.datastore.commit()
720
721 signin_options, response_url = _signin_start(client, "[email protected]")
722 assert response.status_code == 200
723 allow_credentials = signin_options["allowCredentials"]
724 assert len(allow_credentials) == 0
725
726 # Now set USER_HINTS false and should get 400 on second POST
727 app.config["SECURITY_WAN_ALLOW_USER_HINTS"] = False
728
729 # Identity should be ignored
730 signin_options, response_url = _signin_start(client, "[email protected]")
731 allow_credentials = signin_options["allowCredentials"]
732 assert len(allow_credentials) == 0
733
734 response = client.post(
735 response_url,
736 json=dict(credential=json.dumps(SIGNIN_DATA1)),
737 )
738 assert response.status_code == 400
739 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
740 "DISABLED_ACCOUNT"
741 )
742
743
744 def _locked(self, form_error):
745 if self.email == "[email protected]":
746 from flask import request
747
748 if request.endpoint != "security.login":
749 form_error.append("You are not allowed to do that")
750 return True
751 return False
752
753
754 @pytest.mark.app_settings(TESTING_USER_INJECT=dict(is_locked=_locked))
755 def test_override_user_locked(app, client, get_message):
756 authenticate(client, email="[email protected]")
757 register_options, response_url = _register_start_json(
758 client, name="testr3", usage="first"
759 )
760 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
761 logout(client)
762
763 signin_options, response_url, _ = _signin_start_json(client, "[email protected]")
764 response = client.post(
765 response_url,
766 json=dict(credential=json.dumps(SIGNIN_DATA1)),
767 )
768 assert response.status_code == 400
769 assert response.json["response"]["errors"] == ["You are not allowed to do that"]
770 assert response.json["response"]["field_errors"]["credential"] == [
771 "You are not allowed to do that"
772 ]
773
774
775 def test_unk_credid(app, client, get_message):
776 authenticate(client)
777
778 register_options, response_url = _register_start_json(
779 client, name="testr3", usage="first"
780 )
781 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
782 assert response.status_code == 200
783 logout(client)
784
785 signin_options, response_url, _ = _signin_start_json(client, "[email protected]")
786 assert len(signin_options["allowCredentials"]) == 1
787
788 bad_signin = copy.deepcopy(SIGNIN_DATA1)
789 bad_signin["rawId"] = bad_signin["rawId"].replace("w", "d")
790
791 response = client.post(
792 response_url,
793 json=dict(credential=json.dumps(bad_signin)),
794 )
795 assert response.status_code == 400
796 assert response.json["response"]["field_errors"]["credential"][0].encode(
797 "utf-8"
798 ) == get_message("WEBAUTHN_UNKNOWN_CREDENTIAL_ID")
799
800 # same with forms
801 with capture_flashes() as flashes:
802 response = client.post(
803 response_url,
804 data=dict(credential=json.dumps(bad_signin)),
805 follow_redirects=False,
806 )
807 assert response.status_code in [302, 303]
808 assert "/wan-signin" in response.location
809 assert flashes[0]["category"] == "error"
810 assert flashes[0]["message"].encode("utf-8") == get_message(
811 "WEBAUTHN_UNKNOWN_CREDENTIAL_ID"
812 )
813
814
815 @pytest.mark.settings(wan_allow_as_first_factor=False)
816 def test_no_first_factor(app, client, get_message):
817 # make sure that is app not configured to allow a webauthn key as a 'first'
818 # authenticator, that the endpoint 'disappears'.
819 authenticate(client)
820
821 register_options, response_url = _register_start_json(client, name="testr3")
822 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
823 assert response.status_code == 200
824 logout(client)
825
826 response = client.post("wan-signin", json=dict(identity="[email protected]"))
827 assert response.status_code == 404
828
829
830 @pytest.mark.two_factor()
831 @pytest.mark.unified_signin()
832 def test_tf(app, client, get_message):
833 # Test using webauthn key as a second factor
834 # Register 2 keys - one "first" one "secondary"
835 keys = reg_2_keys(client)
836 logout(client)
837
838 # log back in - should require MFA.
839 response = client.post(
840 "/us-signin",
841 data=dict(identity="[email protected]", passcode="password", remember=True),
842 follow_redirects=True,
843 )
844 assert response.status_code == 200
845 assert b"Use a Passkey as a Second Factor" in response.data
846 # we should have a wan key available
847 assert b'action="/wan-signin' in response.data
848
849 # verify NOT logged in
850 response = client.get("/profile", follow_redirects=False)
851 assert "/login" in response.location
852
853 signin_options, response_url = _signin_start(client, "[email protected]")
854 assert len(signin_options["allowCredentials"]) == 1
855 assert signin_options["allowCredentials"][0]["id"] == keys["secondary"]["id"]
856 response = client.post(
857 response_url,
858 json=dict(credential=json.dumps(keys["secondary"]["signin"])),
859 )
860 assert response.status_code == 200
861
862 # verify actually logged in
863 response = client.get("/profile", follow_redirects=False)
864 assert response.status_code == 200
865
866
867 @pytest.mark.two_factor()
868 @pytest.mark.unified_signin()
869 def test_tf_json(app, client, get_message):
870 # Test using webauthn key as a second factor
871 # Register 2 keys - one "first" one "secondary"
872 keys = reg_2_keys(client)
873 logout(client)
874
875 # log back in - should require MFA.
876 response = client.post(
877 "/us-signin",
878 json=dict(identity="[email protected]", passcode="password", remember=True),
879 )
880 assert response.status_code == 200
881 assert response.json["response"]["tf_method"] == "webauthn"
882 assert response.json["response"]["tf_required"]
883 assert response.json["response"]["tf_state"] == "ready"
884 assert response.json["response"]["tf_signin_url"] == "/wan-signin"
885
886 # verify NOT logged in
887 response = client.get("/profile", headers={"accept": "application/json"})
888 assert response.status_code == 401
889
890 # For secondary, identity is stored in session
891 signin_options, response_url, _ = _signin_start_json(client, "")
892 assert len(signin_options["allowCredentials"]) == 1
893 assert signin_options["allowCredentials"][0]["id"] == keys["secondary"]["id"]
894 response = client.post(
895 response_url,
896 json=dict(credential=json.dumps(keys["secondary"]["signin"])),
897 )
898 assert response.status_code == 200
899
900 # verify actually logged in
901 response = client.get("/profile", headers={"accept": "application/json"})
902 assert response.status_code == 200
903
904
905 @pytest.mark.two_factor()
906 @pytest.mark.settings(two_factor_always_validate=False)
907 def test_tf_validity_window(app, client, get_message):
908 # Test with a two-factor validity setting - we don't get re-prompted.
909 authenticate(client)
910 assert not client.get_cookie("tf_validity")
911 register_options, response_url = _register_start_json(client)
912 client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
913 logout(client)
914
915 # login - should require second factor
916 response = client.post(
917 "/login",
918 data=dict(email="[email protected]", password="password"),
919 follow_redirects=True,
920 )
921 assert b"Use a Passkey as a Second Factor" in response.data
922 with client.session_transaction() as session:
923 assert "tf_user_id" in session
924
925 signin_options, response_url = _signin_start(client, "[email protected]")
926 response = client.post(response_url, json=dict(credential=json.dumps(SIGNIN_DATA1)))
927 assert response.status_code == 200
928
929 # verify actually logged in
930 response = client.get("/profile", follow_redirects=False)
931 assert response.status_code == 200
932 reset_signcount(app, "[email protected]", "testr1")
933 logout(client)
934
935 # since we didn't specify 'remember' previously - should still require 2FA
936 response = client.post(
937 "/login",
938 data=dict(email="[email protected]", password="password", remember=True),
939 follow_redirects=True,
940 )
941 assert b"Use a Passkey as a Second Factor" in response.data
942
943 signin_options, response_url = _signin_start(client, "[email protected]")
944 response = client.post(response_url, json=dict(credential=json.dumps(SIGNIN_DATA1)))
945 assert response.status_code == 200
946 assert client.get_cookie("tf_validity")
947 logout(client)
948
949 # since we did specify 'remember' previously - should not require 2FA
950 response = client.post(
951 "/login",
952 data=dict(email="[email protected]", password="password"),
953 follow_redirects=True,
954 )
955 # verify actually logged in
956 response = client.get("/profile", follow_redirects=False)
957 assert response.status_code == 200
958
959 # Since logged in all tf related attributes in session should be gone.
960 assert not tf_in_session(get_existing_session(client))
961
962
963 @pytest.mark.two_factor()
964 @pytest.mark.settings(two_factor_always_validate=False)
965 def test_tf_validity_window_json(app, client, get_message):
966 # Test with a two-factor validity setting - we don't get re-prompted.
967 # This also relies on the tf_validity_cookie
968 json_authenticate(client)
969 register_options, response_url = _register_start_json(client)
970 client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
971 logout(client)
972
973 response = client.post(
974 "/login", json=dict(email="[email protected]", password="password", remember=True)
975 )
976 assert response.status_code == 200
977 assert response.json["response"]["tf_required"]
978
979 signin_options, response_url = _signin_start(client, "[email protected]")
980 response = client.post(response_url, json=dict(credential=json.dumps(SIGNIN_DATA1)))
981 assert response.status_code == 200
982 logout(client)
983
984 # Sign in again - shouldn't require 2FA
985 response = client.post(
986 "/login",
987 json=dict(
988 email="[email protected]",
989 password="password",
990 remember=True,
991 ),
992 )
993 assert response.status_code == 200
994 response = client.get("/profile", follow_redirects=False)
995 assert response.status_code == 200
996
997
998 @pytest.mark.settings(wan_register_within="1 seconds")
999 def test_register_timeout(app, client, get_message):
1000 authenticate(client)
1001
1002 app.security.wan_serializer = FakeSerializer(1.0)
1003 register_options, response_url = _register_start_json(client, name="testr3")
1004
1005 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1006 assert response.status_code == 400
1007 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1008 "WEBAUTHN_EXPIRED", within=app.config["SECURITY_WAN_REGISTER_WITHIN"]
1009 )
1010
1011
1012 @pytest.mark.settings(wan_signin_within="2 seconds")
1013 def test_signin_timeout(app, client, get_message):
1014 authenticate(client)
1015
1016 register_options, response_url = _register_start_json(client, name="testr3")
1017 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1018 assert response.status_code == 200
1019 logout(client)
1020
1021 app.security.wan_serializer = FakeSerializer(2.0)
1022 signin_options, response_url, _ = _signin_start_json(client, "[email protected]")
1023 response = client.post(
1024 response_url,
1025 json=dict(credential=json.dumps(SIGNIN_DATA1)),
1026 )
1027 assert response.status_code == 400
1028 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1029 "WEBAUTHN_EXPIRED", within=app.config["SECURITY_WAN_SIGNIN_WITHIN"]
1030 )
1031
1032
1033 def test_bad_token(app, client, get_message):
1034 authenticate(client)
1035
1036 response = client.post("/wan-register/not a token", json=dict())
1037 assert response.status_code == 400
1038 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1039 "API_ERROR"
1040 )
1041 # same w/o json
1042 response = client.post(
1043 "/wan-register/not a token", data=dict(), follow_redirects=True
1044 )
1045 assert get_message("API_ERROR") in response.data
1046 response = client.post(
1047 "/wan-register/not a token", data=dict(), follow_redirects=False
1048 )
1049 assert "/wan-register" in response.location
1050
1051 # Test wan-verify
1052 response = client.post("/wan-verify/not a token", json=dict())
1053 assert response.status_code == 400
1054 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1055 "API_ERROR"
1056 )
1057 # same w/o json
1058 response = client.post(
1059 "/wan-verify/not a token", data=dict(), follow_redirects=True
1060 )
1061 assert get_message("API_ERROR") in response.data
1062 response = client.post(
1063 "/wan-verify/not a token", data=dict(), follow_redirects=False
1064 )
1065 assert "/wan-verify" in response.location
1066
1067 # Test signin
1068 logout(client)
1069
1070 response = client.post("/wan-signin/not a token", json=dict())
1071 assert response.status_code == 400
1072 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1073 "API_ERROR"
1074 )
1075 # same w/o json
1076 response = client.post(
1077 "/wan-signin/not a token", data=dict(), follow_redirects=True
1078 )
1079 assert get_message("API_ERROR") in response.data
1080 response = client.post(
1081 "/wan-signin/not a token", data=dict(), follow_redirects=False
1082 )
1083 assert "/wan-signin" in response.location
1084
1085
1086 @pytest.mark.settings(
1087 wan_register_template="custom_security/wan_register.html",
1088 wan_signin_template="custom_security/wan_signin.html",
1089 wan_verify_template="custom_security/wan_verify.html",
1090 )
1091 def test_wan_context_processors(client, app):
1092 @app.security.context_processor
1093 def default_ctx_processor():
1094 return {"global": "global"}
1095
1096 @app.security.wan_register_context_processor
1097 def register_ctx():
1098 return {"foo": "register"}
1099
1100 authenticate(client)
1101
1102 response = client.get("wan-register")
1103 assert b"CUSTOM WAN REGISTER" in response.data
1104 assert b"global" in response.data
1105 assert b"register" in response.data
1106
1107 response = client.post("wan-register", data=dict(name="[email protected]"))
1108 assert b"CUSTOM WAN REGISTER" in response.data
1109 assert b"global" in response.data
1110 assert b"register" in response.data
1111 logout(client)
1112
1113 @app.security.wan_signin_context_processor
1114 def signin_ctx():
1115 return {"foo": "signin"}
1116
1117 response = client.get("wan-signin")
1118 assert b"CUSTOM WAN SIGNIN" in response.data
1119 assert b"global" in response.data
1120 assert b"signin" in response.data
1121
1122 response = client.post("wan-signin", data=dict(name="[email protected]"))
1123 assert b"CUSTOM WAN SIGNIN" in response.data
1124 assert b"global" in response.data
1125 assert b"signin" in response.data
1126
1127 @app.security.wan_verify_context_processor
1128 def verify_ctx():
1129 return {"foo": "verify"}
1130
1131 authenticate(client)
1132 response = client.get("wan-verify")
1133 assert b"CUSTOM WAN VERIFY" in response.data
1134 assert b"global" in response.data
1135 assert b"verify" in response.data
1136
1137 response = client.post("wan-verify", data=dict(name="[email protected]"))
1138 assert b"CUSTOM WAN VERIFY" in response.data
1139 assert b"global" in response.data
1140 assert b"verify" in response.data
1141
1142
1143 @pytest.mark.two_factor()
1144 def test_alt_tf(app, client, get_message):
1145 # Use webauthn as primary and set up SMS as second factor
1146 authenticate(client)
1147
1148 register_options, response_url = _register_start_json(client, usage="first")
1149 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1150 assert response.status_code == 200
1151
1152 sms_sender = setup_tf_sms(client)
1153 logout(client)
1154
1155 # sign in using webauthn key
1156 signin_options, response_url, _ = _signin_start_json(client, "[email protected]")
1157 response = client.post(
1158 response_url,
1159 json=dict(credential=json.dumps(SIGNIN_DATA1)),
1160 )
1161 assert response.status_code == 200
1162 assert response.json["response"]["tf_required"]
1163
1164 code = sms_sender.messages[0].split()[-1]
1165 response = client.post("/tf-validate", json=dict(code=code))
1166 assert response.status_code == 200
1167 # verify logged in
1168 response = client.get("/profile", follow_redirects=False)
1169 assert response.status_code == 200
1170
1171
1172 @pytest.mark.two_factor()
1173 def test_all_in_one(app, client, get_message):
1174 # Use a key that supports user_verification - we should be able to
1175 # use that alone.
1176 authenticate(client)
1177 register_options, response_url = _register_start_json(client, usage="first")
1178 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA_UV)))
1179 assert response.status_code == 200
1180 setup_tf_sms(client)
1181
1182 logout(client)
1183 signin_options, response_url, rjson = _signin_start_json(client, "[email protected]")
1184 assert "user" not in rjson["response"]
1185 response = client.post(
1186 response_url, json=dict(credential=json.dumps(SIGNIN_DATA_UV))
1187 )
1188 assert response.json["response"]["user"]["email"] == "[email protected]"
1189
1190 # verify actually logged in
1191 response = client.get("/profile", headers={"accept": "application/json"})
1192 assert response.status_code == 200
1193
1194
1195 @pytest.mark.two_factor()
1196 def test_all_in_one_not_allowed(app, client, get_message):
1197 # now test when we don't allow a key to satisfy both factors
1198 authenticate(client)
1199 register_options, response_url = _register_start_json(client, usage="first")
1200 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA_UV)))
1201 assert response.status_code == 200
1202 setup_tf_sms(client)
1203 logout(client)
1204
1205 app.config["SECURITY_WAN_ALLOW_AS_MULTI_FACTOR"] = False
1206 signin_options, response_url, rjson = _signin_start_json(client, "[email protected]")
1207 assert "user" not in rjson["response"]
1208
1209 response = client.post(
1210 response_url, json=dict(credential=json.dumps(SIGNIN_DATA_UV))
1211 )
1212 assert response.json["response"]["tf_required"]
1213
1214
1215 def test_reset(app, client):
1216 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1217
1218 authenticate(client)
1219 register_options, response_url = _register_start_json(client)
1220 client.post(response_url, json=dict(credential=json.dumps(REG_DATA_UV)))
1221
1222 response = client.get("/wan-register", headers=headers)
1223 active_creds = response.json["response"]["registered_credentials"]
1224 assert active_creds[0]["name"] == "testr1"
1225
1226 with app.test_request_context("/"):
1227 user = app.security.datastore.find_user(email="[email protected]")
1228 app.security.datastore.webauthn_reset(user)
1229 app.security.datastore.commit()
1230
1231 response = client.get("/wan-register", headers=headers)
1232 active_creds = response.json["response"]["registered_credentials"]
1233 assert len(active_creds) == 0
1234
1235
1236 def test_user_handle(app, clients, get_message):
1237 """Test that we fail signin if user_handle doesn't match.
1238 Since we generated the SIGNIN_DATA_OH from view_scaffold - the user_handle
1239 has no way of matching.
1240 """
1241 authenticate(clients)
1242 register_options, response_url = _register_start_json(clients, usage="first")
1243 response = clients.post(response_url, json=dict(credential=json.dumps(REG_DATA_UH)))
1244 assert response.status_code == 200
1245
1246 # verify can't sign in
1247 logout(clients)
1248 signin_options, response_url, _ = _signin_start_json(clients, "[email protected]")
1249 response = clients.post(
1250 response_url, json=dict(credential=json.dumps(SIGNIN_DATA_UH))
1251 )
1252 assert response.json["response"]["field_errors"]["credential"][0].encode(
1253 "utf-8"
1254 ) == get_message("WEBAUTHN_MISMATCH_USER_HANDLE")
1255
1256 # Now change the user_handle both for the user and SIGNIN_DATA_UH
1257 with app.test_request_context("/"):
1258 user = app.security.datastore.find_user(email="[email protected]")
1259 app.security.datastore.set_webauthn_user_handle(user)
1260 app.security.datastore.commit()
1261 b64_user_handle = urlsafe_b64encode(
1262 user.fs_webauthn_user_handle.encode()
1263 ).decode("utf-8")
1264 upd_signin_data = copy.deepcopy(SIGNIN_DATA_UH)
1265 upd_signin_data["response"]["userHandle"] = b64_user_handle
1266 signin_options, response_url, _ = _signin_start_json(clients, "[email protected]")
1267 response = clients.post(
1268 response_url, json=dict(credential=json.dumps(upd_signin_data))
1269 )
1270 # verify actually logged in
1271 response = clients.get("/profile", headers={"accept": "application/json"})
1272 assert response.status_code == 200
1273
1274
1275 def test_autogen_user_handle(app, client, get_message):
1276 # Test that is an existing user doesn't have a fs_webauthn_user_handle - it will
1277 # be generated.
1278 with app.test_request_context("/"):
1279 user = app.security.datastore.find_user(email="[email protected]")
1280 user.fs_webauthn_user_handle = None
1281 app.security.datastore.put(user)
1282 app.security.datastore.commit()
1283
1284 authenticate(client)
1285 register_options, response_url = _register_start_json(client, usage="first")
1286 with app.test_request_context("/"):
1287 user = app.security.datastore.find_user(email="[email protected]")
1288 assert user.fs_webauthn_user_handle
1289 b64_user_handle = (
1290 urlsafe_b64encode(user.fs_webauthn_user_handle.encode())
1291 .decode("utf-8")
1292 .replace("=", "")
1293 )
1294 assert b64_user_handle == register_options["user"]["id"]
1295
1296
1297 def test_verify_json(app, client, get_message):
1298 # Test can re-authenticate using existing webauthn key.
1299 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1300
1301 authenticate(client)
1302 register_options, response_url = _register_start_json(client, usage="first")
1303 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1304 assert response.status_code == 200
1305
1306 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
1307
1308 response = client.get("fresh", headers=headers)
1309 assert response.status_code == 401
1310 assert response.json["response"]["reauth_required"]
1311 assert response.json["response"]["has_webauthn_verify_credential"]
1312
1313 response = client.get("wan-verify", headers=headers)
1314 assert response.status_code == 200
1315
1316 response = client.post("wan-verify", json=dict())
1317 # default webauthn_utils will set userVerification to discouraged in the
1318 # case of verify.
1319 signin_options = response.json["response"]["credential_options"]
1320 assert signin_options["userVerification"] == "discouraged"
1321
1322 response_url = (
1323 f'wan-verify/{response.json["response"]["wan_state"]}?include_auth_token'
1324 )
1325 response = client.post(response_url, json=dict(credential=json.dumps(SIGNIN_DATA1)))
1326 assert response.status_code == 200
1327 verify_token(client, response.json["response"]["user"]["authentication_token"])
1328
1329 response = client.get("fresh", headers=headers)
1330 assert response.status_code == 200
1331
1332
1333 def test_verify(app, client, get_message):
1334 # Test can re-authenticate using existing webauthn key.
1335 # Forms version - verify that the 'next' qparam is properly maintained during the
1336 # 2 part authentication.
1337 authenticate(client)
1338 register_options, response_url = _register_start(client, usage="first")
1339 response = client.post(
1340 response_url, data=dict(credential=json.dumps(REG_DATA1)), follow_redirects=True
1341 )
1342 assert response.status_code == 200
1343 assert b"testr1" in response.data
1344
1345 old_paa = reset_fresh(client, app.config["SECURITY_FRESHNESS"])
1346 response = client.get("fresh")
1347 assert response.location == "/verify?next=/fresh"
1348 signin_options, response_url = _signin_start(
1349 client, endpoint="wan-verify?next=/fresh"
1350 )
1351
1352 response = client.post(
1353 response_url,
1354 data=dict(credential=json.dumps(SIGNIN_DATA1)),
1355 follow_redirects=False,
1356 )
1357 assert "/fresh" in response.location
1358 with client.session_transaction() as sess:
1359 assert sess["fs_paa"] > old_paa
1360
1361
1362 @pytest.mark.settings(wan_signin_within="2 seconds")
1363 def test_verify_timeout(app, client, get_message):
1364 authenticate(client)
1365 register_options, response_url = _register_start_json(client, name="testr3")
1366 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1367 assert response.status_code == 200
1368
1369 app.security.wan_serializer = FakeSerializer(2.0)
1370 response = client.post("wan-verify", json=dict())
1371 response_url = f'wan-verify/{response.json["response"]["wan_state"]}'
1372 response = client.post(response_url, json=dict(credential=json.dumps(SIGNIN_DATA1)))
1373 assert response.status_code == 400
1374 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1375 "WEBAUTHN_EXPIRED", within=app.config["SECURITY_WAN_SIGNIN_WITHIN"]
1376 )
1377
1378
1379 def test_verify_validate_error(app, client, get_message, signals):
1380 authenticate(client)
1381 register_options, response_url = _register_start_json(client, name="testr3")
1382 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1383 assert response.status_code == 200
1384
1385 response = client.post("wan-verify", json=dict())
1386 response_url = f'wan-verify/{response.json["response"]["wan_state"]}'
1387 # send wrong signin data
1388 response = client.post(
1389 response_url, json=dict(credential=json.dumps(SIGNIN_DATA_UH))
1390 )
1391 assert response.status_code == 400
1392 assert response.json["response"]["field_errors"]["credential"][0].encode(
1393 "utf-8"
1394 ) == get_message("WEBAUTHN_UNKNOWN_CREDENTIAL_ID")
1395
1396 # same thing - with forms - this should redirect to wan-verify and flash a message
1397 with capture_flashes() as flashes:
1398 response = client.post(
1399 response_url,
1400 data=dict(credential=json.dumps(SIGNIN_DATA_UH)),
1401 follow_redirects=False,
1402 )
1403 assert response.status_code in [302, 303]
1404 assert "/wan-verify" in response.location
1405 assert flashes[0]["category"] == "error"
1406 assert flashes[0]["message"].encode("utf-8") == get_message(
1407 "WEBAUTHN_UNKNOWN_CREDENTIAL_ID"
1408 )
1409
1410 # now muck with attestation - should get VERIFY ERROR
1411 bad_signin = copy.deepcopy(SIGNIN_DATA1)
1412 bad_signin["response"]["signature"] = bad_signin["response"]["signature"].replace(
1413 "M", "N"
1414 )
1415 response = client.post(response_url, json=dict(credential=json.dumps(bad_signin)))
1416 assert response.status_code == 400
1417 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1418 "WEBAUTHN_NO_VERIFY", cause="Could not verify authentication signature"
1419 )
1420 assert (
1421 signals["user_failed_authn"][0]["request_endpoint"]
1422 == "security.wan_verify_response"
1423 )
1424 assert signals["user_failed_authn"][0]["user"].email == "[email protected]"
1425 assert signals["user_failed_authn"][0]["auth_type"] == "passkey"
1426 assert not signals["user_failed_authn"][0]["tfa"]
1427 check_signals(
1428 signals, ["user_failed_authn", "wan_registered", "user_authenticated"]
1429 )
1430
1431
1432 def test_verify_rejects_cross_user_assertion(app, client, get_message):
1433 # The reauthentication-freshness gate must not be satisfied by a
1434 # WebAuthn assertion whose proven credential belongs to a different
1435 # user than the currently authenticated session user. Sibling of the
1436 # OAuth fix in `oauth_glue.oauth_verify_response`.
1437 authenticate(client, email="[email protected]")
1438 register_options, response_url = _register_start_json(
1439 client, name="joekey", usage="first"
1440 )
1441 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1442 assert response.status_code == 200
1443 logout(client)
1444
1445 authenticate(client, email="[email protected]")
1446 register_options, response_url = _register_start_json(
1447 client, name="mattkey", usage="first"
1448 )
1449 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA_UV)))
1450 assert response.status_code == 200
1451
1452 old_paa = reset_fresh(client, app.config["SECURITY_FRESHNESS"])
1453
1454 response = client.post("wan-verify", json=dict())
1455 response_url = f'wan-verify/{response.json["response"]["wan_state"]}'
1456 # Submit joe's assertion while logged in as matt.
1457 response = client.post(response_url, json=dict(credential=json.dumps(SIGNIN_DATA1)))
1458 assert response.status_code == 400
1459 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1460 "WEBAUTHN_MISMATCH_USER_HANDLE"
1461 )
1462 with client.session_transaction() as sess:
1463 assert sess["fs_paa"] == old_paa
1464
1465 # same with forms
1466 response = client.post(
1467 response_url,
1468 data=dict(credential=json.dumps(SIGNIN_DATA1)),
1469 follow_redirects=True,
1470 )
1471 assert b"<title>Reauthenticate</title>" in response.data
1472 assert b"Credential user handle" in response.data
1473
1474
1475 @pytest.mark.settings(wan_allow_as_verify=None)
1476 def test_no_verify(app, client):
1477 authenticate(client)
1478 response = client.get("/wan-verify")
1479 assert response.status_code == 404
1480
1481
1482 def test_verify_usage_any_json(app, client, get_message):
1483 # Test the WAN_ALLOW_AS_VERIFY config.
1484 # Make sure only allowed credentials show up as options
1485 # Make sure if we use a disallowed credential, we get an error.
1486 keys = reg_2_keys(client)
1487
1488 # Default WAN_ALLOW_AS_VERIFY is ["first", "secondary"]
1489 response = client.post("wan-verify", json=dict())
1490 response_url = f'wan-verify/{response.json["response"]["wan_state"]}'
1491 allow_credentials = response.json["response"]["credential_options"][
1492 "allowCredentials"
1493 ]
1494 assert len(allow_credentials) == 2
1495
1496 # make sure can sign in with either
1497 response = client.post(
1498 response_url, json=dict(credential=json.dumps(keys["first"]["signin"]))
1499 )
1500 assert response.status_code == 200
1501 response = client.post(
1502 response_url, json=dict(credential=json.dumps(keys["secondary"]["signin"]))
1503 )
1504 assert response.status_code == 200
1505
1506
1507 @pytest.mark.settings(wan_allow_as_verify="first")
1508 def test_verify_usage_first_json(app, client, get_message):
1509 # Test the WAN_ALLOW_AS_VERIFY config.
1510 # Make sure only allowed credentials show up as options
1511 # Make sure if we use a disallowed credential, we get an error.
1512 keys = reg_2_keys(client)
1513
1514 response = client.post("wan-verify", json=dict())
1515 response_url = f'wan-verify/{response.json["response"]["wan_state"]}'
1516 allow_credentials = response.json["response"]["credential_options"][
1517 "allowCredentials"
1518 ]
1519 assert len(allow_credentials) == 1
1520 assert allow_credentials[0]["id"] == keys["first"]["id"]
1521
1522 # make sure can sign in with just "first"
1523 response = client.post(
1524 response_url, json=dict(credential=json.dumps(keys["first"]["signin"]))
1525 )
1526 assert response.status_code == 200
1527 # but not "secondary"
1528 response = client.post(
1529 response_url, json=dict(credential=json.dumps(keys["secondary"]["signin"]))
1530 )
1531 assert response.status_code == 400
1532 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1533 "WEBAUTHN_CREDENTIAL_WRONG_USAGE"
1534 )
1535
1536
1537 @pytest.mark.settings(wan_allow_as_verify="secondary")
1538 def test_verify_usage_secondary_json(app, client, get_message):
1539 # Test the WAN_ALLOW_AS_VERIFY config.
1540 # Make sure only allowed credentials show up as options
1541 # Make sure if we use a disallowed credential, we get an error.
1542 keys = reg_2_keys(client)
1543
1544 response = client.post("wan-verify", json=dict())
1545 response_url = f'wan-verify/{response.json["response"]["wan_state"]}'
1546 allow_credentials = response.json["response"]["credential_options"][
1547 "allowCredentials"
1548 ]
1549 assert len(allow_credentials) == 1
1550 assert allow_credentials[0]["id"] == keys["secondary"]["id"]
1551
1552 # make sure can sign in with just "secondary"
1553 response = client.post(
1554 response_url, json=dict(credential=json.dumps(keys["first"]["signin"]))
1555 )
1556 assert response.status_code == 400
1557 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1558 "WEBAUTHN_CREDENTIAL_WRONG_USAGE"
1559 )
1560 response = client.post(
1561 response_url, json=dict(credential=json.dumps(keys["secondary"]["signin"]))
1562 )
1563 assert response.status_code == 200
1564
1565
1566 def test_remember_token(client):
1567 # test that remember token properly set on primary authn with webauthn
1568 authenticate(client)
1569 register_options, response_url = _register_start_json(
1570 client, name="testr3", usage="first"
1571 )
1572 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1573 assert response.status_code == 200
1574 logout(client)
1575
1576 assert not client.get_cookie("remember_token")
1577
1578 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1579
1580 response = client.post(
1581 "wan-signin", headers=headers, json=dict(identity="[email protected]", remember=True)
1582 )
1583 response_url = f'wan-signin/{response.json["response"]["wan_state"]}'
1584 assert response.json["response"]["remember"]
1585
1586 response = client.post(
1587 response_url,
1588 json=dict(credential=json.dumps(SIGNIN_DATA1), remember=True),
1589 )
1590 assert client.get_cookie("remember_token")
1591 client.delete_cookie("session")
1592 response = client.get("/profile")
1593 assert b"Profile Page" in response.data
1594
1595
1596 @pytest.mark.two_factor()
1597 @pytest.mark.unified_signin()
1598 def test_remember_token_tf(client):
1599 # test that remember token properly set after secondary authn with webauthn
1600 authenticate(client)
1601 register_options, response_url = _register_start_json(client, name="testr3")
1602 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1603 assert response.status_code == 200
1604 logout(client)
1605
1606 assert not client.get_cookie("remember_token")
1607
1608 # login again - should require MFA
1609 response = client.post(
1610 "/us-signin",
1611 json=dict(identity="[email protected]", passcode="password", remember=True),
1612 )
1613 assert response.status_code == 200
1614 assert response.json["response"]["tf_method"] == "webauthn"
1615 assert response.json["response"]["tf_required"]
1616 with client.session_transaction() as session:
1617 assert session["tf_remember_login"]
1618
1619 signin_options, response_url, _ = _signin_start_json(client, "[email protected]")
1620 response = client.post(
1621 response_url,
1622 json=dict(credential=json.dumps(SIGNIN_DATA1), remember=True),
1623 )
1624 assert client.get_cookie("remember_token")
1625 client.delete_cookie("session")
1626 response = client.get("/profile")
1627 assert b"profile" in response.data
1628
1629
1630 @pytest.mark.settings(
1631 wan_post_register_view="/post_register",
1632 )
1633 def test_post_register_redirect(app, client, get_message):
1634 authenticate(client)
1635
1636 register_options, response_url = _register_start_json(client, name="testr3")
1637 response = client.post(
1638 response_url,
1639 data=dict(credential=json.dumps(REG_DATA1)),
1640 follow_redirects=False,
1641 )
1642 assert response.status_code in [302, 303]
1643 assert "/post_register" in response.location
1644
1645
1646 class MyWebauthnUtil(HackWebauthnUtil):
1647 def user_verification(self, user, usage):
1648 from webauthn.helpers.structs import UserVerificationRequirement
1649
1650 return UserVerificationRequirement.REQUIRED
1651
1652
1653 @pytest.mark.two_factor()
1654 @pytest.mark.unified_signin()
1655 @pytest.mark.webauthn(webauthn_util_cls=MyWebauthnUtil)
1656 def test_uv_required(client):
1657 # Override WebauthnUtils to require user-verification on signin.
1658 keys = reg_2_keys(client)
1659 logout(client)
1660
1661 # log back in - should require MFA.
1662 response = client.post(
1663 "/us-signin",
1664 json=dict(identity="[email protected]", passcode="password", remember=True),
1665 )
1666 assert response.status_code == 200
1667 assert response.json["response"]["tf_required"]
1668
1669 # since we always REQUIRE user_verification in our WebauthUtil this should fail
1670 signin_options, response_url, _ = _signin_start_json(client, "")
1671 response = client.post(
1672 response_url,
1673 json=dict(credential=json.dumps(keys["secondary"]["signin"])),
1674 )
1675 assert response.status_code == 400
1676 assert (
1677 "User verification is required"
1678 in response.json["response"]["field_errors"]["credential"][0]
1679 )
1680
1681 logout(client)
1682
1683 # Try signing in with 'first' WebAuthn key - this DOES have UV set so should work.
1684 signin_options, response_url, _ = _signin_start_json(client, "")
1685 response = client.post(
1686 response_url,
1687 json=dict(credential=json.dumps(keys["first"]["signin"])),
1688 )
1689 assert response.status_code == 200
1690 assert response.json["response"]["user"]["email"] == "[email protected]"
1691
1692
1693 @pytest.mark.settings(multi_factor_recovery_codes=True)
1694 def test_mf(client):
1695 # Test using recovery codes in-liu of a webauthn second factor
1696 # Note that we are allowed to generate recovery codes even if we don't yet have
1697 # an established 2nd factor
1698 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1699 authenticate(client)
1700 response = client.post("/mf-recovery-codes", headers=headers)
1701 codes = response.json["response"]["recovery_codes"]
1702 assert len(codes) == 5
1703
1704 # setup webauthn
1705 register_options, response_url = _register_start_json(client, name="testr3")
1706 response = client.post(response_url, json=dict(credential=json.dumps(REG_DATA1)))
1707 assert response.status_code == 200
1708 logout(client)
1709
1710 response = client.post(
1711 "/login", json=dict(email="[email protected]", password="password")
1712 )
1713 assert response.status_code == 200
1714 assert response.json["response"]["tf_required"]
1715
1716 # oh no - we forgot our webauthn key
1717 """ Right now tf-rescue is part of TWO_FACTOR - not WEBAUTHN
1718 response = client.get("/tf-rescue", headers=headers)
1719 options = response.json["response"]["recovery_options"]
1720 assert "recovery_code" in options.keys()
1721 assert "/mf-recovery" in options["recovery_code"]
1722 """
1723
1724 response = client.post(
1725 "/mf-recovery", data=dict(code=codes[0]), follow_redirects=True
1726 )
1727 assert response.status_code == 200
1728
1729 # verify actually logged in
1730 response = client.get("/profile", follow_redirects=False)
1731 assert response.status_code == 200
1732
1733
1734 @pytest.mark.settings(url_prefix="/auth")
1735 def test_login_next(app, client, get_message):
1736 # Test that ?next=/xx is propagated through login/wan-signin templates as well as
1737 # views.
1738 # Also - use a different blueprint prefix - we rarely test that....
1739 authenticate(client, endpoint="/auth/login")
1740 register_options, response_url = _register_start(
1741 client, name="testr3", usage="first", endpoint="/auth/wan-register"
1742 )
1743 response = client.post(
1744 response_url, data=dict(credential=json.dumps(REG_DATA1)), follow_redirects=True
1745 )
1746 assert response.status_code == 200
1747 assert get_message("WEBAUTHN_REGISTER_SUCCESSFUL", name="testr3") in response.data
1748 logout(client, endpoint="/auth/logout")
1749
1750 response = client.get("profile", follow_redirects=True)
1751 assert "?next=/profile" in response.request.url
1752 # pull webauthn form action out of login_form - should have ?next=...
1753 webauthn_url = get_form_action(response, 1)
1754
1755 signin_options, response_url = _signin_start(
1756 client, "[email protected]", endpoint=webauthn_url
1757 )
1758 response = client.post(
1759 response_url,
1760 data=dict(credential=json.dumps(SIGNIN_DATA1)),
1761 follow_redirects=True,
1762 )
1763 assert response.status_code == 200
1764 assert b"Profile Page" in response.data
1765
1766 # Try form.next
1767 logout(client, endpoint="/auth/logout")
1768 reset_signcount(app, "[email protected]", "testr3")
1769
1770 response = client.post(
1771 "/auth/wan-signin", data=dict(identity="[email protected]", next="/im-in")
1772 )
1773 response_url = get_form_action(response)
1774
1775 next_loc = get_form_input_value(response, "next")
1776 response = client.post(
1777 response_url,
1778 data=dict(credential=json.dumps(SIGNIN_DATA1), next=next_loc),
1779 follow_redirects=False,
1780 )
1781 assert "/im-in" in response.location
1782
1783
1784 @pytest.mark.flask_async()
1785 def test_async(app, client, get_message):
1786 auths = []
1787
1788 @user_authenticated.connect_via(app)
1789 async def authned(myapp, user, **extra_args):
1790 auths.append((user.email, extra_args["authn_via"]))
1791
1792 @wan_registered.connect_via(app)
1793 async def pc(sender, user, name, **extra_args):
1794 assert name == "testr1"
1795 assert len(user.webauthn) == 1
1796
1797 @wan_deleted.connect_via(app)
1798 async def wan_delete(sender, user, name, **extra_args):
1799 assert name == "testr1"
1800
1801 authenticate(client)
1802
1803 register_options, response_url = _register_start(client, usage="first")
1804 response = client.post(
1805 response_url, data=dict(credential=json.dumps(REG_DATA1)), follow_redirects=True
1806 )
1807 assert response.status_code == 200
1808
1809 # sign in - simple case use identity so we get back allowCredentials
1810 logout(client)
1811 signin_options, response_url = _signin_start(client, "[email protected]")
1812 response = client.post(
1813 response_url,
1814 data=dict(credential=json.dumps(SIGNIN_DATA1)),
1815 follow_redirects=True,
1816 )
1817 assert response.status_code == 200
1818 assert b"Welcome [email protected]" in response.data
1819 assert len(auths) == 2
1820 assert auths[1][1] == ["webauthn"]
1821
1822 # test delete signal
1823 response = client.post(
1824 "/wan-delete", data=dict(name="testr1"), follow_redirects=True
1825 )
1826
1827
1828 @pytest.mark.csrf()
1829 @pytest.mark.settings(
1830 wan_post_register_view="/done-registration",
1831 post_login_view="/post-login",
1832 )
1833 def test_csrf(app, client, get_message):
1834 response = client.get("/login")
1835 csrf_token = get_form_input_value(response, "csrf_token")
1836 authenticate(client, csrf=True)
1837
1838 register_options, response_url = _register_start(
1839 client, usage="first", csrf_token=csrf_token
1840 )
1841 data = dict(credential=json.dumps(REG_DATA1))
1842 response = client.post(response_url, data=data, follow_redirects=True)
1843 assert (
1844 b"The CSRF token is missing" in response.data
1845 ) # this should have been flashed
1846
1847 data["csrf_token"] = csrf_token
1848 response = client.post(response_url, data=data)
1849 assert check_location(app, response.location, "/done-registration")
1850 logout(client)
1851
1852 # use old csrf_token - should fail and we should get the error in the template
1853 response = client.post(
1854 "wan-signin", data=dict(identity="[email protected]", csrf_token=csrf_token)
1855 )
1856 assert b"The CSRF tokens do not match." in response.data
1857
1858 response = client.get("/wan-signin")
1859 csrf_token = get_form_input_value(response, "csrf_token")
1860 signin_options, response_url = _signin_start(
1861 client, "[email protected]", csrf_token=csrf_token
1862 )
1863 data = dict(credential=json.dumps(SIGNIN_DATA1))
1864 response = client.post(response_url, data=data, follow_redirects=True)
1865 assert (
1866 b"The CSRF token is missing" in response.data
1867 ) # this should have been flashed
1868
1869 data["csrf_token"] = csrf_token
1870 response = client.post(response_url, data=data)
1871 assert check_location(app, response.location, "/post-login")
1872
1873
1874 @pytest.mark.settings(default_remember_me=True)
1875 def test_remember_login_form(app, client):
1876 # ensure form has the checkbox set if default set.
1877 response = client.get("/wan-signin")
1878 assert response.status_code == 200
1879 r = get_form_input(response, "remember")
1880 assert "checked" in r