Token issuance updates (#13214)

- Ensure all token issuance endpoints are explicitly checked for MFA auth
- Additional backend unit tests
- Additional frontend unit tests
This commit is contained in:
Oliver authored and GitHub committed 2026-11-07 13:18:30 +11:00
1 parent 0cb1852e0d
commit 02d6a038bf
8 files changed
+576 -254

No files matched your search

+33 -10
View File
@@ -379,6 +379,34 @@ class RuleSetDetail(RuleSetMixin, RetrieveUpdateDestroyAPI):
"""Detail endpoint for a particular RuleSet instance."""
def check_token_reauthentication(request) -> Response | None:
"""Check that a user is allowed to be issued a new API token.
If the user has MFA enabled, they must have recently (re)authenticated
before a new token can be issued. Otherwise a stolen (or aged) session
could be converted into a long-lived API token without the second factor.
This check must be applied to *every* API endpoint which issues new tokens.
Returns:
None if the user may be issued a token, or a 401 response
describing the required reauthentication flows.
"""
user = request.user
if is_mfa_enabled(user) and not did_recently_authenticate(request):
return Response(
{
'id': 'reauthentication_required',
'detail': _('Reauthentication is required to generate a token'),
'data': {'flows': get_reauthentication_flows(user)},
},
status=status.HTTP_401_UNAUTHORIZED,
)
return None
class GetAuthToken(GenericAPIView):
"""Return authentication token for an authenticated user."""
@@ -409,16 +437,8 @@ class GetAuthToken(GenericAPIView):
if not user.is_authenticated:
raise exceptions.NotAuthenticated() # pragma: no cover
# does this user have MFA set up? if so: was he recently verified?
if is_mfa_enabled(user) and not did_recently_authenticate(request):
return Response(
{
'id': 'reauthentication_required',
'detail': _('Reauthentication is required to generate a token'),
'data': {'flows': get_reauthentication_flows(user)},
},
status=status.HTTP_401_UNAUTHORIZED,
)
if reauth_response := check_token_reauthentication(request):
return reauth_response
name = ApiToken.sanitize_name(name)
@@ -533,6 +553,9 @@ class TokenListView(TokenMixin, ListCreateAPI):
def create(self, request, *args, **kwargs):
"""Create token and show key to user."""
if reauth_response := check_token_reauthentication(request):
return reauth_response
resp = super().create(request, *args, **kwargs)
resp.data['token'] = self._created_token.token
+67
View File
@@ -1,12 +1,15 @@
"""API tests for various user / auth API endpoints."""
import datetime
import time
from unittest import mock
from django.contrib.auth.models import Group, User
from django.urls import reverse
from allauth.account.internal.flows.login import AUTHENTICATION_METHODS_SESSION_KEY
from allauth.account.models import EmailAddress
from allauth.mfa.models import Authenticator
import InvenTree.helpers
from common.models import NotificationMessage
@@ -765,6 +768,70 @@ class UserTokenTests(InvenTreeAPITestCase):
self.assertEqual(token.token_version, 2)
self.assertIsNone(token.last_seen)
def set_auth_time(self, age: float):
"""Record an allauth authentication event in the test client session.
Arguments:
age: How many seconds ago the authentication occurred
"""
session = self.client.session
session[AUTHENTICATION_METHODS_SESSION_KEY] = [
{'method': 'mfa', 'type': 'totp', 'at': time.time() - age}
]
session.save()
def test_token_mfa_reauthentication(self):
"""Test that MFA users must have recently authenticated to mint a token.
Every endpoint which issues a new API token must enforce this check.
Otherwise an aged (or stolen) session could be converted into a
long-lived API token without the second factor.
"""
Authenticator.objects.create(
user=self.user, type=Authenticator.Type.TOTP, data={'secret': 'abc'}
)
n_tokens = ApiToken.objects.filter(user=self.user).count()
endpoints = [
lambda name: self.get(
reverse('api-token'), data={'name': name}, expected_code=None
),
lambda name: self.get(
reverse('api-token_legacy'), data={'name': name}, expected_code=None
),
lambda name: self.post(
reverse('api-token-list'), data={'name': name}, expected_code=None
),
]
# No authentication record, or an aged one: reauthentication is required
for age in [None, 600]:
if age is not None:
self.set_auth_time(age)
for idx, mint in enumerate(endpoints):
response = mint(f'mfa-{age}-{idx}')
self.assertEqual(response.status_code, 401, response.data)
self.assertEqual(response.data['id'], 'reauthentication_required')
flows = [flow['id'] for flow in response.data['data']['flows']]
self.assertIn('mfa_reauthenticate', flows)
# No tokens were issued
self.assertEqual(ApiToken.objects.filter(user=self.user).count(), n_tokens)
# After recent (re)authentication, tokens can be issued
self.set_auth_time(10)
self.get(reverse('api-token'), data={'name': 'mfa-ok-0'}, expected_code=200)
response = self.post(
reverse('api-token-list'), data={'name': 'mfa-ok-1'}, expected_code=201
)
self.assertIn('token', response.data)
self.assertEqual(ApiToken.objects.filter(user=self.user).count(), n_tokens + 2)
def test_token_v1(self):
"""Test that v1 API tokens still work."""
# Create a v1 token via model - this is NOT recommended; use v2 tokens