In a multi-tenant SaaS I worked on, one endpoint returned every tenant’s roles to any authenticated user. A company logged into its own account could see the custom roles of every other company on the platform: the role names, the permissions assigned to each role, and the metadata around them. The fix was to filter the query by the request’s tenant even though the database already enforced row-level security, and to stop the frontend from caching role data under a key that didn’t include the organization.
Where this happened
The product is Guardix, a SaaS for security-guard companies with a Django and DRF backend, a Next.js web app and an Expo mobile app. I took the codebase over from the previous agency in early 2026, and this bug turned up while I was getting staging back into a working state.
Each customer company is a tenant, and isolation was meant to happen in Postgres. A custom database backend wraps the cursor, reads the current tenant ID from a Python ContextVar, and runs SET LOCAL rls.tenant_id before each query. Row-level security policies then hide other tenants’ rows. There are two database users: a root user for migrations, which bypasses RLS, and an app user for runtime, which is subject to it. Middleware validates the JWT, sets the RLS context and loads the user’s role and permissions.
On paper, that means a view can’t see another tenant’s rows even if it forgets to filter. The roles endpoint did anyway.
What the bug looked like
There were two parts, one on each side of the API.
On the backend, the view that lists roles returned roles from every tenant. My notes from that time don’t record why the RLS policy didn’t catch that query, so I won’t guess. The part that matters is that the view had no tenant filter of its own. Once the database layer didn’t do its job, nothing else stood in the way.
On the frontend, role data was cached with TanStack Query under a generic key, ["roles"]. A user who switched organizations could see the previous organization’s roles from cache. The queries also fired before the organization context had loaded, so the first request went out unscoped, filled the cache, and the scoped requests after it read that stale entry.
So even with a correct backend, the web app could show one tenant’s roles to a user who had moved to another.
The fix
The view now filters by tenant explicitly and returns an empty list when there is no tenant context. This is a sketch rather than the production code, but the shape is the same:
class TenantRolesView(APIView):
def get(self, request):
tenant = getattr(request, "tenant", None)
if tenant is None:
return Response([])
roles = Role.objects.filter(tenant=tenant)
return Response(RoleSerializer(roles, many=True).data)
The filter sits in the view alongside RLS as defense in depth. If one layer fails, the other still holds. The permission tree endpoint got the same treatment.
In the web app, the three components that fetched roles (the employee list, the employee profile editor and the invite dialog) now put the organization ID in the query key and wait until it exists:
useQuery({
queryKey: ["roles", organizationId],
queryFn: () => fetchRoles(organizationId),
enabled: !!organizationId,
})
A different organization now means a different cache entry, and no request goes out before the app knows which tenant it’s asking about. The shared API clients on web and mobile were tightened too, so every request carries its tenant context explicitly, and the web client now detects a stale organization.
The tenant context has to follow the work
RLS that depends on a ContextVar only protects code that runs with the context set. HTTP views get it from middleware for free. Everything else has to set it on purpose, so I wrote the rules down:
- HTTP views: automatic, through middleware.
- Celery tasks: wrap tenant work in an explicit RLS context.
- WebSocket consumers: a decorator carries the context into database calls.
- Tests: an RLS context, or a tenant fixture with RLS on.
Setting it twice caused a different bug. An explicit RLS context opened inside @transaction.atomic, in a request where the middleware had already set one, led to silent data loss: an employee role update returned 200 OK, the old role membership was deleted, and the new one was never created. It looked like extra safety and it made role changes disappear, so it went into the docs as an anti-pattern.
How to test for it in your own app
The test that catches this is boring, and you want one for every endpoint that lists tenant data:
def test_roles_are_scoped_to_tenant(api_client, tenant_a, tenant_b, user_in_a):
Role.objects.create(tenant=tenant_b, name="Other tenant role")
api_client.force_authenticate(user_in_a)
names = {r["name"] for r in api_client.get("/api/roles/").json()}
assert "Other tenant role" not in names
A few more things worth checking:
- Create two tenants in your fixtures. A suite with one tenant can’t fail on isolation.
- Run these tests as the runtime database user with RLS on, not as the migration user that bypasses it. Otherwise you’ve switched off the database layer in the one place you’re trying to test it.
- Call each endpoint with no tenant context and assert it returns nothing.
- Search the frontend for query keys that hold tenant data but don’t include the tenant or organization ID.
- Make sure tenant-scoped queries stay disabled until the organization is known.
- For background jobs and socket handlers, test that they set the tenant context themselves.
Database policies are a good last line. They shouldn’t be the only one, because a missing filter in the view gives no warning until the day the policy doesn’t apply.
More on the product and the rest of the work is on the Guardix project page.