Sub topic 9
Passing the current user or tenant into a policy
This chapter assumes you can write a basic CREATE POLICY with USING and WITH CHECK, and that you know how GRANT and SET ROLE work. A policy is only as useful as the facts it can see. The policy needs to know who is asking, and in a shared-table design it must also know which tenant that person belongs to.
Three sources of identity
A policy expression can use any expression that is valid in a WHERE clause. Three sources of identity are common.
| Source | Example | Who sets it | Best for |
|---|---|---|---|
| Role name | `owner_name = current_user` | PostgreSQL, from the login or `SET ROLE` | One database role per person or per tenant |
| Session setting | `current_setting('app.tenant_id', true)` | Your application | Many tenants behind one shared application role |
| Lookup table | `tenant_id IN (SELECT ...)` | Rows in a mapping table | Users that belong to several tenants |
The lookup-table approach is covered in a later chapter. This chapter covers the first two.
Role names: current_user and session_user
PostgreSQL tracks two identities. session_user is the role that logged in. current_user is the role whose privileges apply right now, and SET ROLE changes it. Policies are evaluated against current_user, which is why the earlier SET ROLE alice tests work.
SET ROLE alice;
SELECT current_user, session_user;
-- current_user = alice, session_user = the role you logged in as
RESET ROLE;Comparing a column to current_user is simple and needs no cooperation from the application. It has two costs. Every person or tenant needs a database role, and a connection pool cannot share one connection among many roles without issuing SET ROLE each time. For a few dozen internal users this is fine. For thousands of end users it is not practical.
Custom settings: carrying a tenant id
Most web applications connect as one role, such as app_user, and keep their own list of users and tenants. For that design, you pass the tenant into the session as a custom setting. A custom setting is a configuration parameter whose name has a prefix and a dot, such as app.tenant_id. PostgreSQL lets any session set a parameter with a dotted name without declaring it first.
You write a value with set_config and read it back with current_setting:
SELECT set_config('app.tenant_id', '3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b', false);
SELECT current_setting('app.tenant_id');The third argument of set_config is is_local. With false, the value lasts for the whole session. With true, it lasts only until the current transaction ends. The next section explains why you almost always want true.
Why current_setting needs missing_ok
current_setting takes an optional second argument, missing_ok. Its behavior differs depending on that flag.
current_setting('app.tenant_id')raisesunrecognized configuration parameterif the setting was never set in this session.current_setting('app.tenant_id', true)returnsNULLin that case.
There is a second quirk. Once a session has set a custom parameter, even transaction-locally, the name stays known to that session. After the transaction ends, current_setting(..., true) returns an empty string, not NULL. Casting an empty string to uuid raises an error. The NULLIF wrapper used in the invoice example handles both cases:
NULLIF(current_setting('app.tenant_id', true), '')::uuidAn unset value becomes NULL. The comparison tenant_id = NULL is never true, so the policy matches no rows. The query returns zero rows and does not fail, and that is the safe default. This behavior is called failing closed.
Wrapping the expression in a function
Repeating that expression in every USING and WITH CHECK clause invites typos. A small function keeps the logic in one place:
CREATE FUNCTION app_tenant_id() RETURNS uuid
LANGUAGE sql
STABLE
AS $$
SELECT NULLIF(current_setting('app.tenant_id', true), '')::uuid
$$;Mark it STABLE. The result cannot change within one statement, which lets the planner treat it as constant for the scan. It cannot be IMMUTABLE, because the value differs between sessions.
Here is a complete example on a fresh table. It uses a shared application role and a function-based policy:
CREATE ROLE app_user NOLOGIN;
CREATE TABLE projects (
id bigserial PRIMARY KEY,
tenant_id uuid NOT NULL DEFAULT app_tenant_id(),
name text NOT NULL
);
CREATE INDEX projects_tenant_id_idx ON projects (tenant_id);
GRANT SELECT, INSERT, UPDATE, DELETE ON projects TO app_user;
GRANT USAGE ON SEQUENCE projects_id_seq TO app_user;
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON projects
TO app_user
USING (tenant_id = (SELECT app_tenant_id()))
WITH CHECK (tenant_id = (SELECT app_tenant_id()));Two details are worth noting. The DEFAULT app_tenant_id() fills in the tenant on insert, so application code does not need to pass it. That default and the WITH CHECK clause agree by construction. The (SELECT app_tenant_id()) form wraps the call in a scalar subquery. PostgreSQL evaluates such a subquery once per statement, as an initial plan, instead of once per row. For a cheap function the saving is small, but it is a harmless habit for policies on large tables.
Scoping the value to a transaction
Connection pools hand the same physical connection to different requests. If you set the tenant with a session-level SET and forget to clear it, the next request inherits the previous tenant's data. This is the most damaging mistake in this pattern.
The safe approach is to set the value inside each transaction with is_local = true. It disappears automatically at COMMIT or ROLLBACK.
BEGIN;
SELECT set_config('app.tenant_id', '3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b', true);
INSERT INTO projects (name) VALUES ('Website redesign');
SELECT id, name FROM projects;
COMMIT;
SELECT count(*) FROM projects; -- as app_user, outside the transaction: 0 rows visibleSET LOCAL app.tenant_id = '...' does the same thing, but it cannot take a bind parameter. Use set_config so your driver can pass the tenant id as a parameter, for example SELECT set_config('app.tenant_id', $1, true). That also avoids building SQL by string concatenation.
The request flow looks like this:
Limits of the setting-based approach
The setting is not authenticated. Any session can run SET app.tenant_id = '...' for itself, and the database cannot tell whether the application or an attacker typed it. This approach is therefore safe only when the application is the sole author of the SQL that runs on that connection. If an attacker achieves SQL injection through app_user, they can change the setting and read another tenant's rows.
If end users can run their own SQL, such as a reporting tool or a shared analytics console, use real roles and current_user. You can also combine both: use one role per tenant, then put the role name in a mapping table and look it up in the policy.
Checking that the context arrives
When a policy returns no rows, first check whether the setting reached the session. This test shows the three states:
BEGIN;
SELECT current_setting('app.tenant_id', true); -- NULL or '' means nothing was set
SELECT set_config('app.tenant_id', '3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b', true);
SELECT app_tenant_id(); -- the uuid
ROLLBACK;If the value is set correctly and rows are still missing, the policy may not apply to your role, or a restrictive policy may be hiding them. The testing chapter covers those checks.
Summary of the decision
- Use
current_userwhen each person or tenant has a database role. - Use a transaction-local
current_settingwhen one application role serves many tenants and the application is trusted to set the context. - Always pass
trueasmissing_ok, wrap the value inNULLIF(..., ''), and cast to the column type so an unset context returns zero rows. - Always use
is_local = truewith connection pools.
Exercise
A request handler runs SELECT set_config('app.tenant_id', $1, false) at the start of each request and never resets it. The pool uses transaction-level pooling. Name two ways this can expose another tenant's rows, and give the one-word change that fixes the call.
Show answer
Because the setting lasts for the whole server session, a later request that borrows the same server connection and forgets to set the tenant (or fails before setting it) runs with the previous tenant's id. Under transaction-level pooling, a client's own statements may also be sent to a different server connection than the one where the setting was made, so it may see another client's value or none. Change the third argument from false to true and run the call inside the same transaction as the queries it protects, so the value is discarded at commit.
Exercise
With no earlier set_config call in the session, what does SELECT current_setting('app.tenant_id', true) return, and what does SELECT current_setting('app.tenant_id') do? Why does the policy use NULLIF(..., '') as well?
Show answer
The first query returns NULL. The second raises "unrecognized configuration parameter". After a transaction-local set_config has ended, the name is still known to the session and the setting reads as an empty string, which cannot be cast to uuid. NULLIF(..., '') turns the empty string into NULL, so the comparison matches no rows instead of raising an error.