The multi-tenant read that returns nothing, silently
A multi-tenant bug under Postgres row-level security is invisible rather than loud, because the policy enforces writes with an error and reads with a filter. A write that lands outside the current tenant raises SQLSTATE 42501 and stops. A read that lands outside the current tenant is not an error at all: the policy is folded into the query as an extra condition, the condition matches nothing, and the statement succeeds with zero rows. So a query that escaped its tenant scope does not crash. It returns HTTP 200, renders a page indistinguishable from a customer who has no data, and appears in no error monitor.
Postgres row-level security attaches a policy to a table, and the policy has two halves that behave differently. USING is evaluated against rows a statement reads. WITH CHECK is evaluated against rows a statement writes. A row failing WITH CHECK raises an error, because there is no other way to report a write that cannot happen. A row failing USING produces nothing, because removing rows is what a read is for. An empty result set is a successful result set.
That asymmetry is the entire hazard. Kaso's web application connects to Postgres as a role with no BYPASSRLS. When a query escapes its tenant scope, the write path fails loudly and the read path fails silently, and the read path is the one that ships. The bug does not arrive as an exception with a stack trace. It arrives as a page that renders correctly, quickly, and empty.
The mechanism, in four statementsPermalink to this section
Every tenant-scoped policy in this codebase has one shape: using (workspace_id = app_current_workspace()), where app_current_workspace() reads a Postgres session variable. Exactly one module sets that variable, transaction-locally, at the start of every scoped transaction. Set it and the connection sees one tenant; leave it unset and it sees none. Below is both halves of the asymmetry against a live database, on the connection a web request uses.
APP_DSN=$(grep -m1 -o 'postgresql://[a-z]*_app:[^"]*@localhost[^"]*' .env.local)
psql "$APP_DSN" <<'SQL'
\set VERBOSITY verbose
select count(*) as unscoped_accounts from accounts;
begin;
select left(set_config('app.workspace_id', (select id::text from public.workspaces order by created_at limit 1), true), 8) || '...' as scoped_to;
select count(*) as scoped_accounts from accounts;
insert into accounts (workspace_id, name) values ((select id from public.workspaces order by created_at offset 1 limit 1), 'rls probe');
rollback;
SQL
unscoped_accounts
-------------------
0
(1 row)
BEGIN
scoped_to
-------------
124b86c4...
(1 row)
scoped_accounts
-----------------
54
(1 row)
ERROR: 42501: new row violates row-level security policy for table "accounts"
LOCATION: ExecWithCheckOptions, execMain.c:2234
ROLLBACKThe first line lifts the local development connection string a web request uses out of the repository's own .env.local, so the transcript carries no hostname or credential and the command still runs as written from the repository root. The workspace id is truncated by the query itself, not edited afterwards. The insert targets a second workspace, so it is a genuine cross-tenant write rather than a malformed one.
Read the first result again. Zero accounts, no error, no warning. The 54 rows were there the whole time, which the third statement proves on the same connection two lines later, and the fourth proves that connection still cannot write across the tenant boundary. One silent failure and one loud one, seconds apart.
Why the asymmetry exists at allPermalink to this section
The asymmetry is not a Postgres design flaw. It falls out of what the two operations mean. A SELECT asks which rows match a condition; a policy adds another condition; the answer is a smaller set. There is nowhere in a result set to put the row you were not allowed to see. Raising an error instead would be worse than useless: it would distinguish no rows matched your filter from rows matched and the policy removed them, which leaks the existence of exactly the rows the policy hides. Returning nothing is the simplest behaviour and the one that tells an attacker least.
An INSERT or an UPDATE has the opposite shape. It names a specific row and requires that row to exist afterwards. Silently discarding it would be a lie about durability, so Postgres raises SQLSTATE 42501. Each behaviour is correct alone. They are dangerous together, in an application whose tests exercise the loud half and whose users meet the quiet one.
How write and read differ by database rolePermalink to this section
Whether the policy applies at all depends on the database role the connection uses, which is a connection-string decision rather than a code one. An identical function behaves differently in a web request and in a background job, with no branch to explain why.
| Postgres role | BYPASSRLS | Read with no tenant scope set | Write outside the tenant scope |
|---|---|---|---|
| Web requests | no | zero rows, no error | raises SQLSTATE 42501 |
| Job worker | yes | every tenant's rows | succeeds |
| Search indexer | yes | every tenant's rows | succeeds |
| Owner (migrations, DDL) | yes, and superuser | every tenant's rows | succeeds |
OWNER_DSN=$(grep -m1 -o 'postgresql://[a-z]*:[^@"]*@localhost[^"]*' .env.local)
psql "$OWNER_DSN" <<'SQL'
select
case
when rolsuper then 'owner (migrations, DDL)'
when rolname like '%\_app' then 'web requests'
when rolname like '%\_worker' then 'job worker'
when rolname like '%\_search' then 'search indexer'
end as role,
rolsuper as superuser,
rolbypassrls as bypasses_rls
from pg_roles
where rolsuper or oid > 16383
order by 1;
SQL
role | superuser | bypasses_rls
-------------------------+-----------+--------------
job worker | f | t
owner (migrations, DDL) | t | t
search indexer | f | t
web requests | f | f
(4 rows)The owning connection string is read out of .env.local by the first line, for the same reason as the transcript above: no credential in the article, and still runnable. The CASE turns each role's name into what it is for, so the transcript reports the shape rather than this installation's naming; oid > 16383 is Postgres's boundary between roles that ship with the server and roles somebody created. Three of the four ignore every policy. Only the one the web application uses is bound by them, which is the point, and also the reason a reproduction attempt on the wrong credential proves nothing.
This is where the phrase 'it works on my machine' stops being a figure of speech. An engineer reproducing the report with a script on the worker credential sees the customer's data and closes the ticket. The customer, whose request travels through the application role, still sees an empty page. The code is byte-identical.
Why 'the customer says their data vanished' is usually not data lossPermalink to this section
A tenancy scope bug and a genuine data-loss event produce the same user report and share almost nothing else. A scope bug leaves every row in place. It emits a 200 response, a normal latency profile, no exception, and an empty list rendered by the component that also renders an empty list for a customer who signed up ten minutes ago. Every monitor built to catch failures watches for errors, and this one produces none. The shape of the bug is the shape of the product working.
How do you tell a multi-tenant scope bug apart from actual data loss?Permalink to this section
A positive control separates a multi-tenant scope bug from real data loss, and it belongs before any restore. Take the affected tenant's id, open a transaction on the same database role the application uses, set the tenant scope by hand, and count the rows the customer says are missing. A non-zero count means nothing was lost: the application's query lost its scope and the policy filtered every row out. A zero count means the rows are genuinely gone and a restore is the right response. The check takes a minute, and it separates a code bug from a recovery incident, which are very different pages to be woken for.
The three defences, and what each one catchesPermalink to this section
Filter in the application, and let the database be the backstopPermalink to this section
Row-level security is not a replacement for a tenant predicate in the query. It is what catches the query that forgot one. Kaso writes the workspace filter at the application level anyway and treats the policy as the second line, and the ordering matters: the application filter makes a query correct, and the policy makes a mistake in that filter non-catastrophic. A team that deletes its application filters because the database now covers them has thrown away the mechanism and kept only the backstop, and the backstop is the half that fails silently.
OWNER_DSN=$(grep -m1 -o 'postgresql://[a-z]*:[^@"]*@localhost[^"]*' .env.local)
psql "$OWNER_DSN" <<'SQL'
select
(select count(*) from information_schema.tables
where table_schema = 'public' and table_type = 'BASE TABLE') as tables,
(select count(*) from pg_policies where schemaname = 'public') as policies,
(select count(*) from information_schema.columns c
join pg_class p on p.relname = c.table_name
and p.relnamespace = 'public'::regnamespace
where c.table_schema = 'public'
and c.column_name = 'workspace_id'
and not p.relrowsecurity) as tenant_tables_without_rls;
SQL
tables | policies | tenant_tables_without_rls
--------+----------+---------------------------
164 | 178 | 0
(1 row)Same owning connection string, read out of .env.local by the first line. The third column is the one worth watching: a table that grows a workspace_id column without a policy is a tenant table with no backstop, and it is a migration-time check rather than a review-time hope.
Make every bypass a named value from a closed setPermalink to this section
Some work genuinely belongs to no tenant: a worker polling its queue, a login resolving before any workspace is known, a webhook arriving before it can be attributed. In this codebase that work runs inside withoutTenant(reason, ...), where reason is a member of a closed union of eight strings. Adding a ninth kind of bypass is then an edit to a shared type declaration, visible in review rather than made quietly in one file, and every existing bypass is greppable by reason.
echo "reasons used outside tests:"
grep -r --exclude=tenant.ts --exclude-dir=editorial -o 'withoutTenant("[a-z_]*"' src | grep -v '\.test\.' | sed 's/^.*://' | sort | uniq -c | sort -rn
echo "withoutTenant, outside tests then including tests:"
grep -r --exclude=tenant.ts --exclude-dir=editorial -o 'withoutTenant("[a-z_]*"' src | grep -vc '\.test\.'
grep -r --exclude=tenant.ts --exclude-dir=editorial -o 'withoutTenant("[a-z_]*"' src | grep -c 'withoutTenant'
echo "withTenant, outside tests then including tests:"
grep -r --exclude=tenant.ts --exclude-dir=editorial -o 'withTenant(' src | grep -vc '\.test\.'
grep -r --exclude=tenant.ts --exclude-dir=editorial -o 'withTenant(' src | grep -c 'withTenant'
reasons used outside tests:
28 withoutTenant("admin_backfill"
13 withoutTenant("plan_catalogue_read"
12 withoutTenant("auth_login"
7 withoutTenant("webhook_intake"
7 withoutTenant("migration"
3 withoutTenant("job_worker_poll"
2 withoutTenant("job_terminal_write"
1 withoutTenant("job_lease_reclaim"
withoutTenant, outside tests then including tests:
73
155
withTenant, outside tests then including tests:
1065
126373 deliberate bypasses outside tests, spread across all eight declared reasons, and 155 occurrences in total including the tests that exercise them. The withTenant lines are the denominator: outside tests, 73 of 1,138 scope entries leave tenancy behind, and each of those had to name a reason to do it. Every grep here excludes src/lib/editorial, because these articles discuss withTenant and withoutTenant by name and a page that names a symbol would otherwise count itself — without the exclusion the withTenant line reads 1265 rather than 1263, and the difference is this article and its sibling.
Warn at development time, while the mistake still has an authorPermalink to this section
The third defence is a tripwire rather than a control. A helper that must be tenant-scoped calls assertTenantScope("label") on its first line, and outside a tenant scope that prints a development-only warning naming the helper. It does nothing in production, deliberately, because the policy is the control. The value is timing: a warning in a terminal while somebody writes the helper costs seconds, the same mistake found from a staging screen reading zero accounts costs an afternoon, and found from a customer email it costs a great deal more.
Reported honestly: assertTenantScope has three call sites in this repository, across two files. That is a gap, and it is the gap this defence always has. An opt-in check protects the helpers whose author was already thinking about tenant scope, which is not the population that produces the bug.
Why this rule has to be checked by a machinePermalink to this section
A code review cannot enforce tenancy, because the consequence of a statement is a property of the database rather than of the diff. Two adjacent lines in this repository's old seed script made the case. One deleted every user in the installation, because that table has no tenant column and therefore no policy. The line beside it deleted nothing at all, because that table's policy is keyed on its own id and matched no rows unscoped. Neither raised. Both read as an ordinary delete. So the check has to read the schema.
out=$(pnpm audit:scopes 2>/dev/null); code=$?
printf '%s\n' "$out" | sed -n 's/^ \[\([a-z-]*\)\].*/open violation, class: \1/p; /mutation sites/p'
echo "exit status: $code"
open violation, class: inert-unscoped-write
1783 mutation sites, 61 on the bare handle, 1 violation(s).
exit status: 1The full run is long, and it names a file and a line for every site it classifies; the sed keeps the violation class and the totals and drops the locations, because the location of an open finding is not an article's to publish. What survives is the shape: 1,783 mutation sites classified by what the policy on that table would actually do, 61 of them on the unscoped handle, one of those a rule violation. The exit status is the part a pipeline reads — the run is red on this branch.
That output is not a boast, and a passing run would have been less useful. One violation is open on this branch, in the class the scanner calls an inert unscoped write: a statement that runs on the application credential, matches no rows because the policy on that table is strict, and reports success anyway. It is this article's bug class exactly, caught by a machine rather than by a customer. The scanner names the file and the line. This article does not, because where an unfixed finding lives is a disclosure decision and not a formatting one.
The tables a policy cannot protectPermalink to this section
Row-level security filters on a column. A table with no tenant column has nothing to filter on, so there is no policy to write and no backstop to lean on. The only safe move is to enumerate those tables rather than assume the boundary covers everything. The same scan lists eight of them here, including the users table, which carries 70 write sites of which 37 are destructive. Whatever protects those rows, it is not the policy, and a security review that stops at 'row-level security is enabled' never looked at them.
Does row-level security mean an application can stop filtering by tenant?Permalink to this section
No. Row-level security should be the backstop; the application's own tenant predicate stays the mechanism. Two reasons. A policy filters silently, so once it is the only filter, a bug in scope propagation surfaces as an empty page rather than an error, and empty pages are the failure no error monitor catches. And policies are evaluated per role: any connection on a role with BYPASSRLS ignores every policy on the server, so one wrong connection string turns the only defence off with nothing raised anywhere. Keeping both means a breach needs a mistake in each layer.
Why does the same code return data in a background job and nothing in the web application?Permalink to this section
Because row-level security is enforced per database role, and background workers usually connect as a different role from web requests. A role with the BYPASSRLS attribute ignores every policy on the server, so an unscoped query on that role returns every tenant's rows and appears to work. The same query on a role without BYPASSRLS returns zero rows and no error. The application code is identical on both paths, which is why reproducing a tenancy report from a script or a worker is misleading: reproduce it on the exact role the failing request used, or it proves nothing.
What to check in your own system tonightPermalink to this section
- Find which database role your application connects as, and whether it can bypass your policies. In Postgres: select rolname, rolsuper, rolbypassrls from pg_roles where rolname = current_user. A yes in either column means your policies are decoration on that connection.
- Confirm that role differs from the one your workers and migrations use. If every process shares one credential, the strictest role in your system is also the loosest, and the tenancy boundary lives only in the code.
- Take your busiest tenant-scoped table, open a connection with no tenant scope set, and run an unfiltered count. Zero is the answer you want. Any other number is your blast radius, measured.
- Enumerate the tables with no tenant column at all. No policy can protect those, and they are usually the interesting ones: users, sessions, API keys, billing. Write the list down rather than recalling it.
- Ask what alert fires when a screen renders zero rows for an account that had rows yesterday. In most systems the honest answer is none, and that is the finding.
None of this is specific to Postgres, to row-level security, or to any ORM. Every multi-tenant mechanism has a silent direction. A database policy with no bypass fails closed: the reader sees too little, and the complaint arrives as missing data. An application-side default scope, whether an ORM base query, a middleware injecting a tenant id, or a filter added by a repository class, fails open: the reader sees too much, and the complaint arrives from somebody else's customer or from a regulator. Neither raises. Knowing which direction your system fails tells you which of your monitors could ever have caught it.
An empty page is the most expensive output a multi-tenant system can produce, because it is the one failure that looks like success to every layer above it: to the HTTP status, the error tracker, the uptime check, and the engineer reproducing it on the wrong credential. The defence is not a cleverer policy. It is arranging for the boundary to be crossed only by code that had to name itself, and for a machine rather than a reviewer to decide what each statement really does.