Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Refactor and improve jwt and regular api key handling

Roland Geidera33f47a1a7a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index abd41a76a..00659285f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,3 +7,8 @@
* Add a new, more efficient ingredient API endpoint (`/api/v2/ingredient-sync`)
for synchronizing the local database with an upstream wger server (note that
this is a fallback, the regular sync is still via the db dump)
+
+* JWT refresh tokens now rotate on every use. Combined with blacklist-after-rotation
+ this makes refresh tokens single-use and lets a leaked token live only until
+ the next refresh call. It's recommended to update your `prod.env` and set
+ `REFRESH_TOKEN_LIFETIME` to a value like 3000.
diff --git a/settings/main.py b/settings/main.py
index d9404d24b..42ff9c285 100644
--- a/settings/main.py
+++ b/settings/main.py
@@ -221,7 +221,7 @@ AXES_IPWARE_META_PRECEDENCE_ORDER = env.list(
# Django Rest Framework SimpleJWT
#
SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'] = timedelta(minutes=env.int('ACCESS_TOKEN_LIFETIME', 15))
-SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'] = timedelta(hours=env.int('REFRESH_TOKEN_LIFETIME', 24))
+SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'] = timedelta(hours=env.int('REFRESH_TOKEN_LIFETIME', 24 * 30 * 4))
_SIGNING_KEY = env.str('SIGNING_KEY', '')
if not _SIGNING_KEY or _SIGNING_KEY in _DEFAULT_KEYS:
_SIGNING_KEY = secrets.token_urlsafe(50)
diff --git a/settings/settings_global.py b/settings/settings_global.py
index e3f34af16..550063cc1 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -95,6 +95,7 @@ INSTALLED_APPS = [
'rest_framework.authtoken',
'django_filters',
'rest_framework_simplejwt',
+ 'rest_framework_simplejwt.token_blacklist',
'drf_spectacular',
'drf_spectacular_sidecar',
@@ -433,9 +434,9 @@ SPECTACULAR_SETTINGS = {
#
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
- 'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
- 'ROTATE_REFRESH_TOKENS': False,
- 'BLACKLIST_AFTER_ROTATION': False,
+ 'REFRESH_TOKEN_LIFETIME': timedelta(days=120),
+ 'ROTATE_REFRESH_TOKENS': True,
+ 'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
}
diff --git a/wger/core/tasks.py b/wger/core/tasks.py
new file mode 100644
index 000000000..c0b263c19
--- /dev/null
+++ b/wger/core/tasks.py
@@ -0,0 +1,55 @@
+# This file is part of wger Workout Manager.
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+# Standard Library
+import logging
+import random
+
+# Django
+from django.core.management import call_command
+
+# Third Party
+from celery.schedules import crontab
+
+# wger
+from wger.celery_configuration import app
+
+
+logger = logging.getLogger(__name__)
+
+
+def flush_expired_jwt_tokens_task():
+ """
+ Delete OutstandingToken rows whose refresh token has already expired.
+
+ With ROTATE_REFRESH_TOKENS enabled, every refresh creates a new
+ OutstandingToken (and blacklists the previous one). Without periodic
+ cleanup the table grows monotonically. simplejwt ships
+ ``flushexpiredtokens`` for exactly this; cascading FK takes care of
+ the matching BlacklistedToken rows.
+ """
+ call_command('flushexpiredtokens')
+
+
[email protected]_after_finalize.connect
+def setup_periodic_tasks(sender, **kwargs):
+ sender.add_periodic_task(
+ crontab(
+ hour=str(random.randint(0, 23)),
+ minute=str(random.randint(0, 59)),
+ ),
+ flush_expired_jwt_tokens_task.s(),
+ name='Flush expired JWT tokens',
+ )
diff --git a/wger/core/templates/user/api_key.html b/wger/core/templates/user/api_key.html
index 0917705c3..756412284 100644
--- a/wger/core/templates/user/api_key.html
+++ b/wger/core/templates/user/api_key.html
@@ -1,46 +1,54 @@
{% extends "base.html" %}
{% load i18n static wger_extras %}
-{% block title %}{% translate "API key" %}{% endblock %}
+{% block title %}{% translate "API access" %}{% endblock %}
{% block content %}
<p>
- Please use JWT authentication if possible. More details in the
- <a href="https://wger.readthedocs.io/en/latest/">online documentation</a>.
+ {% blocktranslate trimmed %}
+ Theare are two ways to authenticate against the API: JWT is the preferred
+ mechanism for client applications, the static API key is intended for personal
+ scripts or one-off integrations.
+ {% endblocktranslate %}
</p>
- <div class="card mb-4 {% if token %}text-white bg-success{% else %}bg-light{% endif %}">
- <div class="card-header">
- {% translate "Your API key" %}
- </div>
+ <h4 class="mt-4">{% translate "JWT sessions" %}</h4>
+
+ <p>
+ <button
+ type="button"
+ class="btn btn-block btn-light"
+ {% if not active_jwt_sessions %}disabled{% endif %}
+ hx-post="{% url 'core:user:api-key' %}"
+ hx-vals='{"revoke_jwt_sessions": "true"}'
+ hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
+ hx-target="body"
+ hx-push-url="true"
+ >
+ {% translate 'Revoke all JWT sessions' %}
+ </button>
+ </p>
+
+ <div class="card mb-4 {% if active_jwt_sessions %}text-white bg-success{% else %}bg-light{% endif %}">
<div class="card-body">
- {% if token %}
- <strong>{{ token.key }}</strong>
- {% else %}
- <em>{% translate "You have no API key yet" %}</em>
- {% endif %}
+ {% blocktranslate count counter=active_jwt_sessions %}
+ There is currently <strong>{{ counter }}</strong> active JWT session
+ {% plural %}
+ There are currently <strong>{{ counter }}</strong> active JWT sessions
+ {% endblocktranslate %}
</div>
</div>
<p>
- Pass "Token {% if token %}{{ token.key }}{% else %}1234567890abcde...{% endif %}" in the
- <code>Authorization</code> header to use it
+ {% blocktranslate trimmed %}
+ Revoking JWT sessions logs out every device that obtained a refresh token via the JWT login endpoint.
+ {% endblocktranslate %}
</p>
- <p>Example with curl:</p>
- <pre>
-curl -X GET https://wger.de/api/v2/routine/ \
- -H 'Authorization: Token {% if token %}{{ token.key }}{% else %}1234567890abcde...{% endif %}'
-</pre>
-
-{% endblock %}
-
+ <h4 class="mt-4">{% translate "API key" %}</h4>
-{% block sidebar %}
- <h4>{% translate "Options" %}</h4>
-
- <p>
+ <p>
<button
type="button"
class="btn btn-block btn-light"
@@ -58,8 +66,56 @@ curl -X GET https://wger.de/api/v2/routine/ \
</button>
</p>
+ {% if token %}
+ <p>
+ <button
+ type="button"
+ class="btn btn-block btn-light"
+ hx-post="{% url 'core:user:api-key' %}"
+ hx-vals='{"delete_key": "true"}'
+ hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
+ hx-target="body"
+ hx-push-url="true"
+ >
+ {% translate 'Delete API key' %}
+ </button>
+ </p>
+ {% endif %}
+
+ <div class="card mb-4 {% if token %}text-white bg-success{% else %}bg-light{% endif %}">
+ <div class="card-body">
+ {% if token %}
+ <strong>{{ token.key }}</strong>
+ {% else %}
+ <em>{% translate "You have no API key yet" %}</em>
+ {% endif %}
+ </div>
+ </div>
+
+ <p>
+ {% blocktranslate with key=token.key|default:"1234567890abcde..." %}
+ Pass <code>Token {{ key }}</code> in the
+ <code>Authorization</code> header to use it.
+ {% endblocktranslate %}
+ </p>
+
+ <p>{% translate "Example with curl:" %}</p>
+ <pre>
+curl -X GET https://wger.de/api/v2/routine/ \
+ -H 'Authorization: Token {% if token %}{{ token.key }}{% else %}1234567890abcde...{% endif %}'
+</pre>
+
+{% endblock %}
+
+
+{# #}
+{# Sidebar #}
+{# #}
+{% block sidebar %}
+
+ <h5 class="mt-4">{% translate "Documentation" %}</h5>
+
<p>
- <a href="{% url 'software:api' %}"
- class="btn btn-block btn-light">{% translate 'Documentation' %}</a>
+ <a href="{% url 'software:api' %}">{% translate 'API documentation' %}</a>
</p>
{% endblock %}
diff --git a/wger/core/tests/test_apikey.py b/wger/core/tests/test_apikey.py
index 9cf9b1b4b..7deb8790f 100644
--- a/wger/core/tests/test_apikey.py
+++ b/wger/core/tests/test_apikey.py
@@ -21,6 +21,11 @@ from django.urls import reverse
# Third Party
from rest_framework.authtoken.models import Token
+from rest_framework.test import APIClient
+from rest_framework_simplejwt.token_blacklist.models import (
+ BlacklistedToken,
+ OutstandingToken,
+)
# wger
from wger.core.tests.base_testcase import WgerTestCase
@@ -76,6 +81,35 @@ class ApiKeyTestCase(WgerTestCase):
# New key is different from the one before
self.assertNotEqual(key_before.key, key_after.key)
+ def test_api_key_can_be_deleted_without_replacement(self):
+ """
+ The "Delete API key" button removes the token without immediately
+ creating a new one. Distinct from rotation, which is the existing
+ ``new_key`` flow.
+ """
+ self.user_login('test')
+ user = User.objects.get(username='test')
+ self.assertTrue(Token.objects.filter(user=user).exists())
+
+ response = self.client.post(reverse('core:user:api-key'), {'delete_key': 'true'})
+ self.assertEqual(response.status_code, 302)
+
+ self.assertFalse(Token.objects.filter(user=user).exists())
+
+ def test_api_key_delete_requires_post(self):
+ """
+ Same CSRF-via-img-tag concern as rotation: a GET must not destroy
+ the user's token.
+ """
+ self.user_login('test')
+ user = User.objects.get(username='test')
+ key_before = Token.objects.get(user=user).key
+
+ response = self.client.get(reverse('core:user:api-key'), {'delete_key': 'true'})
+ self.assertEqual(response.status_code, 200)
+
+ self.assertEqual(Token.objects.get(user=user).key, key_before)
+
def test_api_key_rotation_requires_post(self):
"""
Token rotation is a state-changing action and must not be triggered
@@ -91,3 +125,104 @@ class ApiKeyTestCase(WgerTestCase):
key_after = Token.objects.get(user=user)
self.assertEqual(key_before.key, key_after.key)
+
+ def test_revoke_jwt_sessions_blacklists_outstanding_refresh_tokens(self):
+ """
+ The "Revoke all API sessions" button on /user/api-key has to
+ blacklist every still-usable refresh token for the current user,
+ and a previously-issued refresh must stop minting access tokens.
+ """
+ api = APIClient()
+ obtain = api.post(
+ '/api/v2/token',
+ {'username': 'test', 'password': 'testtest'},
+ format='json',
+ )
+ self.assertEqual(obtain.status_code, 200)
+ old_refresh = obtain.data['refresh']
+
+ # Sanity baseline before the revoke
+ refresh_before = api.post(
+ '/api/v2/token/refresh',
+ {'refresh': old_refresh},
+ format='json',
+ )
+ self.assertEqual(refresh_before.status_code, 200)
+
+ self.user_login('test')
+ response = self.client.post(
+ reverse('core:user:api-key'),
+ {'revoke_jwt_sessions': 'true'},
+ )
+ self.assertEqual(response.status_code, 302)
+
+ user = User.objects.get(username='test')
+ outstanding = OutstandingToken.objects.filter(user=user)
+ self.assertTrue(outstanding.exists())
+ for ot in outstanding:
+ self.assertTrue(BlacklistedToken.objects.filter(token=ot).exists())
+
+ refresh_after = api.post(
+ '/api/v2/token/refresh',
+ {'refresh': old_refresh},
+ format='json',
+ )
+ self.assertEqual(refresh_after.status_code, 401)
+
+ def test_revoke_jwt_sessions_only_touches_current_user(self):
+ """
+ Hitting the revoke button as user 'test' must not blacklist the
+ refresh tokens of an unrelated user (e.g. 'admin'). Cross-user
+ leakage here would be a one-call DoS.
+ """
+ api_admin = APIClient()
+ admin_obtain = api_admin.post(
+ '/api/v2/token',
+ {'username': 'admin', 'password': 'adminadmin'},
+ format='json',
+ )
+ self.assertEqual(admin_obtain.status_code, 200)
+ admin_refresh = admin_obtain.data['refresh']
+
+ self.user_login('test')
+ response = self.client.post(
+ reverse('core:user:api-key'),
+ {'revoke_jwt_sessions': 'true'},
+ )
+ self.assertEqual(response.status_code, 302)
+
+ # The admin's refresh token is untouched
+ admin_refresh_after = api_admin.post(
+ '/api/v2/token/refresh',
+ {'refresh': admin_refresh},
+ format='json',
+ )
+ self.assertEqual(admin_refresh_after.status_code, 200)
+
+ def test_revoke_jwt_sessions_requires_post(self):
+ """
+ Same CSRF concern as ``new_key``: a GET must not blacklist anything,
+ otherwise an attacker could embed an <img src=...> that silently
+ kills the victim's mobile sessions.
+ """
+ api = APIClient()
+ obtain = api.post(
+ '/api/v2/token',
+ {'username': 'test', 'password': 'testtest'},
+ format='json',
+ )
+ old_refresh = obtain.data['refresh']
+
+ self.user_login('test')
+ response = self.client.get(
+ reverse('core:user:api-key'),
+ {'revoke_jwt_sessions': 'true'},
+ )
+ self.assertEqual(response.status_code, 200)
+
+ refresh_after = api.post(
+ '/api/v2/token/refresh',
+ {'refresh': old_refresh},
+ format='json',
+ )
+ self.assertEqual(refresh_after.status_code, 200)
diff --git a/wger/core/tests/test_change_password.py b/wger/core/tests/test_change_password.py
index e3677180a..ebf7ab2f8 100644
--- a/wger/core/tests/test_change_password.py
+++ b/wger/core/tests/test_change_password.py
@@ -21,6 +21,10 @@ from django.contrib.auth.models import User
from django.test import Client
from django.urls import reverse
+# Third Party
+from rest_framework.authtoken.models import Token
+from rest_framework.test import APIClient
+
# wger
from wger.core.tests.base_testcase import WgerTestCase
@@ -112,3 +116,48 @@ class ChangePasswordTestCase(WgerTestCase):
response = browser_b.get(protected_url)
self.assertEqual(response.status_code, 302)
self.assertTrue(response['Location'].startswith(settings.LOGIN_URL))
+
+ def test_password_change_does_not_revoke_api_credentials(self):
+ """
+ Password change is intentionally session-scoped. The DRF API key and
+ any active JWT refresh tokens must keep working — they are managed
+ explicitly via the ``/user/api-key`` page (rotate the key, revoke
+ sessions). Same model as GitHub PATs. This test guards against the
+ coupling being silently re-introduced.
+ """
+ user = User.objects.get(username='test')
+ drf_token_key = Token.objects.get(user=user).key
+
+ api = APIClient()
+ obtain = api.post(
+ '/api/v2/token',
+ {'username': 'test', 'password': 'testtest'},
+ format='json',
+ )
+ self.assertEqual(obtain.status_code, 200)
+ old_refresh = obtain.data['refresh']
+
+ self.user_login('test')
+ response = self.client.post(
+ reverse('core:user:change-password'),
+ {
+ 'old_password': 'testtest',
+ 'new_password1': 'shuZoh2oGu7i',
+ 'new_password2': 'shuZoh2oGu7i',
+ },
+ )
+ self.assertEqual(response.status_code, 302)
+
+ # DRF token survives
+ self.assertTrue(Token.objects.filter(user=user, key=drf_token_key).exists())
+ api_drf = APIClient()
+ api_drf.credentials(HTTP_AUTHORIZATION=f'Token {drf_token_key}')
+ self.assertEqual(api_drf.get('/api/v2/weightentry/').status_code, 200)
+
+ # JWT refresh survives
+ refresh_after = api.post(
+ '/api/v2/token/refresh',
+ {'refresh': old_refresh},
+ format='json',
+ )
+ self.assertEqual(refresh_after.status_code, 200)
diff --git a/wger/core/views/user.py b/wger/core/views/user.py
index 7522ea0af..74f0c873f 100644
--- a/wger/core/views/user.py
+++ b/wger/core/views/user.py
@@ -101,7 +101,11 @@ from wger.manager.models import (
WorkoutSession,
)
from wger.nutrition.models import NutritionPlan
-from wger.utils.api_token import create_token
+from wger.utils.api_token import (
+ blacklist_jwt_refresh_tokens,
+ count_active_jwt_refresh_tokens,
+ create_token,
+)
from wger.utils.generic_views import (
WgerFormMixin,
WgerMultiplePermissionRequiredMixin,
@@ -556,7 +560,18 @@ def api_key(request):
# Redirect so a refresh doesn't try to rotate again
return HttpResponseRedirect(reverse('core:user:api-key'))
+ if request.method == 'POST' and request.POST.get('delete_key'):
+ Token.objects.filter(user=request.user).delete()
+ messages.success(request, _('API key was deleted'))
+ return HttpResponseRedirect(reverse('core:user:api-key'))
+
+ if request.method == 'POST' and request.POST.get('revoke_jwt_sessions'):
+ blacklist_jwt_refresh_tokens(request.user)
+ messages.success(request, _('All API sessions were revoked'))
+ return HttpResponseRedirect(reverse('core:user:api-key'))
+
context['token'] = token
+ context['active_jwt_sessions'] = count_active_jwt_refresh_tokens(request.user)
return render(request, 'user/api_key.html', context)
diff --git a/wger/utils/api_token.py b/wger/utils/api_token.py
index 721994f7b..68efbfd77 100644
--- a/wger/utils/api_token.py
+++ b/wger/utils/api_token.py
@@ -15,8 +15,15 @@
# Standard Library
import logging
+# Django
+from django.utils import timezone
+
# Third Party
from rest_framework.authtoken.models import Token
+from rest_framework_simplejwt.token_blacklist.models import (
+ BlacklistedToken,
+ OutstandingToken,
+)
logger = logging.getLogger(__name__)
@@ -42,3 +49,34 @@ def create_token(user, force_new=False):
token = Token.objects.create(user=user)
return token
+
+
+def _active_jwt_refresh_tokens(user):
+ """
+ Outstanding refresh tokens for ``user`` that are still usable: not yet
+ expired and not already blacklisted.
+ """
+ return OutstandingToken.objects.filter(
+ user=user,
+ expires_at__gt=timezone.now(),
+ blacklistedtoken__isnull=True,
+ )
+
+
+def count_active_jwt_refresh_tokens(user):
+ """
+ How many JWT refresh tokens are currently usable for ``user``.
+ """
+ return _active_jwt_refresh_tokens(user).count()
+
+
+def blacklist_jwt_refresh_tokens(user):
+ """
+ Blacklist every outstanding JWT refresh token belonging to ``user``.
+
+ Subsequent calls to ``/api/v2/token/refresh`` with these tokens are
+ rejected; the matching access tokens still work until their (much
+ shorter) lifetime expires.
+ """
+ for outstanding in _active_jwt_refresh_tokens(user):
+ BlacklistedToken.objects.get_or_create(token=outstanding)