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