Sub topic 15
Pitfalls: connection pools, side channels, and foreign keys
This chapter assumes you can write tenant policies like the ones in the earlier chapters. You should know current_setting, set_config, FORCE ROW LEVEL SECURITY, and how USING and WITH CHECK differ. The policies themselves are usually fine. The failures happen around them: how the application sets the tenant, what the planner and error messages reveal, and which internal checks skip RLS.
Connection pools carry session state between users
A pooler such as PgBouncer or an application-side pool keeps database connections open and hands them to different requests. Session state set on a connection stays on it. If your policy reads app.tenant_id, the value must not outlive the request that set it.
The third argument of set_config decides how long the value lives:
falsekeeps the value for the whole session, which is the connection.truekeeps it only until the end of the current transaction.
The unsafe pattern looks like this:
-- Request A, on pooled connection 1
SELECT set_config('app.tenant_id', '3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b', false);
SELECT count(*) FROM invoices;
-- Request B is later given connection 1 and forgets to set a tenant
SELECT count(*) FROM invoices; -- still sees tenant A's rowsThe fix is to set the tenant inside every transaction with is_local = true, as in the earlier chapter:
BEGIN;
SELECT set_config('app.tenant_id', '3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b', true);
SELECT id, amount_cents FROM invoices;
COMMIT;Several related details matter here.
- Transaction pooling mode. In PgBouncer's transaction mode, the server connection can change between transactions. Session-level
SETis unreliable there, so use transaction-local settings only. - Autocommit. Outside an explicit
BEGIN, each statement is its own transaction. Aset_config(..., true)in autocommit expires immediately, so the next statement sees no tenant. Always wrap the setting and the queries in one transaction. - Empty string instead of NULL. Once a custom setting has been used in a session, it reverts to an empty string, not to unset, after the transaction ends. That is why the policy uses
NULLIF(current_setting('app.tenant_id', true), '')::uuid. WithoutNULLIF, the cast of''touuidraises an error. With it, the policy compares againstNULLand matches no rows, which is the safe default. - Connection reset. If you cannot avoid session-level state, run
DISCARD ALLwhen a connection returns to the pool. PgBouncer'sserver_reset_querycan do this. It is a safety net. It does not replace transaction-local settings.
A second pool-related risk is the role the pool connects as. If the application connects as the table owner or a superuser, RLS is bypassed (or not enforced) no matter what you set. Connect as a plain role without BYPASSRLS, and use FORCE ROW LEVEL SECURITY if the owner must be covered.
Side channels: information can leak without returning rows
RLS controls which rows a query returns. It does not hide everything a query can reveal.
Functions in the WHERE clause
A user can write WHERE some_function(col). If the planner ran that function before the policy filter, the function would see rows the user may not read, and could leak them through a RAISE NOTICE or an error message. PostgreSQL prevents this by treating policy expressions as security barriers. A user-defined function is evaluated only after the policy qual unless the function is marked LEAKPROOF.
CREATE FUNCTION noisy(text) RETURNS boolean
LANGUAGE plpgsql COST 0.0000001 AS $$
BEGIN
RAISE NOTICE 'saw %', $1;
RETURN true;
END $$;
SET ROLE bob;
SELECT title FROM documents WHERE noisy(title); -- notices only for rows bob may see
RESET ROLE;LEAKPROOF is a promise that a function reveals nothing about its arguments through errors or side effects. Only superusers can set it, because the planner trusts the promise and may then run the function before the policy. Audit the existing ones:
SELECT proname, pronamespace::regnamespace
FROM pg_proc
WHERE proleakproof
ORDER BY 2, 1;Do not mark your own functions LEAKPROOF for convenience. A function that can raise an error on bad input is not leakproof.
Errors and constraint violations
Constraints are checked against all rows, including rows the role cannot see. A unique index on a column that holds hidden values turns an INSERT into a probe:
SET ROLE bob;
INSERT INTO documents (title) VALUES ('Alice notes');
-- if the table had UNIQUE (title), this would fail with
-- ERROR: duplicate key value violates unique constraint
-- DETAIL: Key (title)=(Alice notes) already exists.The error confirms that another owner has a document with that title. Reduce this exposure in these ways:
- Make unique keys include the tenant, such as
UNIQUE (tenant_id, title). A duplicate can then only collide with your own rows. - Prefer opaque keys such as UUIDs or sequence values over meaningful business values.
- Avoid returning raw database error text to end users.
Timing and statistics
Query timing can hint at how many hidden rows exist, since a scan still visits them. Planner statistics in pg_stats, such as most common values, are built from all rows. PostgreSQL restricts pg_stats so users only see statistics for columns they can read, but the planner still uses the full statistics when estimating. Treat these as low-bandwidth channels. If your threat model includes them, RLS alone is not enough, and separate schemas or databases per tenant are the stronger option.
Referential integrity checks bypass RLS
Foreign key checks, and the cascading actions behind ON DELETE CASCADE, run as the owner of the table and ignore RLS. This is deliberate, since integrity must hold across all rows. It also means a foreign key can reveal or touch rows a role cannot see.
CREATE TABLE comments (
id bigserial PRIMARY KEY,
document_id bigint NOT NULL REFERENCES documents (id),
body text
);
GRANT INSERT ON comments TO bob;
GRANT USAGE ON SEQUENCE comments_id_seq TO bob;
SET ROLE bob;
INSERT INTO comments (document_id, body) VALUES (1, 'hi');
-- succeeds if document 1 exists, even though bob cannot see it
INSERT INTO comments (document_id, body) VALUES (999999, 'hi');
-- ERROR: insert or update on table "comments" violates foreign key constraint
RESET ROLE;Bob can now tell which document IDs exist, and he can attach a comment to a document he does not own. A cascading delete from the parent side also removes child rows regardless of the child table's policies.
The robust design is a composite key that carries the tenant, so a child row can only reference a parent in the same tenant:
CREATE TABLE projects (
tenant_id uuid NOT NULL,
id bigint NOT NULL,
name text NOT NULL,
PRIMARY KEY (tenant_id, id)
);
CREATE TABLE tasks (
tenant_id uuid NOT NULL,
id bigint NOT NULL,
project_id bigint NOT NULL,
title text NOT NULL,
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, project_id) REFERENCES projects (tenant_id, id)
);With this schema, a task can never point at another tenant's project. The WITH CHECK policy on tasks already forces tenant_id to match the session tenant, and the foreign key then forces the project to be in that same tenant.
Other places RLS does not reach
| Situation | What happens | What to do |
|---|---|---|
| `pg_dump` by a role subject to RLS | Dump fails by default rather than silently omitting rows | Dump as a role that bypasses RLS, or knowingly use `--enable-row-security` |
| Views owned by an exempt role | View runs with owner privileges and can expose all rows | Use `security_invoker = true` (PostgreSQL 15 and later) |
| Superusers and `BYPASSRLS` roles | Policies are never applied | Never use these roles for application connections |
| Table owner without `FORCE` | Policies are skipped for the owner | Add `ALTER TABLE ... FORCE ROW LEVEL SECURITY` |
A checklist before you ship
- The application role is not a superuser, not the owner, and has no
BYPASSRLS. - Every request sets its tenant with
set_config(..., true)inside the same transaction as its queries. - An unset tenant matches no rows, because the policy uses
NULLIFand a missing-okcurrent_setting. - Unique keys and foreign keys include the tenant column.
- No custom function is marked
LEAKPROOF. - You have a test that connects as each role and confirms that cross-tenant reads, writes, and references fail.
Exercise
An application sets the tenant with SELECT set_config('app.tenant_id', $1, false) on a pooled connection, then runs its queries. Describe the failure, and give the corrected statement and the structure it must run in.
Show answer
With is_local = false the value lasts for the whole session, so when the pool hands the same connection to another request, that request runs with the previous tenant's ID unless it sets its own. Use set_config('app.tenant_id', $1, true) inside an explicit transaction: BEGIN; SELECT set_config('app.tenant_id', $1, true); ...queries...; COMMIT;. The value is discarded at the end of the transaction, and the policy's NULLIF(..., '') makes an unset tenant match no rows.
Exercise
A role cannot see any rows in documents, yet inserting a comments row with document_id = 1 succeeds, while document_id = 999999 fails. What does this reveal, and how do you prevent it?
Show answer
Foreign key checks run as the table owner and ignore RLS, so success versus failure reveals whether a document with that ID exists, and lets the role attach data to a document it cannot see. Prevent it by including the tenant in the keys: make the parent's primary key (tenant_id, id) and the child's foreign key (tenant_id, document_id), with a WITH CHECK policy forcing tenant_id to the session tenant.