Debian Codegraph @

tests/test_recovery_codes.py

raw
1 """
2 test_recovery_codes
3 ~~~~~~~~~~~~~~~~~
4
5 recovery code tests
6
7 :copyright: (c) 2022-2024 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9 """
10
11 import re
12
13 import pytest
14
15 from tests.test_two_factor import tf_authenticate
16 from tests.test_utils import (
17 authenticate,
18 logout,
19 reset_fresh,
20 setup_tf_sms,
21 )
22
23 pytestmark = pytest.mark.two_factor()
24
25
26 @pytest.mark.settings(multi_factor_recovery_codes=True)
27 def test_rc_json(app, clients, get_message):
28 # Test recovery codes
29 # gal has two-factor already setup for 'sms'
30 client = clients
31 headers = {"Accept": "application/json", "Content-Type": "application/json"}
32 tf_authenticate(app, client)
33
34 response = client.get("/mf-recovery-codes", headers=headers)
35 assert response.status_code == 200
36 codes = response.json["response"]["recovery_codes"]
37 assert len(codes) == 0
38
39 response = client.post("/mf-recovery-codes", headers=headers)
40 codes = response.json["response"]["recovery_codes"]
41 assert len(codes) == 5
42
43 response = client.get("/mf-recovery-codes", headers=headers)
44 recodes = response.json["response"]["recovery_codes"]
45 assert len(recodes) == 5 and codes[0] == recodes[0]
46
47 response = client.get("/mf-recovery-codes", headers=headers)
48 assert response.status_code == 200
49 assert not hasattr(response.json["response"], "recovery_codes")
50
51 # endpoint is for unauthenticated only
52 response = client.post("/mf-recovery", json=dict(code=codes[0]))
53 assert response.status_code == 400
54 logout(client)
55
56 response = client.post("/login", json=dict(email="[email protected]", password="password"))
57 assert response.json["response"]["tf_required"]
58
59 response = client.post("/mf-recovery", json=dict(code=codes[0]))
60 assert response.status_code == 200
61
62 # verify actually logged in
63 response = client.get("/profile", follow_redirects=False)
64 assert response.status_code == 200
65
66 # logout and try again - first code shouldn't work again
67 logout(client)
68 response = client.post("/login", json=dict(email="[email protected]", password="password"))
69 assert response.json["response"]["tf_required"]
70
71 response = client.post("/mf-recovery", json=dict(code=codes[0]))
72 assert response.status_code == 400
73 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
74 "INVALID_RECOVERY_CODE"
75 )
76 response = client.post("/mf-recovery", json=dict(code=codes[1]))
77 assert response.status_code == 200
78
79
80 @pytest.mark.settings(multi_factor_recovery_codes=True)
81 def test_rc(app, client, get_message):
82 # Test recovery codes
83 # gal has two-factor already setup for 'sms'
84 tf_authenticate(app, client)
85
86 response = client.get("/mf-recovery-codes?show_codes=hi")
87 assert response.status_code == 200
88 assert get_message("NO_RECOVERY_CODES_SETUP") in response.data
89
90 response = client.post("/mf-recovery-codes")
91 rd = response.data.decode("utf-8")
92 codes = re.findall(r"[a-f,\d]{4}-[a-f,\d]{4}-[a-f,\d]{4}", rd)
93 assert len(codes) == 5
94
95 response = client.get("/mf-recovery-codes?show_codes=hi")
96 assert response.status_code == 200
97 assert b"Recovery Codes" in response.data
98 rd = response.data.decode("utf-8")
99 codes = re.findall(r"[a-f,\d]{4}-[a-f,\d]{4}-[a-f,\d]{4}", rd)
100 assert len(codes) == 5
101
102 # endpoint is for unauthenticated only
103 response = client.post(
104 "/mf-recovery", data=dict(code=codes[0]), follow_redirects=False
105 )
106 assert response.status_code in [302, 303]
107 logout(client)
108
109 response = client.post("/login", json=dict(email="[email protected]", password="password"))
110 assert response.json["response"]["tf_required"]
111
112 response = client.post(
113 "/mf-recovery", data=dict(code=codes[0]), follow_redirects=True
114 )
115 assert response.status_code == 200
116
117 # verify actually logged in
118 response = client.get("/profile", follow_redirects=False)
119 assert response.status_code == 200
120
121 # logout and try again - first code shouldn't work again
122 logout(client)
123 response = client.post("/login", data=dict(email="[email protected]", password="password"))
124
125 response = client.post("/mf-recovery", data=dict(code=codes[0]))
126 assert get_message("INVALID_RECOVERY_CODE") in response.data
127 response = client.post(
128 "/mf-recovery", data=dict(code=codes[1]), follow_redirects=True
129 )
130 assert response.status_code == 200
131 # verify actually logged in
132 response = client.get("/profile", follow_redirects=False)
133 assert response.status_code == 200
134
135
136 @pytest.mark.settings(multi_factor_recovery_codes=True)
137 def test_rc_reset(app, client, get_message):
138 # test that reset_user_access, removes recovery codes
139 headers = {"Accept": "application/json", "Content-Type": "application/json"}
140 tf_authenticate(app, client)
141
142 response = client.post("/mf-recovery-codes", headers=headers)
143 codes = response.json["response"]["recovery_codes"]
144 assert len(codes) == 5
145
146 with app.app_context():
147 user = app.security.datastore.find_user(email="[email protected]")
148 app.security.datastore.reset_user_access(user)
149 app.security.datastore.commit()
150
151 client.post("/login", json=dict(email="[email protected]", password="password"))
152 response = client.get("/mf-recovery-codes", headers=headers)
153 codes = response.json["response"]["recovery_codes"]
154 assert len(codes) == 0
155
156
157 @pytest.mark.settings(multi_factor_recovery_codes=True, url_prefix="/api")
158 def test_rc_bad_state(app, client, get_message):
159 response = client.post("/api/mf-recovery", json=dict(code="hi"))
160 assert response.status_code == 400
161 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
162 "TWO_FACTOR_PERMISSION_DENIED"
163 )
164
165 response = client.post(
166 "/api/mf-recovery", data=dict(code="hi"), follow_redirects=False
167 )
168 assert response.status_code in [302, 303]
169 assert "/api/login" in response.location
170
171
172 @pytest.mark.settings(multi_factor_recovery_codes=True)
173 def test_rc_rescue(app, client, get_message):
174 headers = {"Accept": "application/json", "Content-Type": "application/json"}
175 tf_authenticate(app, client)
176
177 response = client.post("/mf-recovery-codes", headers=headers)
178 codes = response.json["response"]["recovery_codes"]
179 assert len(codes) == 5
180 logout(client)
181
182 data = dict(email="[email protected]", password="password")
183 response = client.post("/login", json=data)
184 assert response.json["response"]["tf_required"]
185
186 response = client.get("/tf-rescue")
187 assert b"Use previously downloaded recovery code" in response.data
188
189 response = client.get("/tf-rescue", headers=headers)
190 options = response.json["response"]["recovery_options"]
191 assert "recovery_code" in options.keys()
192 assert "/mf-recovery" in options["recovery_code"]
193
194 response = client.post(
195 "/tf-rescue", data=dict(help_setup="recovery_code"), follow_redirects=False
196 )
197 assert "/mf-recovery" in response.location
198
199
200 @pytest.mark.settings(multi_factor_recovery_codes=True)
201 def test_fresh(app, client):
202 # Make sure fetching recovery codes is protected with a freshness check.
203 headers = {"Accept": "application/json", "Content-Type": "application/json"}
204
205 authenticate(client)
206 response = client.post("/mf-recovery-codes", headers=headers)
207 codes = response.json["response"]["recovery_codes"]
208 assert len(codes) == 5
209
210 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
211 response = client.post("/mf-recovery-codes", headers=headers)
212 assert response.status_code == 401
213 assert response.json["response"]["reauth_required"]
214
215 response = client.post("/verify", json=dict(password="password"))
216 assert response.status_code == 200
217
218 response = client.post("/mf-recovery-codes", headers=headers)
219 codes = response.json["response"]["recovery_codes"]
220 assert len(codes) == 5
221
222
223 @pytest.mark.settings(
224 multi_factor_recovery_codes=True,
225 multi_factor_recovery_codes_keys=[b"6_WhDTwI1RKJ3_ra9nADCBQbrRywlA88psGsq21xcsU="],
226 )
227 def test_rc_json_encrypted(app, client, get_message):
228 # Test recovery codes with encryption option
229 # gal has two-factor already setup for 'sms'
230 headers = {"Accept": "application/json", "Content-Type": "application/json"}
231 tf_authenticate(app, client)
232
233 response = client.post("/mf-recovery-codes", headers=headers)
234 codes = response.json["response"]["recovery_codes"]
235 assert len(codes) == 5
236
237 # endpoint is for unauthenticated only
238 response = client.post("/mf-recovery", json=dict(code=codes[0]))
239 assert response.status_code == 400
240 logout(client)
241
242 response = client.post("/login", json=dict(email="[email protected]", password="password"))
243 assert response.json["response"]["tf_required"]
244
245 response = client.post("/mf-recovery", json=dict(code=codes[0]))
246 assert response.status_code == 200
247
248 # verify actually logged in
249 response = client.get("/profile", follow_redirects=False)
250 assert response.status_code == 200
251
252 # logout and try again - first code shouldn't work again
253 logout(client)
254 response = client.post("/login", json=dict(email="[email protected]", password="password"))
255 assert response.json["response"]["tf_required"]
256
257 response = client.post("/mf-recovery", json=dict(code=codes[0]))
258 assert response.status_code == 400
259 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
260 "INVALID_RECOVERY_CODE"
261 )
262 response = client.post("/mf-recovery", json=dict(code=codes[1]))
263 assert response.status_code == 200
264
265 # make sure DB actually has encrypted codes!
266 with app.test_request_context("/"):
267 user = app.security.datastore.find_user(email="[email protected]")
268 codes = user.mf_recovery_codes
269 assert len(codes) == 3
270 assert len(codes[0]) == 100
271
272
273 @pytest.mark.settings(
274 multi_factor_recovery_codes=True,
275 multi_factor_recovery_codes_keys=[b"6_WhDTwI1RKJ3_ra9nADCBQbrRywlA88psGsq21xcsU="],
276 )
277 def test_rc_json_encrypted_multi(app, client, get_message):
278 # Test recovery codes with encryption option and multiple keys
279 # gal has two-factor already setup for 'sms'
280 from cryptography.fernet import Fernet
281
282 headers = {"Accept": "application/json", "Content-Type": "application/json"}
283 tf_authenticate(app, client)
284
285 response = client.post("/mf-recovery-codes", headers=headers)
286 codes = response.json["response"]["recovery_codes"]
287 assert len(codes) == 5
288 logout(client)
289
290 response = client.post("/login", json=dict(email="[email protected]", password="password"))
291 assert response.json["response"]["tf_required"]
292
293 response = client.post("/mf-recovery", json=dict(code=codes[0]))
294 assert response.status_code == 200
295
296 # verify actually logged in
297 response = client.get("/profile", follow_redirects=False)
298 assert response.status_code == 200
299 logout(client)
300
301 # add a new key to cryptor and verify old code still works
302 key2 = Fernet.generate_key()
303 newkeys = [key2, b"6_WhDTwI1RKJ3_ra9nADCBQbrRywlA88psGsq21xcsU="]
304 app.security.mf_recovery_codes_util.setup_cryptor(newkeys)
305
306 response = client.post("/login", json=dict(email="[email protected]", password="password"))
307 assert response.json["response"]["tf_required"]
308 response = client.post("/mf-recovery", json=dict(code=codes[1]))
309 assert response.status_code == 200
310 logout(client)
311
312 # creat codes for new user - this should use the new primary key.
313 response = client.post(
314 "/login", json=dict(email="[email protected]", password="password")
315 )
316 setup_tf_sms(client)
317 response = client.post("/mf-recovery-codes", headers=headers)
318 matt_codes = response.json["response"]["recovery_codes"]
319 logout(client)
320
321 # Now remove older key and codes for [email protected] shouldn't work
322 app.security._mf_recovery_codes_util.setup_cryptor([key2])
323 response = client.post("/login", json=dict(email="[email protected]", password="password"))
324 assert response.json["response"]["tf_required"]
325 response = client.post("/mf-recovery", json=dict(code=codes[2]))
326 assert response.status_code == 400
327 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
328 "INVALID_RECOVERY_CODE"
329 )
330
331 # matts codes should work
332 response = client.post(
333 "/login", json=dict(email="[email protected]", password="password")
334 )
335 assert response.json["response"]["tf_required"]
336 response = client.post("/mf-recovery", json=dict(code=matt_codes[0]))
337 assert response.status_code == 200