Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Released TBD
Features & Improvements
+++++++++++++++++++++++
- (:issue:`1206`) Add support for refresh tokens. See :ref:`token_topic`
- (:pr:`1233`) Change :py:data:`SECURITY_TOKEN_MAX_AGE` from an int to a timedelta.
Also - change default from ``never expire`` to 15 minutes.

Fixes
+++++
Expand All @@ -25,6 +27,10 @@ Backwards Compatibility Concerns
+++++++++++++++++++++++++++++++++
- The fix for the inverted `is_locked` logic will require any application using it
to invert their logic.
- The change to :py:data:`SECURITY_TOKEN_MAX_AGE` default improves a long-standing
'insecure-out-of-the-box' issue. Applications will have to either change the
value if they really want a long-lasting token or use the new refresh token
feature.

Notes
+++++
Expand Down
9 changes: 7 additions & 2 deletions docs/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,14 @@ These configuration keys are used globally across all features.

.. py:data:: SECURITY_TOKEN_MAX_AGE

Specifies the number of seconds before an authentication token expires.
Specifies token expiration as a timedelta. Setting to 0 will mean the
token never expires.

Default: ``None``, meaning the token never expires.
Default: ``timedelta(minutes=15)``

.. versionchanged:: 5.9.0
Change from int to a timedelta. If an int is provided, it will be
changed to a timedelta as part of Flask-Security initialization.

.. py:data:: SECURITY_TOKEN_EXPIRE_TIMESTAMP

Expand Down
7 changes: 6 additions & 1 deletion flask_security/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@
"TWO_FACTOR_RESCUE_MAIL": "no-reply@localhost",
"TOKEN_AUTHENTICATION_KEY": "auth_token",
"TOKEN_AUTHENTICATION_HEADER": "Authentication-Token",
"TOKEN_MAX_AGE": None,
"TOKEN_MAX_AGE": timedelta(minutes=15),
"TOKEN_EXPIRE_TIMESTAMP": lambda user: 0,
"REFRESH_TOKEN": False,
"REFRESH_TOKEN_SALT": "refresh-token-salt",
Expand Down Expand Up @@ -1761,6 +1761,11 @@ def init_app(
" must have one and only one key."
)

if not isinstance(cv("TOKEN_MAX_AGE", app=app), timedelta):
app.config["SECURITY_TOKEN_MAX_AGE"] = timedelta(
seconds=cv("TOKEN_MAX_AGE", app=app)
)

self.login_manager = _get_login_manager(app, self)
self._phone_util = self._phone_util_cls(app)
self._mail_util = self._mail_util_cls(app)
Expand Down
1 change: 0 additions & 1 deletion flask_security/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
TODO
- add ability for app to add/verify additional stuff in refresh_token
- add endpoint to user can revoke refresh token?
- change TOKEN_MAX_AGE to accept timedelta and change default to 30minutes or so.
- implment rotation overlap period?:
https://auth0.com/docs/secure/tokens/refresh-tokens/configure-refresh-token-rotation

Expand Down
2 changes: 1 addition & 1 deletion flask_security/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ def parse_auth_token(auth_token: str) -> dict[str, t.Any]:

# This can raise BadSignature or SignatureExpired exceptions from itsdangerous
raw_data = _security.remember_token_serializer.loads(
auth_token, max_age=config_value("TOKEN_MAX_AGE")
auth_token, max_age=config_value("TOKEN_MAX_AGE").total_seconds()
)

