Postgres row level security multi-tenant thumbnail: a correct policy with seven isolation gaps around it

Multi-Tenant Postgres Row Level Security: 7 Ways Around It

We wrote one Postgres row level security policy, checked it was right, and never touched it again. Then we let a normal logged-in user from tenant B try to read tenant A’s data. He got it seven different ways. None of them involved breaking the policy.

If you use Postgres row level security for multi-tenant isolation, this is where we’d look first. It’s a lab we built on purpose to fail, so these are mechanisms, not a count of how often each mistake happens in the wild. Below are the raw requests, the one-line fixes, and a catalog query that flagged five of the seven.

Key takeaways

  • The policy held every time. Isolation failed around it: the role the app connects as, how tenant context reaches a pooled connection, views and SECURITY DEFINER functions, a table with no RLS, and a unique constraint.
  • The worst one was a pool leak. In three bursts of 200 concurrent requests, 33, 95 and 103 responses carried the other tenant’s rows. After the fix it was 0 in all three.
  • Each route closed with a one-line fix. A read-only audit query caught five of the seven from catalog data alone. The other two need a code review and a two-tenant test.

The lab: one app, two tenants, one policy we never changed

The app is a small notes API: Express 5.3.0, node-postgres 8.23.1 and PostgreSQL 18.6, all on 127.0.0.1. Two tenants. Acme has alice, 3 notes and 2 attachments. Globex has bob, 2 notes and 1 attachment. Bob is the attacker in every test: a normal authenticated Globex user with his own valid API key.

The policy on notes is the textbook one, and we never edited it:

CREATE POLICY tenant_isolation ON notes
  USING      (tenant_id = current_setting('app.tenant_id', true)::int)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::int);

Two roles matter. app_owner runs migrations and owns every object. app_user has DML grants only. Both are NOSUPERUSER and NOBYPASSRLS. Every test started from a fresh database. As a baseline, count(*) on notes as app_user with no tenant set is 0. As app_owner it’s 5. Hold onto that second number.

ID Mistake around the policy What bob got Fix After
L0 attachments table added later, RLS never enabled 3 attachments incl. acme-cap-table.xlsx enable RLS + policy 1 (his own)
L1 App connects as the table owner, RLS not forced 5 notes (3 Acme) FORCE ROW LEVEL SECURITY 2 (his own)
L2 App connects as a superuser 5 notes, even with FORCE on connect as app_user 2
L3 Tenant set at session level on a connection pool 33, 95, 103 of 200 responses held the other tenant’s rows transaction-local setting 0, 0, 0 of 200
L4 Reporting view owned by the table owner Acme’s row: 3 notes, latest title “Acme Q4 board deck” security_invoker = true Globex row only
L5 SECURITY DEFINER search function all 3 Acme titles for ?q=acme SECURITY INVOKER []
L6 Globally unique slug 409 for an Acme slug, 201 for a made-up one UNIQUE (tenant_id, slug) 201 for both

Seven routes tried, seven reproduced, seven closed by the listed fix with a positive control still working. Bob still saw his own rows every time.

L1 and L2: the role you connect as decides whether RLS exists

According to the PostgreSQL docs, superusers and roles with BYPASSRLS always skip row security. Table owners skip it too, unless the table has FORCE ROW LEVEL SECURITY.

In L1 the app connected as app_owner, the migration role. This is the usual way in: one DATABASE_URL for migrations and for the app. The catalog showed the table was set up exactly as most tutorials say:

relname | relrowsecurity | relforcerowsecurity | owner
notes   | true           | false               | app_owner

Bob listed his notes and got all five, three of them Acme’s:

$ curl -s http://127.0.0.1:5301/api/notes -H "Authorization: Bearer $BOB_KEY"
HTTP 200
{"you": "bo*@****ex.test (tenant 2)",
 "notes": [{"id":1,"tenant_id":1,"title":"Acme Q4 board deck"},
           {"id":2,"tenant_id":1,"title":"Acme layoff plan"},
           {"id":3,"tenant_id":1,"title":"Acme pentest findings"},
           {"id":4,"tenant_id":2,"title":"Globex roadmap"},
           {"id":5,"tenant_id":2,"title":"Globex pricing draft"}]}

Same role, one statement later:

ALTER TABLE notes FORCE ROW LEVEL SECURITY;

