mirror of
https://github.com/inventree/InvenTree.git
synced 2026-11-25 09:13:08 +00:00
[bug] Fix for token issuance via UI (#13307)
- Fixes bug where non-staff users could not generate (or revoke) their own tokens via the API - Closes https://github.com/inventree/InvenTree/issues/13299
This commit is contained in:
1 parent
ec23dcfdb8
commit
8f8502d0d9
5 files changed
+174
-19
No files matched your search
@@ -136,20 +136,10 @@ class InvenTreeMetadata(SimpleMetadata):
|
||||
role_required and check_user_role(user, role_required, permission)
|
||||
)
|
||||
|
||||
# check if simple IsAuthenticated permission class is used
|
||||
# Views guarded only by an "any authenticated user" permission class
|
||||
# do not require model permissions (e.g. users managing their own API tokens)
|
||||
if not result:
|
||||
result = (
|
||||
view.permission_classes
|
||||
and len(view.permission_classes) == 1
|
||||
and any(
|
||||
perm
|
||||
in [
|
||||
permissions.IsAuthenticated,
|
||||
InvenTree.permissions.IsAuthenticatedOrReadScope,
|
||||
]
|
||||
for perm in view.permission_classes
|
||||
)
|
||||
)
|
||||
result = self.allows_any_authenticated_user(view)
|
||||
|
||||
if method in actions and not result:
|
||||
del actions[method]
|
||||
@@ -173,6 +163,24 @@ class InvenTreeMetadata(SimpleMetadata):
|
||||
|
||||
return metadata
|
||||
|
||||
@staticmethod
|
||||
def allows_any_authenticated_user(view) -> bool:
|
||||
"""Return True if the view is guarded by a single permission class which grants access to any authenticated user.
|
||||
|
||||
Such views do not require model / role permissions,
|
||||
so the available actions should not be filtered by them.
|
||||
"""
|
||||
permission_classes = getattr(view, 'permission_classes', None) or []
|
||||
|
||||
if len(permission_classes) != 1:
|
||||
return False
|
||||
|
||||
perm = permission_classes[0]
|
||||
|
||||
return perm is permissions.IsAuthenticated or bool(
|
||||
getattr(perm, 'allows_any_authenticated_user', False)
|
||||
)
|
||||
|
||||
def get_filter_metadata(self, request, view) -> dict:
|
||||
"""Return information on the choice filters available for an API endpoint.
|
||||
|
||||
|
||||
@@ -367,6 +367,10 @@ class IsSuperuserOrReadOnlyOrScope(OASTokenMixin, permissions.IsAdminUser):
|
||||
class IsAuthenticatedOrReadScope(OASTokenMixin, permissions.IsAuthenticated):
|
||||
"""Allows access only to authenticated users or read / write scope tokens."""
|
||||
|
||||
# Any authenticated user may access the endpoint, regardless of model permissions
|
||||
# (see InvenTreeMetadata.determine_metadata)
|
||||
allows_any_authenticated_user = True
|
||||
|
||||
def get_required_alternate_scopes(self, request, view):
|
||||
"""Return the required scopes for the current request."""
|
||||
return map_scope(
|
||||
@@ -383,6 +387,10 @@ class IsAuthenticatedNotOAuth2(OASTokenMixin, permissions.IsAuthenticated):
|
||||
a scoped OAuth2 token must not be able to obtain an unscoped credential.
|
||||
"""
|
||||
|
||||
# Any authenticated user may access the endpoint, regardless of model permissions
|
||||
# (see InvenTreeMetadata.determine_metadata)
|
||||
allows_any_authenticated_user = True
|
||||
|
||||
def get_required_alternate_scopes(self, request, view):
|
||||
"""No scope grants access to this endpoint."""
|
||||
return {}
|
||||
|
||||
@@ -1021,6 +1021,77 @@ class UserTokenTests(InvenTreeAPITestCase):
|
||||
self.assertIsNotNone(response_data.get('database'))
|
||||
|
||||
|
||||
class UnprivilegedUserTokenTests(InvenTreeAPITestCase):
|
||||
"""Token tests for a non-staff user without any assigned roles.
|
||||
|
||||
Regression tests for https://github.com/inventree/InvenTree/issues/13299
|
||||
"""
|
||||
|
||||
fixtures = ['users']
|
||||
is_staff = False
|
||||
roles = []
|
||||
|
||||
def test_user_is_unprivileged(self):
|
||||
"""Sanity check: the test user has no elevated access."""
|
||||
self.assertFalse(self.user.is_staff)
|
||||
self.assertFalse(self.user.is_superuser)
|
||||
self.assertFalse(self.user.has_perm('users.view_apitoken'))
|
||||
self.assertFalse(self.user.has_perm('users.add_apitoken'))
|
||||
|
||||
def test_token_options(self):
|
||||
"""The OPTIONS metadata must advertise token creation to any authenticated user.
|
||||
|
||||
The frontend builds the "Generate Token" form from these actions,
|
||||
so missing actions prevent users from minting their own tokens.
|
||||
"""
|
||||
# Token generation endpoint (used by the frontend)
|
||||
actions = self.options(reverse('api-token'), expected_code=200).data['actions']
|
||||
self.assertIn('GET', actions)
|
||||
self.assertIn('name', actions['GET'])
|
||||
|
||||
# Token list / create endpoint
|
||||
actions = self.options(reverse('api-token-list'), expected_code=200).data[
|
||||
'actions'
|
||||
]
|
||||
self.assertIn('GET', actions)
|
||||
self.assertIn('POST', actions)
|
||||
self.assertIn('name', actions['POST'])
|
||||
|
||||
def test_token_create_and_revoke(self):
|
||||
"""An unprivileged user can create, list and revoke their own tokens."""
|
||||
# Generate via the 'me' endpoint
|
||||
data = self.get(
|
||||
reverse('api-token'), data={'name': 'via-get'}, expected_code=200
|
||||
).data
|
||||
self.assertTrue(data['token'].startswith('inv-'))
|
||||
|
||||
# Create via the token list endpoint
|
||||
data = self.post(
|
||||
reverse('api-token-list'), data={'name': 'via-post'}, expected_code=201
|
||||
).data
|
||||
self.assertTrue(data['token'].startswith('inv-'))
|
||||
|
||||
tokens = self.get(reverse('api-token-list'), expected_code=200).data
|
||||
self.assertEqual({t['name'] for t in tokens}, {'via-get', 'via-post'})
|
||||
|
||||
for token in ApiToken.objects.filter(user=self.user):
|
||||
self.delete(
|
||||
reverse('api-token-detail', kwargs={'pk': token.pk}), expected_code=204
|
||||
)
|
||||
token.refresh_from_db()
|
||||
self.assertTrue(token.revoked)
|
||||
|
||||
def test_no_model_permission_bypass(self):
|
||||
"""The authenticated-user fallback must not expose actions on role-protected endpoints."""
|
||||
self.assignRole('part.view')
|
||||
|
||||
actions = self.options(reverse('api-part-list'), expected_code=200).data[
|
||||
'actions'
|
||||
]
|
||||
self.assertIn('GET', actions)
|
||||
self.assertNotIn('POST', actions)
|
||||
|
||||
|
||||
class GroupDetailTests(InvenTreeAPITestCase):
|
||||
"""Tests for the GroupDetail API endpoint."""
|
||||
|
||||
|
||||
Reference in new issue
Block a user