DEV Community

Anas El_Faleh
Anas El_Faleh

Posted on AI-assisted

Multi-tenancy in NestJS + Prisma 7 with Postgres Row Level Security, done right

Most multi-tenant SaaS backends isolate customers like this:

this.prisma.project.findMany({ where: { tenantId } });
Enter fullscreen mode Exit fullscreen mode

It works until the day someone forgets the where. A new endpoint, a raw query for a report, a background job, a
tired developer, an AI assistant that "simplified" the query. One missing filter and customer A sees customer B's
data. Code review won't catch every one, and tests usually check the happy path.

PostgreSQL has a better place for this rule: Row Level Security (RLS). The database itself filters every row, for
every query, including the ones you forgot about.

But RLS has sharp edges. Done half-way, it gives you a false sense of safety. This post walks through the four things
you need to get right, with NestJS and Prisma 7, and the tests that prove it.

1. The policy: USING and WITH CHECK

ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON projects
  USING      (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
  WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
Enter fullscreen mode Exit fullscreen mode
  • USING decides which rows you can see, update and delete.
  • WITH CHECK decides which rows you can write (INSERT, and the new version of an UPDATEd row). It stops tenant A from inserting a row with tenant B's id, or moving one of its rows to tenant B.
  • To be precise: if you leave WITH CHECK out of a policy like this one, Postgres reuses the USING expression for writes. I still write it out, so the intent is explicit and a test can assert that every tenant table has both. What matters is that writes are checked; the test that inserts a row with another tenant's id is what proves it.
  • current_setting('app.tenant_id', true) returns an empty string or NULL when nothing is set, and NULLIF turns both into NULL. tenant_id = NULL is never true, so a forgotten tenant gives zero rows, never all rows. Fail closed.

2. FORCE, and a role that can't cheat

Here is the trap many tutorials skip: RLS does not apply to the table owner or to superusers. And in many projects,
the app connects with the same user that ran the migrations, which is the owner.

So the policy exists, the tests pass on your machine, and it filters nothing.

Two fixes, and you want both:

ALTER TABLE projects FORCE ROW LEVEL SECURITY;   -- applies to the owner too
Enter fullscreen mode Exit fullscreen mode

and a separate runtime role:

CREATE ROLE app_user LOGIN PASSWORD '...' NOSUPERUSER NOBYPASSRLS;
GRANT SELECT, INSERT, UPDATE, DELETE ON projects TO app_user;
Enter fullscreen mode Exit fullscreen mode

The app uses APP_DATABASE_URL (as app_user). Migrations use DATABASE_URL (the owner). And the app checks this at
boot, so a wrong env var fails loudly instead of silently turning isolation off:

const [row] = await this.$queryRaw<{ is_super: boolean; bypass_rls: boolean; owned_tables: number }[]>`
  SELECT r.rolsuper AS is_super, r.rolbypassrls AS bypass_rls,
         (SELECT count(*)::int FROM pg_tables
           WHERE schemaname = 'public' AND tableowner = current_user) AS owned_tables
  FROM pg_roles r WHERE r.rolname = current_user`;
if (!row || row.is_super || row.bypass_rls || row.owned_tables > 0) {
  throw new Error('Unsafe DB role for the app');
}
Enter fullscreen mode Exit fullscreen mode

3. Set the tenant per transaction, not per connection

You tell Postgres the current tenant with set_config. The third argument matters a lot:

async withTenant<T>(tenantId: string, fn: (tx: Prisma.TransactionClient) => Promise<T>) {
  return this.$transaction(async (tx) => {
    await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
    return fn(tx);
  });
}
Enter fullscreen mode Exit fullscreen mode

true = local to the transaction. At COMMIT or ROLLBACK the setting is gone. With false (session level), the
setting stays on the pooled connection, and the next request that gets that connection runs as the previous tenant.
That is a data leak that only shows up under load.

Now service code has no tenant filter at all:

list() {
  return this.prisma.withCurrentTenant((tx) => tx.project.findMany());
}
Enter fullscreen mode Exit fullscreen mode

withCurrentTenant reads the tenant from an AsyncLocalStorage set once per request, so it survives every await
and concurrent requests never mix. Outside a tenant context it throws, instead of quietly returning nothing.

4. Finding the tenant without breaking the rules

There is a chicken-and-egg problem. To authenticate an API key you must read api_keys. But api_keys is under RLS,
and you don't know the tenant yet, so you see no keys.

The two common "fixes" are both bad: query with the owner connection (now your app holds an RLS-bypassing
connection), or trust an X-Tenant-Id header (now the client picks its tenant).

The clean answer is a narrow SECURITY DEFINER function, owned by a role nobody can log in as:

CREATE ROLE tenant_resolver NOLOGIN;
GRANT SELECT (tenant_id, key_hash, revoked_at) ON api_keys TO tenant_resolver;  -- 3 columns, nothing else
CREATE POLICY api_keys_tenant_resolver_select ON api_keys FOR SELECT TO tenant_resolver USING (true);

CREATE FUNCTION resolve_api_key(p_key_hash bytea) RETURNS uuid
LANGUAGE sql STABLE SECURITY DEFINER
SET search_path = pg_catalog, pg_temp          -- no search_path hijacking
AS $$
  SELECT k.tenant_id FROM public.api_keys k
  JOIN public.tenants t ON t.id = k.tenant_id
  WHERE k.key_hash = p_key_hash AND k.revoked_at IS NULL AND t.status = 'ACTIVE'
  LIMIT 1
$$;
ALTER FUNCTION resolve_api_key(bytea) OWNER TO tenant_resolver;
REVOKE ALL ON FUNCTION resolve_api_key(bytea) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION resolve_api_key(bytea) TO app_user;
Enter fullscreen mode Exit fullscreen mode

The app can call one function that takes a hash and returns one tenant id. It cannot read any key. A global NestJS
guard calls it, sets req.tenantId, and an interceptor runs the handler inside that tenant's context.

(Gotcha on managed Postgres like Neon or Supabase, where you are not a superuser: ALTER FUNCTION ... OWNER TO needs
the new owner to have CREATE on the schema. Grant it just for that statement and revoke it right after.)

Prove it: tests that fail when isolation breaks

RLS you don't test is RLS you don't have. For every tenant-owned table, through the app's real connection:

it('A cannot read B', async () => {
  const rows = await app.withTenant(a, (tx) => tx.project.findMany());
  expect(rows.map((r) => r.id)).toEqual([projectOfA]);
});

it('A cannot insert a row for B', async () => {
  await expect(
    app.withTenant(a, (tx) => tx.project.create({ data: { tenantId: b, name: 'evil' } })),
  ).rejects.toThrow(/row-level security/i);
});

it('the tenant does not leak to the next query on the pool', async () => {
  await app.withTenant(a, (tx) => tx.project.findMany());
  expect(await app.project.findMany()).toEqual([]);
});
Enter fullscreen mode Exit fullscreen mode

Plus update, delete, moving a row to another tenant, raw SQL, and 20 concurrent transactions of two tenants.

And one more test that I think every RLS project needs: a privilege audit. It lists every table in the schema
with the exact grants the runtime role should have, and checks that every table with a tenant_id column has
ENABLE + FORCE + a policy with both USING and WITH CHECK. If someone adds a table and forgets RLS, CI goes red.

To check the tests themselves, I turned RLS off on one table: 15 tests failed. That is the point.

Summary

Mistake Fix
Implicit or missing write checks Write both USING and WITH CHECK, and test inserts with another tenant's id
App connects as owner/superuser FORCE RLS + a separate NOBYPASSRLS role, checked at boot
set_config(..., false) Transaction-local true, one transaction per unit of work
Tenant from a header Server-side resolution via a narrow SECURITY DEFINER function
"We tested the happy path" Cross-tenant tests + a privilege audit in CI

I packaged all of this into a free, MIT-licensed NestJS starter: Prisma 7, API-key auth, a CRUD example, a tenant CLI,
Docker, CI, and the full test suite: https://github.com/anasFaleh/nestjs-rls-saas-starter

If you run multi-tenant Postgres in production, I'd like to hear how you handle it, especially background jobs and
reporting queries.

Top comments (0)