From 8f8502d0d9e0cebb726430746e39327c51845a8a Mon Sep 17 00:00:00 2001 From: Oliver Date: Tue, 17 Nov 2026 22:03:48 +1100 Subject: [PATCH] [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 --- src/backend/InvenTree/InvenTree/metadata.py | 34 +++++---- .../InvenTree/InvenTree/permissions.py | 8 ++ src/backend/InvenTree/users/test_api.py | 71 ++++++++++++++++++ .../src/tables/settings/ApiTokenTable.tsx | 7 +- src/frontend/tests/pui_settings.spec.ts | 73 +++++++++++++++++-- 5 files changed, 174 insertions(+), 19 deletions(-) diff --git a/src/backend/InvenTree/InvenTree/metadata.py b/src/backend/InvenTree/InvenTree/metadata.py index 576c849150..347a3d91db 100644 --- a/src/backend/InvenTree/InvenTree/metadata.py +++ b/src/backend/InvenTree/InvenTree/metadata.py @@ -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. diff --git a/src/backend/InvenTree/InvenTree/permissions.py b/src/backend/InvenTree/InvenTree/permissions.py index 0dd05aa538..8543e69cca 100644 --- a/src/backend/InvenTree/InvenTree/permissions.py +++ b/src/backend/InvenTree/InvenTree/permissions.py @@ -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 {} diff --git a/src/backend/InvenTree/users/test_api.py b/src/backend/InvenTree/users/test_api.py index a4a1b0246b..45841a57dc 100644 --- a/src/backend/InvenTree/users/test_api.py +++ b/src/backend/InvenTree/users/test_api.py @@ -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.""" diff --git a/src/frontend/src/tables/settings/ApiTokenTable.tsx b/src/frontend/src/tables/settings/ApiTokenTable.tsx index 5d795ee279..e00ecd2a97 100644 --- a/src/frontend/src/tables/settings/ApiTokenTable.tsx +++ b/src/frontend/src/tables/settings/ApiTokenTable.tsx @@ -21,6 +21,7 @@ import { Textarea } from '@mantine/core'; import { useDisclosure } from '@mantine/hooks'; +import { notifications } from '@mantine/notifications'; import { IconAlertTriangle, IconCircleX } from '@tabler/icons-react'; import { useCallback, useMemo, useState } from 'react'; import { api } from '../../App'; @@ -212,6 +213,10 @@ export function ApiTokenTable({ table.refreshTable(); setRevokeTokenId(null); setRevocationReason(''); + notifications.show({ + title: t`Token revoked`, + message: t`The token has been successfully revoked` + }); }) .catch((error) => { showApiErrorMessage({ @@ -270,7 +275,7 @@ export function ApiTokenTable({ setRevokeTokenId(null); setRevocationReason(''); }} - title={t`Revoke Token`} + title={{t`Revoke Token`}} centered >