mirror of
https://github.com/inventree/InvenTree.git
synced 2026-12-03 12:51:34 +00:00
User role checks for action endpoints (#13410)
* User role checks for action endpoints * fix broken playwright test
This commit is contained in:
1 parent
11ace83fb4
commit
f2b98ff286
11 files changed
+225
-8
No files matched your search
@@ -1,11 +1,15 @@
|
||||
"""InvenTree API version information."""
|
||||
|
||||
# InvenTree API version
|
||||
INVENTREE_API_VERSION = 585
|
||||
INVENTREE_API_VERSION = 586
|
||||
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
|
||||
|
||||
INVENTREE_API_TEXT = """
|
||||
|
||||
v586 -> 2026-11-29 : https://github.com/inventree/InvenTree/pull/13410
|
||||
- Stock, build and order "action" endpoints now require the correct user role action (e.g. "change") rather than "add"
|
||||
- Deleting build outputs now requires the "build.delete" role
|
||||
|
||||
v585 -> 2026-11-23 : https://github.com/inventree/InvenTree/pull/13356
|
||||
- Adds "locked" field to the instance-info API endpoint as a new generic model mixin is added for lockable models
|
||||
|
||||
|
||||
@@ -211,8 +211,26 @@ class ModelPermission(permissions.DjangoModelPermissions):
|
||||
"""Custom ModelPermission implementation which provides cached lookup of queryset.
|
||||
|
||||
This is entirely for optimization purposes.
|
||||
|
||||
If the view explicitly declares a 'role_required' attribute (and is protected
|
||||
by RolePermission), the Django model permission check is skipped, and the
|
||||
declared role is authoritative. This is required for "action" endpoints
|
||||
(e.g. stock adjustments, order state transitions) which are implemented
|
||||
as POST requests, but perform 'change' (or 'delete') operations. Otherwise,
|
||||
the default mapping (POST -> add_<model>) would require the wrong permission.
|
||||
"""
|
||||
|
||||
def has_permission(self, request, view):
|
||||
"""Check model permissions, deferring to RolePermission where a role is declared."""
|
||||
if getattr(view, 'role_required', None) and any(
|
||||
isinstance(pc, type) and issubclass(pc, RolePermission)
|
||||
for pc in getattr(view, 'permission_classes', [])
|
||||
):
|
||||
user = getattr(request, 'user', None)
|
||||
return bool(user and user.is_authenticated)
|
||||
|
||||
return super().has_permission(request, view)
|
||||
|
||||
def _queryset(self, view):
|
||||
"""Return the queryset associated with this view, with caching.
|
||||
|
||||
|
||||
@@ -1214,3 +1214,77 @@ class GeneralApiTests(InvenTreeAPITestCase):
|
||||
lookup_url('user', 'password__startswith', 'x'), expected_code=400
|
||||
)
|
||||
self.assertIn('Invalid lookup field', str(response.data))
|
||||
|
||||
|
||||
class RolePermissionCoverageTests(TestCase):
|
||||
"""Ensure that write API endpoints do not bypass the RolePermission check."""
|
||||
|
||||
def test_write_views_have_role(self):
|
||||
"""Every write view using RolePermission must resolve a model or role.
|
||||
|
||||
Views whose serializer has no Meta.model (e.g. action endpoints backed by
|
||||
a plain Serializer) cause RolePermission to skip the role check, leaving
|
||||
only the DjangoModelPermissions check (which maps POST to 'add').
|
||||
Such views must declare 'role_required' explicitly.
|
||||
"""
|
||||
from django.urls import URLPattern, URLResolver, get_resolver
|
||||
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from InvenTree.permissions import RolePermission, get_model_for_view
|
||||
|
||||
offenders = set()
|
||||
|
||||
def walk(patterns):
|
||||
for entry in patterns:
|
||||
if isinstance(entry, URLResolver):
|
||||
walk(entry.url_patterns)
|
||||
continue
|
||||
|
||||
if not isinstance(entry, URLPattern):
|
||||
continue
|
||||
|
||||
cls = getattr(entry.callback, 'view_class', None) or getattr(
|
||||
entry.callback, 'cls', None
|
||||
)
|
||||
|
||||
if not cls or not issubclass(cls, APIView):
|
||||
continue
|
||||
|
||||
if not any(
|
||||
issubclass(pc, RolePermission) for pc in cls.permission_classes
|
||||
):
|
||||
continue
|
||||
|
||||
if getattr(cls, 'role_required', None):
|
||||
continue
|
||||
|
||||
if not any(
|
||||
hasattr(cls, method)
|
||||
for method in ('post', 'put', 'patch', 'delete')
|
||||
):
|
||||
continue
|
||||
|
||||
view = cls()
|
||||
view.request = None
|
||||
view.kwargs = {}
|
||||
view.format_kwarg = None
|
||||
|
||||
try:
|
||||
if get_model_for_view(view) is not None:
|
||||
continue
|
||||
except AttributeError:
|
||||
pass
|
||||
except Exception:
|
||||
# Model cannot be determined without a real request
|
||||
continue
|
||||
|
||||
offenders.add(f'{cls.__module__}.{cls.__name__}')
|
||||
|
||||
walk(get_resolver().url_patterns)
|
||||
|
||||
self.assertEqual(
|
||||
sorted(offenders),
|
||||
[],
|
||||
'API views must define role_required when no model can be determined',
|
||||
)
|
||||
@@ -440,6 +440,7 @@ class BuildUnallocate(CreateAPI):
|
||||
"""
|
||||
|
||||
queryset = Build.objects.none()
|
||||
role_required = 'build.change'
|
||||
|
||||
serializer_class = build.serializers.BuildUnallocationSerializer
|
||||
|
||||
@@ -749,6 +750,9 @@ class BuildOrderContextMixin(ActionLockMixin):
|
||||
|
||||
lock_model = Build
|
||||
|
||||
# Action endpoints use plain serializers, so the required role must be explicit
|
||||
role_required = 'build.change'
|
||||
|
||||
def get_build(self):
|
||||
"""Return the Build object associated with this API endpoint."""
|
||||
try:
|
||||
@@ -791,6 +795,7 @@ class BuildOutputCreate(BuildOrderContextMixin, CreateAPI):
|
||||
"""API endpoint for creating new build output(s)."""
|
||||
|
||||
queryset = Build.objects.none()
|
||||
role_required = 'build.add'
|
||||
|
||||
serializer_class = build.serializers.BuildOutputCreateSerializer
|
||||
pagination_class = None
|
||||
@@ -910,6 +915,7 @@ class BuildOutputDelete(BuildOrderContextMixin, CreateAPI):
|
||||
return ctx
|
||||
|
||||
queryset = Build.objects.none()
|
||||
role_required = 'build.delete'
|
||||
serializer_class = build.serializers.BuildOutputDeleteSerializer
|
||||
|
||||
@extend_schema(responses={200: common.serializers.TaskDetailSerializer})
|
||||
|
||||
@@ -382,6 +382,8 @@ class BuildTest(BuildAPITest):
|
||||
|
||||
def test_create_delete_output(self):
|
||||
"""Test that we can create and delete build outputs via the API."""
|
||||
self.assignRole('build.delete')
|
||||
|
||||
bo = Build.objects.get(pk=1)
|
||||
|
||||
n_outputs = bo.output_count
|
||||
@@ -1839,6 +1841,8 @@ class BuildOutputCancelTest(BuildAPITest):
|
||||
|
||||
def test_cancel_output(self):
|
||||
"""Test cancellation of a build output."""
|
||||
self.assignRole('build.delete')
|
||||
|
||||
build = Build.objects.get(pk=1)
|
||||
build.part.trackable = True
|
||||
build.part.save()
|
||||
@@ -3519,7 +3523,7 @@ class BuildActionMissingPkTest(InvenTreeAPITestCase):
|
||||
rather than a clean 404. Fixed by BuildOrderContextMixin.create().
|
||||
"""
|
||||
|
||||
roles = ['build.add']
|
||||
roles = ['build.add', 'build.change', 'build.delete']
|
||||
|
||||
def test_actions_404_for_missing_build(self):
|
||||
"""Every BuildOrderContextMixin-based action should 404, not 500, for a bad pk."""
|
||||
@@ -3549,3 +3553,45 @@ class BuildActionMissingPkTest(InvenTreeAPITestCase):
|
||||
]:
|
||||
url = reverse(url_name, kwargs={'pk': 999999})
|
||||
self.post(url, {}, expected_code=404)
|
||||
|
||||
|
||||
class BuildActionRoleTest(InvenTreeAPITestCase):
|
||||
"""Build action endpoints must require the correct role action.
|
||||
|
||||
These endpoints use plain serializers, so the required role is declared
|
||||
explicitly via 'role_required'. Previously only the Django 'add' model
|
||||
permission was checked, so users with 'change' (but not 'add') were rejected.
|
||||
"""
|
||||
|
||||
fixtures = ['category', 'part', 'location', 'bom', 'build', 'build_line', 'stock']
|
||||
|
||||
roles = ['build.view']
|
||||
|
||||
def test_cancel_requires_change(self):
|
||||
"""Cancelling a build requires 'change', and does not require 'add'."""
|
||||
bo = Build.objects.get(pk=1)
|
||||
status = bo.status
|
||||
url = reverse('api-build-cancel', kwargs={'pk': bo.pk})
|
||||
|
||||
self.post(url, {}, expected_code=403)
|
||||
bo.refresh_from_db()
|
||||
self.assertEqual(bo.status, status)
|
||||
|
||||
# Grant 'change' only (no 'add')
|
||||
self.assignRole('build.change')
|
||||
self.assertFalse(self.group.rule_sets.get(name='build').can_add)
|
||||
|
||||
self.post(url, {}, expected_code=201)
|
||||
bo.refresh_from_db()
|
||||
self.assertEqual(bo.status, BuildStatus.CANCELLED)
|
||||
|
||||
def test_output_delete_requires_delete(self):
|
||||
"""Deleting build outputs requires the 'delete' role."""
|
||||
url = reverse('api-build-output-delete', kwargs={'pk': 1})
|
||||
|
||||
self.assignRole('build.change')
|
||||
self.post(url, {'outputs': []}, expected_code=403)
|
||||
|
||||
# Request now passes the permission check (and fails validation)
|
||||
self.assignRole('build.delete')
|
||||
self.post(url, {'outputs': []}, expected_code=400)
|
||||
@@ -1187,6 +1187,9 @@ class SalesOrderContextMixin(ActionLockMixin):
|
||||
# The order row is locked for the duration of the action
|
||||
lock_model = models.SalesOrder
|
||||
|
||||
# Action endpoints use plain serializers, so the required role must be explicit
|
||||
role_required = 'sales_order.change'
|
||||
|
||||
def get_order(self):
|
||||
"""Return the SalesOrder object associated with this API endpoint."""
|
||||
pk = self.kwargs.get('pk', None)
|
||||
@@ -1784,6 +1787,9 @@ class ReturnOrderContextMixin(ActionLockMixin):
|
||||
# The order row is locked for the duration of the action
|
||||
lock_model = models.ReturnOrder
|
||||
|
||||
# Action endpoints use plain serializers, so the required role must be explicit
|
||||
role_required = 'return_order.change'
|
||||
|
||||
def get_order(self):
|
||||
"""Return the ReturnOrder object associated with this API endpoint."""
|
||||
pk = self.kwargs.get('pk', None)
|
||||
@@ -2096,6 +2102,9 @@ class TransferOrderContextMixin(ActionLockMixin):
|
||||
# The order row is locked for the duration of the action
|
||||
lock_model = models.TransferOrder
|
||||
|
||||
# Action endpoints use plain serializers, so the required role must be explicit
|
||||
role_required = 'transfer_order.change'
|
||||
|
||||
def get_order(self):
|
||||
"""Return the TransferOrder object associated with this API endpoint."""
|
||||
pk = self.kwargs.get('pk', None)
|
||||
|
||||
@@ -2914,10 +2914,13 @@ class SalesOrderTest(OrderTest):
|
||||
|
||||
url = reverse('api-so-cancel', kwargs={'pk': so.pk})
|
||||
|
||||
# Try to cancel, without permission
|
||||
# Try to cancel, without permission ('view' only)
|
||||
self.clearRoles()
|
||||
self.assignRole('sales_order.view')
|
||||
self.post(url, {}, expected_code=403)
|
||||
|
||||
self.assignRole('sales_order.add')
|
||||
# The 'change' role is sufficient (the 'add' role is not required)
|
||||
self.assignRole('sales_order.change')
|
||||
|
||||
self.post(url, {}, expected_code=201)
|
||||
|
||||
@@ -5217,10 +5220,13 @@ class TransferOrderTest(OrderTest):
|
||||
|
||||
url = reverse('api-transfer-order-cancel', kwargs={'pk': to.pk})
|
||||
|
||||
# Try to cancel, without permission
|
||||
# Try to cancel, without permission ('view' only)
|
||||
self.clearRoles()
|
||||
self.assignRole('transfer_order.view')
|
||||
self.post(url, {}, expected_code=403)
|
||||
|
||||
self.assignRole('transfer_order.add')
|
||||
# The 'change' role is sufficient (the 'add' role is not required)
|
||||
self.assignRole('transfer_order.change')
|
||||
|
||||
self.post(url, {}, expected_code=201)
|
||||
|
||||
@@ -5269,10 +5275,13 @@ class TransferOrderTest(OrderTest):
|
||||
|
||||
url = reverse('api-transfer-order-hold', kwargs={'pk': to.pk})
|
||||
|
||||
# Try to hold, without permission
|
||||
# Try to hold, without permission ('view' only)
|
||||
self.clearRoles()
|
||||
self.assignRole('transfer_order.view')
|
||||
self.post(url, {}, expected_code=403)
|
||||
|
||||
self.assignRole('transfer_order.add')
|
||||
# The 'change' role is sufficient (the 'add' role is not required)
|
||||
self.assignRole('transfer_order.change')
|
||||
|
||||
self.post(url, {}, expected_code=201)
|
||||
|
||||
|
||||
@@ -1214,6 +1214,7 @@ class PartStocktakeGenerate(CreateAPI):
|
||||
|
||||
queryset = PartStocktake.objects.all()
|
||||
serializer_class = part_serializers.PartStocktakeGenerateSerializer
|
||||
role_required = 'part.add'
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
"""Perform stocktake generation on POST request."""
|
||||
@@ -1491,6 +1492,7 @@ class BomItemValidate(UpdateAPI):
|
||||
|
||||
queryset = BomItem.objects.all()
|
||||
serializer_class = BomItemValidationSerializer
|
||||
role_required = 'bom.change'
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
"""Perform update request."""
|
||||
|
||||
@@ -234,6 +234,9 @@ class StockAdjustView(CreateAPI):
|
||||
|
||||
queryset = StockItem.objects.none()
|
||||
|
||||
# Action endpoints use plain serializers, so the required role must be explicit
|
||||
role_required = 'stock.change'
|
||||
|
||||
def get_serializer_context(self):
|
||||
"""Extend serializer context."""
|
||||
context = super().get_serializer_context()
|
||||
@@ -288,6 +291,7 @@ class StockAssign(CreateAPI):
|
||||
|
||||
queryset = StockItem.objects.all()
|
||||
serializer_class = StockSerializers.StockAssignmentSerializer
|
||||
role_required = 'stock.change'
|
||||
|
||||
def get_serializer_context(self):
|
||||
"""Extend serializer context."""
|
||||
@@ -302,6 +306,7 @@ class StockMerge(CreateAPI):
|
||||
|
||||
queryset = StockItem.objects.none()
|
||||
serializer_class = StockSerializers.StockMergeSerializer
|
||||
role_required = 'stock.change'
|
||||
|
||||
def get_serializer_context(self):
|
||||
"""Extend serializer context."""
|
||||
|
||||
@@ -5404,3 +5404,45 @@ class StockApiPerformanceTest(StockAPITestCase, InvenTreeAPIPerformanceTestCase)
|
||||
url = reverse('api-stock-list')
|
||||
response = self.get(url, expected_code=200)
|
||||
self.assertGreater(len(response.data), 13)
|
||||
|
||||
|
||||
class StockAdjustRoleTest(StockAPITestCase):
|
||||
"""Stock adjustment endpoints must require the 'stock.change' role.
|
||||
|
||||
These endpoints use plain serializers, so the required role is declared
|
||||
explicitly via 'role_required'. Previously only the Django 'add' model
|
||||
permission was checked, so users with 'change' (but not 'add') were rejected.
|
||||
"""
|
||||
|
||||
roles = ['stock.view']
|
||||
|
||||
ENDPOINTS = [
|
||||
'api-stock-count',
|
||||
'api-stock-add',
|
||||
'api-stock-remove',
|
||||
'api-stock-transfer',
|
||||
'api-stock-return',
|
||||
'api-stock-change-status',
|
||||
'api-stock-merge',
|
||||
'api-stock-assign',
|
||||
]
|
||||
|
||||
def test_adjust_requires_change(self):
|
||||
"""Stock adjustments require 'change', and do not require 'add'."""
|
||||
item = StockItem.objects.get(pk=1234)
|
||||
quantity = item.quantity
|
||||
data = {'items': [{'pk': item.pk, 'quantity': 1}]}
|
||||
|
||||
for name in self.ENDPOINTS:
|
||||
self.post(reverse(name), data, expected_code=403, msg=name)
|
||||
|
||||
item.refresh_from_db()
|
||||
self.assertEqual(item.quantity, quantity)
|
||||
|
||||
# Grant 'change' only (no 'add')
|
||||
self.assignRole('stock.change')
|
||||
self.assertFalse(self.group.rule_sets.get(name='stock').can_add)
|
||||
|
||||
self.post(reverse('api-stock-count'), data, expected_code=201)
|
||||
item.refresh_from_db()
|
||||
self.assertEqual(item.quantity, 1)
|
||||
@@ -568,6 +568,7 @@ export default function BuildOutputTable({
|
||||
icon={<InvenTreeIcon icon='cancel' />}
|
||||
color='red'
|
||||
disabled={!table.hasSelectedRecords}
|
||||
hidden={!user.hasDeleteRole(UserRoles.build)}
|
||||
onClick={() => {
|
||||
setSelectedOutputs(table.selectedRecords);
|
||||
cancelBuildOutputsForm.open();
|
||||
@@ -666,6 +667,7 @@ export default function BuildOutputTable({
|
||||
tooltip: t`Cancel build output`,
|
||||
icon: <InvenTreeIcon icon='cancel' />,
|
||||
color: 'red',
|
||||
hidden: !user.hasDeleteRole(UserRoles.build),
|
||||
onClick: () => {
|
||||
setSelectedOutputs([record]);
|
||||
cancelBuildOutputsForm.open();
|
||||
|
||||
Reference in new issue
Block a user