Bob got his two notes. But FORCE doesn’t bind everyone. In L2 we left FORCE on and connected the app as postgres, where rolsuper and rolbypassrls are both true. Bob got all five again. The fix was the connection string: app_user. The OWASP Multi-Tenant Application Security Cheat Sheet says the same thing: FORCE doesn’t constrain a superuser or BYPASSRLS role, so don’t serve tenant-scoped requests through a privileged connection.

A related note on Supabase. Its docs say the secret key acts through the service_role role, which has bypassrls, and skips RLS when the request carries no user token. We didn’t test any Supabase project. We’d just keep that key off any path that serves end users.

L3: the pooled connection that remembered the last tenant

This is the one we’d fix first. Here’s the bug, from the lab’s app.js:

await pool.query("SELECT set_config('app.tenant_id', $1, false)", [String(tenantId)]);
return pool.query(text, params);

It looks fine. It isn’t, for two reasons. The false means the setting lasts for the rest of the session, according to the Postgres docs. And two separate pool.query calls can land on different pooled connections. The node-postgres docs say to use one client for every statement in a transaction, and not to use transactions with pool.query.

So a connection that last served Acme can serve the next request, from Globex, with Acme’s tenant still set. We fired 200 concurrent GET /api/notes requests, 100 from alice and 100 from bob, interleaved, and counted responses holding the other tenant’s rows. We did it three times:

burst 1: 200 requests, 167 correct, other_tenant_rows: 33
burst 2: 200 requests, 105 correct, other_tenant_rows: 95
burst 3: 200 requests,  97 correct, other_tenant_rows: 103

One of bob’s leaked responses:

HTTP 200
{"you": "bo*@****ex.test (tenant 2)",
 "notes": [{"id":1,"tenant_id":1,"title":"Acme Q4 board deck"},
           {"id":2,"tenant_id":1,"title":"Acme layoff plan"},
           {"id":3,"tenant_id":1,"title":"Acme pentest findings"}]}

HTTP 200, no error. The number moves from run to run (33 to 103 across three bursts), so don’t read it as a rate you’d see in production. Any non-zero count is the finding.

The variant is odder. After one alice request, an unauthenticated GET /api/status reported "visible_notes": 3. The developer expected 0. A request with no identity at all inherited Acme’s context.

The fix is boring. One client, one transaction, and a setting that dies with it:

