In PostgreSQL, a tasks policy compares org_id with current_setting('app.org_id', true)::uuid; why does set_config's is_local argument matter, and what can current_setting return?
answer
- a two-part custom setting name
- transaction scope versus session scope
- NULL before, empty string after
- fail closed with NULLIF
basics
~20 sset_config('app.org_id', id, true) keeps the tenant only until the transaction ends, so it cannot leak to the next request on a reused connection. current_setting(name, true) returns NULL if never set, but an empty string after a local value expires.
solid answer
~50 sAny two-part name such as `app.org_id` is accepted as a placeholder setting. `set_config(name, value, is_local)` is the function form of `SET`: with `is_local = true` it behaves like `SET LOCAL` and reverts at commit or rollback, and with `false` it lasts for the session, so it reaches whatever request borrows the connection next (the pooler side is PgBouncer's). In autocommit, a standalone `SELECT set_config(..., true)` is its own transaction, so the value is gone before the next statement: wrap each request in `BEGIN ... COMMIT`. `current_setting(name, true)` returns NULL for a name never set in the session, but an empty string after a local value expires, and `''::uuid` is an error. Write `NULLIF(current_setting('app.org_id', true), '')::uuid` so an unset tenant compares as NULL and rows stay hidden. Any client can set the parameter, so it is not authentication.
code
sql · 10 linesCREATE POLICY org_isolation ON tasks
USING (org_id = NULLIF(current_setting('app.org_id', true), '')::uuid);
-- an ALL policy reuses USING as its WITH CHECK
BEGIN;
SELECT set_config('app.org_id', $1, true); -- $1 bound by the driver
SELECT id, title FROM tasks WHERE project_id = $2;
COMMIT;
SELECT current_setting('app.org_id', true); -- now '' (empty string), not NULLgo deeper
Know that a policy can read a custom two-part setting with current_setting, and that set_config writes it.
Explain is_local, why a standalone call in autocommit vanishes, and the three things current_setting can return over a session's life.
Write the fail-closed expression with NULLIF, scope the tenant to each request's transaction on pooled connections, and say plainly that the setting relies on the application's word.
Decide whether the application's word is enough for tenant identity, or whether per-tenant roles are worth their operational cost.
## A custom setting as the tenant carrier A multi-tenant project-management app usually connects every request as one database role, `app_rw`. Policies therefore need some other way to learn which organization the request is for. PostgreSQL's usual answer is a **custom configuration parameter**: - The server accepts a setting for any **two-part name** (`app.org_id`), even though no extension defines it. The value is kept as a string **placeholder**. - Placeholders are **user-settable**. Any session can set one with `SET` or `set_config`, and any expression can read it with `current_setting`. - `current_setting` is a `STABLE` function, so its value is fixed within one statement. A policy such as `org_id = ...current_setting(...)::uuid` can still use an index on `org_id`, because uuid equality is leakproof and the function receives no column values. ## Session scope versus transaction scope The third argument of `set_config(setting_name, new_value, is_local)` decides how long the value lives: | Call | Lasts until | Under autocommit | |---|---|---| | `set_config('app.org_id', v, false)` or `SET app.org_id = ...` | session end or `RESET` | persists and reaches the next borrower of the connection | | `set_config('app.org_id', v, true)` | end of the current transaction | gone after its own statement | | `SET LOCAL app.org_id = ...` | end of the current transaction | warning, then no effect | So `is_local = true` only helps inside an explicit transaction that also contains the request's queries. That transaction scoping is what makes the tenant safe on a connection that a pool hands to someone else next. How a pooler resets session state is the PgBouncer leaf's subject. `set_config` has one more practical edge over `SET LOCAL`. `SET` takes its value as literal SQL text, so a driver would have to splice the tenant id into the statement. `set_config` is an ordinary function, so the id travels as a **bind parameter**. ## What current_setting returns `current_setting(setting_name, missing_ok)` behaves differently over a session's life: 1. **Never set in this session:** with `missing_ok = true` it returns `NULL`. Without it, it raises `unrecognized configuration parameter "app.org_id"`. 2. **Set in the current transaction or session:** it returns the string that was set. 3. **Set locally in an earlier, finished transaction:** the placeholder still exists, its value has reverted to unset, and `current_setting` returns an **empty string**, not `NULL`. State 3 is the one that bites. A policy written as `current_setting('app.org_id', true)::uuid` works in testing and then fails with an invalid-input error for type uuid on the second request a pooled connection serves without a tenant. ## Failing closed The policy should deny, not crash, when no tenant is set: - `NULLIF(current_setting('app.org_id', true), '')::uuid` turns both NULL and the empty string into `NULL`. - `org_id = NULL` is NULL, not true. In `USING` that hides the row, and in `WITH CHECK` it makes the write fail with the row-level security error. - `COALESCE(..., '')::uuid` gets this backwards, because it manufactures the empty string the cast rejects. - Keep the expression identical in `USING` and `WITH CHECK`, or omit `WITH CHECK` on an `ALL` policy so the `USING` expression is reused. ## What the setting cannot protect against The parameter carries the application's claim about the tenant, nothing more: - Any SQL the role can run, including an injected statement, can call `set_config` with another tenant's id. - Superusers, `BYPASSRLS` roles and the table owner (without `FORCE`) ignore the policy whatever the setting says. - If the tenant must come from something the session cannot rewrite, base the policy on the role itself (`current_user`), with one role per tenant. ## A request's lifecycle 1. `BEGIN`. 2. `SELECT set_config('app.org_id', $1, true)` with the authenticated tenant bound as `$1`. 3. Run the request's queries. Every policy reads the same tenant. 4. `COMMIT` or `ROLLBACK`. The tenant is gone, and the next borrower of the connection starts from an empty string. 5. In tests, cover the empty-tenant path on purpose. After a `COMMIT`, run a query on the same connection without setting a tenant and expect zero rows and a failing insert, not a cast error and not another tenant's data. A pool that hands each request a fresh transaction makes steps 1 and 4 natural. A pool that runs several requests in one transaction does not, and the tenant then has to be set again before every request's first statement.
- Why prefer set_config over SET LOCAL for the tenant id?Both scope the value to the transaction. But `SET` takes its value as literal SQL, so the driver would have to splice the tenant id into the statement text, whereas `set_config` accepts it as a bind parameter. Outside a transaction block `SET LOCAL` warns and does nothing, and `set_config(..., true)` lasts only for its own statement. Either way, open the transaction first.
- Can the application's database role change app.org_id itself, and what does that imply?Yes. Placeholder settings are user-settable, so any statement the role can run, including an injected one, can call `set_config` with another tenant's id. The setting carries the application's word, not a verified identity. If that is not enough, base the policy on something the session cannot rewrite, such as `current_user` with a role per tenant.
- Does a policy calling current_setting stop an index on tasks.org_id from being used?No. `current_setting` is `STABLE` and receives no column values, and uuid equality is leakproof. The planner can therefore compute the comparison value once and use an index on `org_id`, or a composite index that leads with it, for the policy predicate.
- set_config with is_local false is safe on pooled connections
- current_setting with missing_ok always returns NULL when no tenant is set
- SET LOCAL outside a transaction block keeps the value for the session
- A custom setting like app.org_id must be declared in postgresql.conf first
- Only superusers can change app.org_id, so it is tamper-proof