# Version 3.x generated tokens that map to data with 3 elements,
Expand Down
31 changes: 0 additions & 31 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
"""

import base64
from datetime import datetime, timedelta, timezone
import json
import re
import pytest
Expand All @@ -19,7 +18,6 @@
from flask_security import uia_email_mapper
from flask_security.decorators import auth_required
from flask_principal import identity_loaded
from freezegun import freeze_time

from tests.conftest import v2_param
from tests.test_utils import (
Expand Down Expand Up @@ -729,35 +727,6 @@ def test_token_auth_invalid_for_session_auth(client):
assert response.status_code == 401


def test_per_user_expired_token(app, client_nc):
# Test expiry in auth_token using callable
with freeze_time("2024-01-01"):

def exp(user):
assert user.email == "matt@lp.com"
return int((datetime.now(timezone.utc) + timedelta(days=1)).timestamp())

app.config["SECURITY_TOKEN_EXPIRE_TIMESTAMP"] = exp

response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]

verify_token(client_nc, token, status=401)


def test_per_user_not_expired_token(app, client_nc):
# Test expiry in auth_token using callable
def exp(user):
assert user.email == "matt@lp.com"
return int((datetime.now(timezone.utc) + timedelta(days=1)).timestamp())

app.config["SECURITY_TOKEN_EXPIRE_TIMESTAMP"] = exp

response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
verify_token(client_nc, token)


def test_garbled_auth_token(app, client_nc):
# garble token
def augment_auth_token(tdata):
Expand Down
67 changes: 66 additions & 1 deletion tests/test_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@
:license: MIT, see LICENSE for more details.
"""

from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
import math

import pytest
from freezegun import freeze_time
from itsdangerous import SignatureExpired
from sqlalchemy import Column, String

from flask_security.datastore import PeeweeDatastore
from flask_security.tokens import RefreshTokenErrors
from flask_security.utils import parse_auth_token
from tests.test_csrf import _get_csrf_token
from tests.test_utils import (
check_signals,
Expand Down Expand Up @@ -371,3 +374,65 @@ def test_refresh_token_csrf(app, client, get_message):
user = app.security.datastore.find_user(email="matt@lp.com")
assert len(user.refresh_trackers) == 1
assert user.refresh_trackers[0].revoked_at is not None


@pytest.mark.settings(token_max_age=60)
def test_auth_token_max_age_int(app, client_nc):
with app.app_context():
with freeze_time(datetime.now(timezone.utc) + timedelta(minutes=-3)):
response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
with pytest.raises(SignatureExpired):
parse_auth_token(token)


@pytest.mark.settings(token_max_age=timedelta(days=3))
def test_auth_token_max_age_delta(app, client_nc):
with app.app_context():
with freeze_time(datetime.now(timezone.utc) + timedelta(days=-5)):
response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
with pytest.raises(SignatureExpired):
parse_auth_token(token)


@pytest.mark.settings(token_max_age=0)
def test_auth_token_max_age_0(app, client_nc):
with app.app_context():
with freeze_time(datetime.now(timezone.utc) + timedelta(weeks=-1000)):
response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
with pytest.raises(SignatureExpired):
parse_auth_token(token)


@pytest.mark.settings(token_max_age=timedelta(days=6))
def test_per_user_expired_token(app, client_nc):
# Test expiry in auth_token using callable
with app.app_context():
with freeze_time(datetime.now(timezone.utc) + timedelta(days=-3)):

def exp(user):
assert user.email == "matt@lp.com"
return int((datetime.now(timezone.utc) + timedelta(days=1)).timestamp())

app.config["SECURITY_TOKEN_EXPIRE_TIMESTAMP"] = exp

response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
with pytest.raises(SignatureExpired) as e:
parse_auth_token(token)
assert "token[exp] value expired" in e.value.message


def test_per_user_not_expired_token(app, client_nc):
# Test expiry in auth_token using callable
def exp(user):
assert user.email == "matt@lp.com"
return int((datetime.now(timezone.utc) + timedelta(days=1)).timestamp())

app.config["SECURITY_TOKEN_EXPIRE_TIMESTAMP"] = exp

response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
verify_token(client_nc, token)
1 change: 1 addition & 0 deletions tests/test_two_factor.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,6 +946,7 @@ def pc(sender, user, method, **kwargs):
assert response.json["response"]["tf_phone_number"] == "+442083661177"


@pytest.mark.settings(token_max_age=timedelta(days=4))
def test_opt_in_nc_expired(app, client_nc, get_message):
"""
Test tf-setup without cookies - expired token
Expand Down