async function asTenant(tenantId, sql, params = []) {
  const client = await pool.connect();          // one connection for the whole unit of work
  try {
    await client.query('BEGIN');
    await client.query("SELECT set_config('app.tenant_id', $1, true)", [String(tenantId)]); // true = this transaction only
    const result = await client.query(sql, params);
    await client.query('COMMIT');
    return result;
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

Same three bursts after the fix: 0, 0 and 0 of 200. The OWASP cheat sheet recommends exactly this: scope tenant context to the transaction and never assume a borrowed connection has the right setting. PgBouncer’s feature table lists SET and RESET as unsupported in transaction pooling mode, so the same reasoning applies there. We didn’t test PgBouncer.

The 500 the fix introduced

After the fix, the same unauthenticated /api/status call returned this:

HTTP 500
{"error": "invalid input syntax for type integer: \"\""}

A custom setting that was never set reads as NULL. After a transaction-local set_config has run on a connection, it reads as an empty string, not NULL. ''::int throws. That fails closed, which is good, but it echoes a database error to the client. Wrapping the value in nullif makes the policy return zero rows instead:

ALTER POLICY tenant_isolation ON notes
  USING      (tenant_id = nullif(current_setting('app.tenant_id', true), '')::int)
  WITH CHECK (tenant_id = nullif(current_setting('app.tenant_id', true), '')::int);

L4 and L5: views and SECURITY DEFINER functions run as their owner

By default, a view reads its base tables with the view owner’s permissions, and if RLS is on, the owner’s policies apply. That’s from the CREATE VIEW docs. Setting security_invoker = true switches to the caller, and it arrived in PostgreSQL 15.

Our migration role created a reporting view, notes_summary. Bob called the endpoint that reads it:

GET /api/notes/summary
{"summary": [{"tenant_id":1,"notes":"3","latest_title":"Acme Q4 board deck"},
             {"tenant_id":2,"notes":"2","latest_title":"Globex roadmap"}]}

One statement fixed it:

ALTER VIEW notes_summary SET (security_invoker = true);

After that, bob saw only the Globex row.

L5 is the same idea in a function. We wrote a search helper “so it can read the index”, declared SECURITY DEFINER, owned by app_owner:

CREATE FUNCTION search_notes(q text) RETURNS TABLE (id int, tenant_id int, title text)
  LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public AS
  $$ SELECT id, tenant_id, title FROM notes WHERE title ILIKE '%' || q || '%' $$;

Bob searched for acme and got all three Acme titles back. Note the SET search_path = public. We pinned it, as the CREATE FUNCTION docs advise for SECURITY DEFINER, and it still leaked. A pinned search_path protects against hijacking. It does nothing about a function that reads every tenant.

ALTER FUNCTION search_notes(text) SECURITY INVOKER;

After that, ?q=acme returned [] and ?q=globex still returned his two notes. If a function really must be DEFINER, filter by tenant inside it, explicitly. The Supabase docs flag both patterns: views bypass RLS by default because they’re usually created by postgres, and DEFINER functions in an exposed schema can be called through the Data API with the creator’s privileges.

Views and DEFINER functions aren’t insecure. They run as their owner by design. The mistake is using them on tenant data without a tenant filter.

L0 and L6: the table nobody enabled RLS on, and the 409 that answers a question

L0 is the dull one. attachments arrived in a later migration. Someone wrote the table and the grants and forgot ENABLE ROW LEVEL SECURITY. Bob listed three attachments, including acme-cap-table.xlsx and acme-soc2-bridge-letter.pdf. Enable RLS, add the policy, and he saw one file, his own.

L6 doesn’t read a row at all. The Postgres docs say unique, primary key and foreign key checks always bypass row security, and warn about covert channels. Our slug column was globally UNIQUE. Bob posted a note with a slug that exists in Acme:

$ curl -s -X POST http://127.0.0.1:5301/api/notes -H "Authorization: Bearer $BOB_KEY" \
    -H 'Content-Type: application/json' -d '{"slug":"acme-layoff-plan","title":"x","body":"x"}'
HTTP 409
{"error": "duplicate key value violates unique constraint \"notes_slug_key\""}

Then one that doesn’t exist:

-d '{"slug":"acme-ipo-plan","title":"x","body":"x"}'
HTTP 201
{"id": 7, "slug": "acme-ipo-plan"}

409 versus 201 answers “does Acme have a layoff plan note?” without returning a single row. To be precise, Postgres didn’t hand the key value back to app_user here. It returned the constraint name only. The status code was enough. Also note probe 2 created a real row in bob’s tenant, so an oracle like this writes data as it asks.

A generic error message won’t fix this, because the signal is the 409 itself. The fix is a per-tenant constraint:

ALTER TABLE notes DROP CONSTRAINT notes_slug_key;
ALTER TABLE notes ADD CONSTRAINT notes_tenant_slug_key UNIQUE (tenant_id, slug);

The same slug request then returned 201. If you need global uniqueness for something like public URLs, add a random suffix instead.

Check your own database in one query

Five of the seven show up in catalog data. This query is read-only. Replace app_user with the role your app connects as:

SELECT 'table without RLS' AS finding, n.nspname || '.' || c.relname AS object
  FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
 WHERE c.relkind IN ('r','p') AND n.nspname NOT IN ('pg_catalog','information_schema') AND NOT c.relrowsecurity
UNION ALL
SELECT 'RLS on but not FORCEd (owner bypasses)', n.nspname || '.' || c.relname || ' owner=' || pg_get_userbyid(c.relowner)
  FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
 WHERE c.relrowsecurity AND NOT c.relforcerowsecurity
UNION ALL
SELECT 'role bypasses RLS', rolname || CASE WHEN rolsuper THEN ' (superuser)' ELSE ' (BYPASSRLS)' END
  FROM pg_roles WHERE (rolsuper OR rolbypassrls) AND rolcanlogin
UNION ALL
SELECT 'view runs as owner (no security_invoker)', n.nspname || '.' || c.relname || ' owner=' || pg_get_userbyid(c.relowner)
  FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
 WHERE c.relkind = 'v' AND n.nspname NOT IN ('pg_catalog','information_schema')
   AND NOT coalesce(c.reloptions @> ARRAY['security_invoker=true'] OR c.reloptions @> ARRAY['security_invoker=on'], false)
UNION ALL
SELECT 'SECURITY DEFINER function', p.oid::regprocedure::text || ' owner=' || pg_get_userbyid(p.proowner)
  FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
 WHERE p.prosecdef AND n.nspname NOT IN ('pg_catalog','information_schema')
UNION ALL
SELECT 'app role owns an RLS table', c.relname
  FROM pg_class c WHERE c.relrowsecurity AND pg_get_userbyid(c.relowner) = 'app_user'
ORDER BY 1, 2;

On the lab before any fixes it returned seven rows: notes not forced, the postgres superuser, search_notes(text), attachments, notes_summary, and two lookup tables (tenants, auth.api_keys) that have no RLS on purpose. After the fixes only the superuser and those two lookup tables were left.

The query lists expected objects too, so a human has to read it. It can’t see L3, because that bug lives in application code. It can’t see L6, because a unique constraint being global is a schema decision, not a catalog flag. Those two need a code review and a test.

Patch level matters too

One short note. PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 shipped on 12 November 2026. Per the Postgres security pages, they fix CVE-2026-120154 (INSERT ... ON CONFLICT can read every row despite RLS for a user with INSERT, UPDATE and SELECT, CVSS 4.3) and CVE-2026-116311 (DROP OWNED can remove restrictive RLS policies, CVSS 5.4). Our lab role has exactly the privilege set the first one describes, but we didn’t test either CVE. Our seven routes are configuration, not bugs. We also ran 18.6, not 18.7. According to the versioning policy, 14 reached end of life with 14.25, and it has no security_invoker anyway.

Postgres row level security for multi-tenant apps: what to do, in order

  1. Split the roles. Migrations run as the owner. The app runs as a NOSUPERUSER, NOBYPASSRLS role with DML grants only.
  2. Put FORCE ROW LEVEL SECURITY on every tenant table. Owner-run maintenance scripts will now see filtered rows, so run them as a dedicated role or set the context explicitly.
  3. Set tenant context per transaction: one client, BEGIN, set_config(..., true), query, COMMIT. Use nullif so a missing value returns zero rows.
  4. Make views security_invoker = true and functions SECURITY INVOKER. Where DEFINER is needed, filter by tenant inside it. Invoker views need the caller to have grants on the base tables.
  5. Use UNIQUE (tenant_id, slug), and random IDs for anything user-visible.
  6. Run the audit query in CI against a migrated test database and fail on new rows, with an allowlist for the intentional ones.
  7. Add a two-tenant test to your suite: a user from tenant B hits every endpoint and must see zero tenant A rows, including under concurrency.

This is the same pattern we saw in our vibe-coding study, flipped. There the authorization code held and the defaults around it didn’t. Here the policy holds and the database plumbing doesn’t. If you use Supabase JWT claims to carry the tenant, our JWT mistakes post covers what to check on the token side, and if tenants reach your data through an MCP server, our MCP server OAuth security post is relevant.

What we didn’t test

One app, one stack (Node and node-postgres). No other drivers or ORMs, no PgBouncer, no Supabase project. L3 depends on how the app sets context rather than on the driver, but we haven’t shown that on another stack. We didn’t test timing side channels, column-level exposure, materialized views or performance. And we wrote the vulnerable app ourselves, so this shows how each mistake works, not how often it appears in real codebases.

FAQ

Does Postgres RLS apply to the table owner?

Not by default. Owners skip RLS unless the table has FORCE ROW LEVEL SECURITY. Superusers and BYPASSRLS roles skip it even then, so the role your app connects as matters as much as the policy. We saw both cases in the lab.

Is it safe to use SET for the tenant id with a connection pool?

Not at session level. The setting stays on the pooled connection after your request ends, and the next request inherits it. Use set_config(..., true) or SET LOCAL inside the same transaction, on the same client, as the query. We measured 33 to 103 leaked responses per 200 requests before the fix, and 0 after.

Can one tenant learn about another’s data with RLS on?

Yes, through unique and foreign key checks, which bypass RLS. Our 409 versus 201 test answered “does this exist?” for another tenant without returning a row. Make unique constraints per tenant, for example UNIQUE (tenant_id, slug), so a duplicate in one tenant never depends on another.

Is RLS enough for tenant isolation?

It’s a strong backstop, not the whole design. OWASP still says to keep tenant-scoped requests on a least-privileged role and fail closed when context is missing. You also need application checks and a two-tenant test that runs on every build.

Want a human to try this on your app?

This is what our web and API pentests do: log in as one tenant and try to reach another’s data, through the policy and around it. Tenant isolation is a standard line on enterprise security questionnaires, and if SOC 2 is on your list, our SOC 2 pentest guide covers what auditors look for. Your policy is probably fine. Check what runs around it, or start with a free external snapshot, no access needed.

Last updated 13 November 2026. Tested 13 November 2026 by the NoMoreBreach Team on PostgreSQL 18.6. All testing was on our own local lab. Keys and secrets are redacted.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *