Your DRF Permission Class Protects /projects/42, but /projects Still Lists Every Tenant
The problem A question on a public coding board this month pointed at a quiet hole in a multi-tenant API. The author had a Django REST Framework (DRF) permission class that checked obj.workspace_id == request.user.work
The problem
A question on a public coding board this month pointed at a quiet hole in a multi-tenant API. The author had a Django REST Framework (DRF) permission class that checked obj.workspace_id == request.user.workspace_id. Retrieve, update and delete all call get_object(), so those routes were protected. The list route does not call get_object(). If get_queryset still returned Project.objects.all(), the list handed back every workspace's rows.
The same gap shows up on a custom @action(detail=False), or on a get_object you write yourself and forget to hook up. Filtering in get_queryset closes the hole, but then the rule lives in two places, and a new viewset can ship without the filter. The post asked how people keep that from happening.
This is not a rumor. The official DRF permissions page says it straight. We rebuilt the leak, then a fix, on Linux with Python 3.13, Django 6.1.3 and DRF 3.18.3.
Root cause
DRF's docs, in the section "Object level permissions," say that object permissions "are run by REST framework's generic views when .get_object() is called." The next section, "Limitations of object level permissions," is the part people miss:
For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.
The page then tells you to filter the queryset, so users only see rows they are allowed to see. That is the whole bug: has_object_permission never runs on a list, by design. A permission class that looks complete can still leave the list wide open.
The docs also note that get_object() is not called when you create an object, so has_object_permission does not run then either. And if you override get_object, you must call check_object_permissions yourself. We focused on the list leak, which is the one the forum post ran into.
The leak, reproduced
A permission class that looks finished:
from rest_framework.permissions import BasePermission
class SameWorkspace(BasePermission):
"""Looks safe: it checks the object's workspace. It only runs when get_object() is called."""
def has_permission(self, request, view):
user = request.user
return user is not None and getattr(user, "is_authenticated", False)
def has_object_permission(self, request, view, obj):
return obj.workspace_id == request.user.workspace_id
And a viewset that trusts it:
class LeakyProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
permission_classes = [SameWorkspace]
We created two workspaces, each with one project (alpha in A, beta in B), and called the API as a user from workspace A. Retrieve of B's project returned 403. The list returned 200 and both titles, including beta. That is the leak.
The fix: scope the queryset, and make that the default
Put the rule on the model, then make every viewset use it unless someone overrides it on purpose:
class Project(models.Model):
workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE)
title = models.CharField(max_length=80)
@classmethod
def for_user(cls, user):
return cls.objects.filter(workspace_id=user.workspace_id)
class TenantViewSet(viewsets.ModelViewSet):
"""Fail-safe base: every subclass is scoped unless it overrides get_queryset on purpose."""
serializer_class = ProjectSerializer
permission_classes = [SameWorkspace]
queryset = Project.objects.all()
def get_queryset(self):
return self.queryset.model.for_user(self.request.user)
class SafeProjectViewSet(TenantViewSet):
pass
In our run, the safe list returned only ["alpha"]. Retrieve of B's project now returned 404, because the object is no longer in the queryset at all. That is a behavior change, and it is one of the trade-offs below.
A custom list-style action can still leak if it queries the model itself. This one did, even on the safe base class: Project.objects.values_list(...) returned beta. The safe version calls self.get_queryset() instead, and returned only ["alpha"].
@action(detail=False)
def titles(self, request):
titles = list(Project.objects.values_list("title", flat=True)) # leaks
return Response(titles)
@action(detail=False)
def titles_safe(self, request):
titles = list(self.get_queryset().values_list("title", flat=True))
return Response(titles)
Trade-offs
- 404 versus 403. A scoped queryset hides other tenants' rows, so a retrieve returns 404. The permission class alone returned 403, which tells a caller that the id exists. For a multi-tenant API, 404 is usually the better signal. Keep both layers if you want the queryset as the fence and the permission class as a second check on retrieve, update and delete.
-
The rule in one place. A base viewset is fail-safe for new list routes. It is not fail-safe for an action that talks to
Model.objectsdirectly. The test below is what catches that. -
Database-level rules. One reply suggested Postgres row-level security. That is a strong extra fence, and we did not test it here (our tests used SQLite). If you add it, still keep the queryset filter, so a missed
FOR_USERdoes not depend on the database alone. - Checking every row in Python. DRF skips object permissions on lists for a reason: it would be one check per row. Filtering in SQL is the cheaper, and complete, fix.
-
Packages such as django-guardian. The original post asked about
get_objects_for_useron large tables. We did not benchmark that, so we make no speed claim.
Checking that the leak is gone
A single successful request is not enough proof. Create rows in two workspaces and call every list route as the "wrong" user. We registered both viewsets on a DRF router and walked router.registry:
def _list_titles(self, viewset, user):
view = viewset.as_view({"get": "list"})
request = self.factory.get("/api/x/")
force_authenticate(request, user=user)
resp = view(request)
self.assertEqual(resp.status_code, 200)
return [row["title"] for row in resp.data]
def test_every_list_route_as_the_wrong_user(self):
router = DefaultRouter()
router.register("leaky", LeakyProjectViewSet, basename="leaky")
router.register("safe", SafeProjectViewSet, basename="safe")
leaks = [prefix for prefix, viewset, _ in router.registry
if "beta" in self._list_titles(viewset, self.user_a)]
self.assertEqual(leaks, ["leaky"])
Seven tests passed:
- Retrieve of the other workspace's row is 403 on the leaky viewset.
- The leaky list returns both titles.
- The safe list returns only the caller's title.
- Safe retrieve of the other row is 404.
- A custom
detail=Falseaction that queries the model still includes the other title. - The same action, written against
get_queryset(), does not. - Walking the router flags only the leaky list route.
The snippets above are the ones we ran, inside a small Django project with an in-memory SQLite database. In our tests, force_authenticate is what sets request.user. Assigning request.user by hand was not enough, and the list came back 403 before we switched.
Official sources
- Django REST framework, Permissions, "Object level permissions" and "Limitations of object level permissions": https://www.django-rest-framework.org/api-guide/permissions/#object-level-permissions
- Django REST framework, Permissions (filter the queryset;
check_object_permissionswhen you overrideget_object): https://www.django-rest-framework.org/api-guide/permissions/
Written by the team at ByteBridge Talent LLC, an IT staffing company. Learn more at bytebridgetalent.com. Questions: [email protected].
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.