Make your tenant filter refuse when the tenant is missing
Most multi-tenant apps I have built share one quiet design choice: the data layer adds the tenant filter for you. A request comes in, the auth code figures out which organization the user belongs to, it stashes that id somewhere request scoped, and every query after that gets WHERE org_id = ? added automatically. Route code never has to remember it, so route code can’t forget it.
That is a good pattern. It also has a trap built into it, and I found it in one of my own side projects while reading the wrapper with fresh eyes.
The trap: no tenant meant no filter
The wrapper had to support code that legitimately runs without a tenant. Login looks up a user by email before it knows their organization. Webhooks arrive from outside with no session. Scheduled jobs loop over every organization. So the rule was simple: if there is a tenant in context, filter by it. If there isn’t, pass the query through unscoped.
Read that second sentence again from the point of view of a signed-in user whose account has no organization. Maybe the field is empty because of an old import. Maybe it points at an organization that was deleted. The auth code loads the user, sets the tenant to that empty value, and the wrapper sees “no tenant.” It does exactly what it was told: it runs every query with no filter at all.
So the one user who should see nothing was the one user who could see everything. Nobody had hit it, and a read-only count in production showed every account had a valid organization. But “the data happens to be clean today” is not a security property. One bad import or one deleted organization would have turned it on.
Separate “not known yet” from “required but missing”
The fix is to stop treating “no tenant” as one state. There are really two:
- Not known yet. Login, token lookups, webhooks, cron. Unscoped access is expected, and the code that runs here is small and written with that in mind.
- Required but missing. Any authenticated staff request. A tenant must exist. If it doesn’t, the right answer is to refuse, not to guess and not to widen.
I added a second request-scoped flag next to the tenant id. Once a request is authenticated, the flag says a tenant is required. The wrapper checks it before every operation:
from contextvars import ContextVar
current_tenant: ContextVar[str | None] = ContextVar("current_tenant", default=None)
tenant_required: ContextVar[bool] = ContextVar("tenant_required", default=False)
GLOBAL_COLLECTIONS = {"tenants", "login_attempts", "job_runs"}
class TenantRefused(Exception):
pass
class ScopedCollection:
def __init__(self, coll, name):
self._c, self._name = coll, name
def _tenant(self):
if self._name in GLOBAL_COLLECTIONS:
return None
tid = current_tenant.get()
if tenant_required.get() and tid is None:
raise TenantRefused("This account is not linked to an organization.")
return tid
def find(self, flt=None, *a, **kw):
tid = self._tenant()
flt = dict(flt or {})
if tid is not None:
flt["org_id"] = tid
return self._c.find(flt, *a, **kw)
def __getattr__(self, item):
self._tenant() # index helpers, drops, anything not wrapped
return getattr(self._c, item)
Two details matter more than they look.
First, the check runs on every path, including the ones that don’t take a filter. Bulk inserts and the catch-all attribute passthrough used to skip the tenant lookup entirely because they didn’t need it. Now they call it anyway, purely so the guard fires.
Second, clearing the tenant does not clear the requirement. If some code path calls “set tenant to none” halfway through a request, the flag is still on and the next query is refused. Only the request boundary resets both values, in middleware, so nothing leaks from one request into the next.
Refuse at the front door too
The wrapper is the backstop. The front door is the auth code. When it loads the user, it now checks that the organization id is present and that the organization still exists, and it refuses with a 403 if not. I put the same check on login and on token refresh, so a broken account can’t get a fresh session in the first place.
That gives a clear message to the person instead of a confusing empty screen, and it means the wrapper’s refusal is something you only see if the front door missed a case.
Look for the side doors
The first sweep of the code turned up two places that did their own authentication instead of calling the shared function.
One was a CSV export that accepted a token in the query string, because a plain download link can’t always send cookies. It decoded the token and loaded the user by hand. It never checked the token type, never checked whether the user was disabled, and never set the tenant requirement. For an account with no organization, that export would have returned every organization’s records. The fix was to delete the hand-rolled version and pass the query token into the same function the cookie path uses, so a link token gets exactly the same checks.
The other was a download route that caught any auth error and fell back to a private link flow. That fallback is useful for expired sessions. It is wrong for “this account has no tenant,” so that one specific refusal now propagates instead of being swallowed.
The general lesson: if you have one function that decides who the user is, every route should call it. Any route that decodes a token itself is a second security policy that nobody is maintaining.
Test the whole surface, not a sample
A handful of tests for a handful of routes would have passed before the fix and after it, and told me nothing about the export link. So the test enumerates every route the app registers, finds the ones that reach the user lookup, and calls each one as a user with no organization and as a user whose organization was deleted, once with a cookie, once with a bearer header, and once with a link token.
Every one of those calls must be refused, and the test also records every query issued after the user lookup and asserts none of them ran unscoped against tenant data. Then the normal cases: regular users stay scoped to their own organization, the cross-organization admin console still works through its explicit global access, and two requests in a row don’t share tenant state.
Because the test walks the route table, a route I add next month is covered without anyone remembering to add it.
Tradeoffs
Failing closed has a real cost: if your data is not as clean as you think, people get locked out. That is why I checked production first, read only and counts only, before shipping. If some accounts had been broken, I would have fixed those records first, then shipped the guard.
It also makes admin tooling slightly more explicit. Code that truly needs to read across tenants has to say so by using the global collections or a raw handle on purpose. I consider that a feature. Cross-tenant access should look different in the code from normal access.
The short version
If your data layer adds the tenant filter automatically, ask what it does when the tenant is missing. “Run unscoped” is the right answer for login and background jobs and the wrong answer for everyone who is already signed in. Make the requirement its own flag, check it on every operation, reset it only at the request boundary, route every token through one auth function, and test every route rather than a few.