Debian Codegraph @

tests/test_tokens.py

raw
1 """
2 test_tokens
3 ~~~~~~~~~~~~~~~~
4
5 Refresh/Auth Token functionality tests
6
7 :copyright: (c) 2026-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9 """
10
11 from datetime import datetime, timedelta, timezone
12 import math
13
14 import pytest
15 from freezegun import freeze_time
16 from itsdangerous import SignatureExpired
17 from sqlalchemy import Column, String
18
19 from flask_security.datastore import PeeweeDatastore
20 from flask_security.tokens import RefreshTokenErrors
21 from flask_security.utils import parse_auth_token
22 from tests.test_csrf import _get_csrf_token
23 from tests.test_utils import (
24 check_signals,
25 json_authenticate,
26 logout,
27 FakeSerializer,
28 verify_token,
29 )
30
31 pytestmark = pytest.mark.refresh_token()
32
33
34 def _set_refresh_tracker(app, refresh_token, **kwargs):
35 with app.app_context():
36 tdata = app.security.refresh_token_serializer.loads(refresh_token)
37 refresh_tracker = app.security.datastore.find_refresh_tracker(tdata["family"])
38 for k, v in kwargs.items():
39 setattr(refresh_tracker, k, v)
40 app.security.datastore.put(refresh_tracker)
41 app.security.datastore.commit()
42 if isinstance(app.security.datastore, PeeweeDatastore):
43 app.security.datastore.db.close_db(None)
44
45
46 @pytest.mark.app_settings(testing_no_cookies=True)
47 @pytest.mark.settings(refresh_token_cookie_name=None)
48 def test_refresh(app, clients, get_message):
49 """Test basic refresh token flow.
50 - authenticate and receive auth_token and refresh_token
51 - we hack the auth_token to be already expired
52 - we should get a 401 when using it
53 - use the /refresh-token endpoint to get a new refresh_token and auth_token
54 - auth_token should be valid
55 """
56 start_ts = datetime.now(timezone.utc).replace(tzinfo=None).timestamp()
57 max_age = app.config["SECURITY_REFRESH_TOKEN_MAX_AGE"]
58 rts = app.security.remember_token_serializer
59 app.security.remember_token_serializer = FakeSerializer(2.0)
60 response = json_authenticate(clients)
61 with pytest.raises(TypeError):
62 clients.get_cookie("session")
63
64 auth_token1 = response.json["response"]["user"]["authentication_token"]
65 refresh_token = response.json["response"]["user"]["refresh_token"]
66
67 tdict = app.security.refresh_token_serializer.loads(refresh_token)
68 assert (
69 tdict["expires_at"]
70 > ((datetime.today() + max_age) - timedelta(days=1)).timestamp()
71 )
72 assert tdict["gen"] == 1
73 assert tdict["last_used_at"] >= start_ts
74 verify_token(clients, auth_token1, 401)
75
76 # set auth_token serializer back to one that doesn't expire
77 app.security.remember_token_serializer = rts
78 response = clients.post("/refresh-token", json={"refresh_token": refresh_token})
79 new_refresh_token = response.json["response"]["user"]["refresh_token"]
80 auth_token = response.json["response"]["user"]["authentication_token"]
81 verify_token(clients, auth_token)
82
83 ntdict = app.security.refresh_token_serializer.loads(new_refresh_token)
84 assert (
85 ntdict["expires_at"]
86 > ((datetime.today() + max_age) - timedelta(days=1)).timestamp()
87 )
88 assert ntdict["gen"] == 2
89 assert tdict["family"] == ntdict["family"]
90 # mongo stores more digits...
91 te = math.floor(tdict["expires_at"] * 1000.0)
92 nte = math.floor(ntdict["expires_at"] * 1000.0)
93 assert te == nte
94
95
96 @pytest.mark.app_settings(testing_no_cookies=True)
97 @pytest.mark.settings(refresh_token_cookie_name=None)
98 def test_refresh_errors(app, client, get_message):
99 response = json_authenticate(client)
100 refresh_token = response.json["response"]["user"]["refresh_token"]
101 response = client.post("/refresh-token", json={"refresh_token": ""})
102 assert response.status_code == 400
103 assert response.json["response"]["errors"][0] == "This field is required."
104
105 response = client.post("/refresh-token", json={"refresh_token": "12345"})
106 assert response.status_code == 400
107 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
108 "REFRESH_TOKEN_INVALID", reason=RefreshTokenErrors.INVALID.name
109 )
110
111 # This is a JSON endpoint only.
112 response = client.post("/refresh-token", data={"refresh_token": refresh_token})
113 assert response.status_code == 400
114
115 # now delete the tracker from the server
116 response = client.post("/refresh-token", json={"refresh_token": refresh_token})
117 assert response.status_code == 200
118 with app.test_request_context("/"):
119 user = app.security.datastore.find_user(email="[email protected]")
120 assert len(user.refresh_trackers) == 1
121 app.security.datastore.delete(user.refresh_trackers[0])
122 app.security.datastore.commit()
123 response = client.post("/refresh-token", json={"refresh_token": refresh_token})
124 assert response.status_code == 400
125 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
126 "REFRESH_TOKEN_INVALID", reason=RefreshTokenErrors.NOT_FOUND.name
127 )
128
129
130 @pytest.mark.app_settings(testing_no_cookies=True)
131 @pytest.mark.settings(
132 refresh_token_max_idle=timedelta(hours=1), refresh_token_cookie_name=None
133 )
134 def test_idle_expire(app, clients, get_message):
135 response = json_authenticate(clients)
136 refresh_token = response.json["response"]["user"]["refresh_token"]
137
138 new_last_used_at = app.security.datetime_factory() - timedelta(days=1)
139 _set_refresh_tracker(app, refresh_token, last_used_at=new_last_used_at)
140
141 response = clients.post("/refresh-token", json={"refresh_token": refresh_token})
142 assert response.status_code == 400
143 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
144 "REFRESH_TOKEN_INVALID", reason=RefreshTokenErrors.EXPIRED.name
145 )
146
147
148 @pytest.mark.settings(refresh_token_cookie_name=None)
149 def test_gen_mismatch(app, clients, get_message, signals):
150 # If there is generation mismatch, the system should revoke the
151 # entire refresh token family.
152 response = json_authenticate(clients)
153
154 refresh_token1 = response.json["response"]["user"]["refresh_token"]
155
156 response = clients.post("/refresh-token", json={"refresh_token": refresh_token1})
157 refresh_token2 = response.json["response"]["user"]["refresh_token"]
158 auth_token2 = response.json["response"]["user"]["authentication_token"]
159 verify_token(clients, auth_token2)
160
161 # now use refresh_token1 again and the system should revoke the entire
162 # refresh token family and a signal sent
163 response = clients.post("/refresh-token", json={"refresh_token": refresh_token1})
164 assert response.status_code == 400
165 rsignal = signals["refresh_tracker_revoked"][0]
166 assert rsignal["request_endpoint"] == "security.refresh_token"
167 assert rsignal["refresh_errors"] == RefreshTokenErrors.GEN_MISMATCH
168
169 # now use the supposedly good refresh_token - it too should have been revoked
170 response = clients.post("/refresh-token", json={"refresh_token": refresh_token2})
171 assert response.status_code == 400
172 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
173 "REFRESH_TOKEN_INVALID", reason=RefreshTokenErrors.REVOKED.name
174 )
175 check_signals(signals, ["refresh_tracker_revoked", "refresh_tracker_created"])
176
177
178 @pytest.mark.app_settings(testing_no_cookies=True)
179 @pytest.mark.settings(refresh_token_cookie_name=None)
180 def test_auto_cleanup_expired(app, clients, get_message, signals):
181 # test that expired refresh trackers are cleaned up as part of getting a new tracker
182 response = json_authenticate(clients)
183 refresh_token = response.json["response"]["user"]["refresh_token"]
184 new_expires_at = app.security.datetime_factory() - timedelta(days=1)
185 _set_refresh_tracker(app, refresh_token, expires_at=new_expires_at)
186
187 response = clients.post("/refresh-token", json={"refresh_token": refresh_token})
188 assert response.status_code == 400
189 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
190 "REFRESH_TOKEN_INVALID", reason=RefreshTokenErrors.EXPIRED.name
191 )
192
193 # log out and back in and should get a new refresh token
194 logout(clients)
195 response = json_authenticate(clients)
196 check_signals(signals, {"refresh_tracker_created": 2})
197
198 with app.app_context():
199 user = app.security.datastore.find_user(email="[email protected]")
200 assert len(user.refresh_trackers) == 1
201
202
203 @pytest.mark.app_settings(testing_no_cookies=True)
204 @pytest.mark.settings(refresh_token_cookie_name=None)
205 def test_reset(app, clients, get_message):
206 response = json_authenticate(clients)
207 refresh_token = response.json["response"]["user"]["refresh_token"]
208
209 with app.test_request_context("/"):
210 user = app.security.datastore.find_user(email="[email protected]")
211 assert len(user.refresh_trackers) == 1
212 app.security.datastore.refresh_tracker_reset(user)
213 app.security.datastore.commit()
214
215 response = clients.post("/refresh-token", json={"refresh_token": refresh_token})
216 assert response.status_code == 400
217 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
218 "REFRESH_TOKEN_INVALID", reason=RefreshTokenErrors.REVOKED.name
219 )
220
221
222 class UserWithTokenUniquifier:
223 fs_token_uniquifier = Column(String(64), unique=True, nullable=False)
224
225
226 @pytest.mark.app_settings(
227 TESTING_USER_MIXIN=UserWithTokenUniquifier, testing_no_cookies=True
228 )
229 @pytest.mark.settings(refresh_token_cookie_name=None)
230 @pytest.mark.changeable()
231 def test_token_uniquifier(app, client, get_message):
232 # Test if User model has a fs_token_uniquifier field then change password doesn't
233 # affect refresh tokens.
234 with app.test_request_context("/"):
235 user = app.security.datastore.find_user(email="[email protected]")
236 assert user.fs_token_uniquifier is not None
237
238 response = json_authenticate(client)
239 refresh_token = response.json["response"]["user"]["refresh_token"]
240 auth_token = response.json["response"]["user"]["authentication_token"]
241 headers = {"Authentication-Token": auth_token}
242
243 response = client.post(
244 "/change",
245 json=dict(
246 password="password",
247 new_password="awesome sunset",
248 new_password_confirm="awesome sunset",
249 ),
250 headers=headers,
251 )
252 assert response.status_code == 200
253
254 response = client.post("/refresh-token", json={"refresh_token": refresh_token})
255 assert response.status_code == 200
256
257
258 @pytest.mark.app_settings(testing_no_cookies=True)
259 @pytest.mark.changeable()
260 @pytest.mark.settings(refresh_token_cookie_name=None)
261 def test_no_token_uniquifier(app, client, get_message):
262 # Test if User model doesn't have a fs_token_uniquifier field then change
263 # password will invalidate all refresh tokens.
264 response = json_authenticate(client)
265 refresh_token = response.json["response"]["user"]["refresh_token"]
266 auth_token = response.json["response"]["user"]["authentication_token"]
267 headers = {"Authentication-Token": auth_token}
268
269 response = client.post(
270 "/change",
271 json=dict(
272 password="password",
273 new_password="awesome sunset",
274 new_password_confirm="awesome sunset",
275 ),
276 headers=headers,
277 )
278 assert response.status_code == 200
279
280 response = client.post("/refresh-token", json={"refresh_token": refresh_token})
281 assert response.status_code == 400
282
283
284 @pytest.mark.app_settings(testing_no_cookies=True)
285 @pytest.mark.settings(refresh_token_cookie_name=None)
286 def test_logout_with_token(app, client, get_message):
287 response = json_authenticate(client)
288 refresh_token = response.json["response"]["user"]["refresh_token"]
289 auth_token = response.json["response"]["user"]["authentication_token"]
290 headers = {"Authentication-Token": auth_token}
291 client.post("/logout", json=dict(refresh_token=refresh_token), headers=headers)
292
293 response = client.post("/refresh-token", json={"refresh_token": refresh_token})
294 assert response.status_code == 400
295 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
296 "REFRESH_TOKEN_INVALID", reason=RefreshTokenErrors.REVOKED.name
297 )
298 with app.test_request_context("/"):
299 user = app.security.datastore.find_user(email="[email protected]")
300 assert len(user.refresh_trackers) == 1
301 assert user.refresh_trackers[0].revoked_at is not None
302
303
304 @pytest.mark.settings(
305 refresh_token_cookie_name="fs_rtoken_test",
306 refresh_token_cookie=dict(
307 samesite="Lax",
308 httponly=True,
309 secure=True,
310 ),
311 )
312 def test_refresh_cookie(app, client, get_message):
313 """If we configure a cookie we shouldn't get the refresh token in the response.
314 The cookie should be properly updated when getting a new auth_token.
315 The cookie should be deleted as part of logout.
316 """
317 response = json_authenticate(client)
318 assert "refresh_token" not in response.json["response"]["user"]
319 rcookie = client.get_cookie("fs_rtoken_test")
320 assert rcookie is not None
321 assert rcookie.http_only
322 assert rcookie.same_site == "Lax"
323 assert rcookie.secure
324 tdict = app.security.refresh_token_serializer.loads(rcookie.value)
325 assert tdict["gen"] == 1
326
327 auth_token = response.json["response"]["user"]["authentication_token"]
328 verify_token(client, auth_token)
329
330 headers = {"Accept": "application/json", "Content-Type": "application/json"}
331 response = client.post("/refresh-token", headers=headers)
332 assert response.status_code == 200
333
334 nrcookie = client.get_cookie("fs_rtoken_test")
335 assert nrcookie is not None
336 assert nrcookie.http_only
337 ntdict = app.security.refresh_token_serializer.loads(nrcookie.value)
338 assert ntdict["gen"] == 2
339 assert tdict["family"] == ntdict["family"]
340
341 # log out and ensure cookie is removed
342 client.post("/logout")
343 assert client.get_cookie("fs_rtoken_test") is None
344 assert len(client._cookies) == 1 # session
345 with app.test_request_context("/"):
346 user = app.security.datastore.find_user(email="[email protected]")
347 assert len(user.refresh_trackers) == 1
348 assert user.refresh_trackers[0].revoked_at is not None
349
350
351 @pytest.mark.csrf(csrfprotect=True)
352 def test_refresh_token_csrf(app, client, get_message):
353 csrf_token = _get_csrf_token(client)
354 headers = {"X-CSRF-Token": csrf_token}
355
356 json_authenticate(client, headers=headers)
357 rcookie = client.get_cookie("fs_refresh")
358 assert rcookie is not None
359
360 response = client.post("/refresh-token", json={})
361 assert response.status_code == 400
362 assert response.json["response"]["errors"][0] == "The CSRF token is missing."
363
364 client.post("/refresh-token", json={}, headers=headers)
365 nrcookie = client.get_cookie("fs_refresh")
366 assert nrcookie is not None
367 ntdict = app.security.refresh_token_serializer.loads(nrcookie.value)
368 assert ntdict["gen"] == 2
369
370 # upon logout refresh tracker/token should have been revoked
371 client.post("/logout")
372 assert client.get_cookie("fs_rtoken_test") is None
373 with app.test_request_context("/"):
374 user = app.security.datastore.find_user(email="[email protected]")
375 assert len(user.refresh_trackers) == 1
376 assert user.refresh_trackers[0].revoked_at is not None
377
378
379 @pytest.mark.settings(token_max_age=60)
380 def test_auth_token_max_age_int(app, client_nc):
381 with app.app_context():
382 with freeze_time(datetime.now(timezone.utc) + timedelta(minutes=-3)):
383 response = json_authenticate(client_nc)
384 token = response.json["response"]["user"]["authentication_token"]
385 with pytest.raises(SignatureExpired):
386 parse_auth_token(token)
387
388
389 @pytest.mark.settings(token_max_age=timedelta(days=3))
390 def test_auth_token_max_age_delta(app, client_nc):
391 with app.app_context():
392 with freeze_time(datetime.now(timezone.utc) + timedelta(days=-5)):
393 response = json_authenticate(client_nc)
394 token = response.json["response"]["user"]["authentication_token"]
395 with pytest.raises(SignatureExpired):
396 parse_auth_token(token)
397
398
399 @pytest.mark.settings(token_max_age=0)
400 def test_auth_token_max_age_0(app, client_nc):
401 with app.app_context():
402 with freeze_time(datetime.now(timezone.utc) + timedelta(weeks=-1000)):
403 response = json_authenticate(client_nc)
404 token = response.json["response"]["user"]["authentication_token"]
405 with pytest.raises(SignatureExpired):
406 parse_auth_token(token)
407
408
409 @pytest.mark.settings(token_max_age=timedelta(days=6))
410 def test_per_user_expired_token(app, client_nc):
411 # Test expiry in auth_token using callable
412 with app.app_context():
413 with freeze_time(datetime.now(timezone.utc) + timedelta(days=-3)):
414
415 def exp(user):
416 assert user.email == "[email protected]"
417 return int((datetime.now(timezone.utc) + timedelta(days=1)).timestamp())
418
419 app.config["SECURITY_TOKEN_EXPIRE_TIMESTAMP"] = exp
420
421 response = json_authenticate(client_nc)
422 token = response.json["response"]["user"]["authentication_token"]
423 with pytest.raises(SignatureExpired) as e:
424 parse_auth_token(token)
425 assert "token[exp] value expired" in e.value.message
426
427
428 def test_per_user_not_expired_token(app, client_nc):
429 # Test expiry in auth_token using callable
430 def exp(user):
431 assert user.email == "[email protected]"
432 return int((datetime.now(timezone.utc) + timedelta(days=1)).timestamp())
433
434 app.config["SECURITY_TOKEN_EXPIRE_TIMESTAMP"] = exp
435
436 response = json_authenticate(client_nc)
437 token = response.json["response"]["user"]["authentication_token"]
438 verify_token(client_nc, token)